// // Example location script for 2BrightSparks SyncBackPro: NASA Images. // // SBLang=Pascal // // http://www.2BrightSparks.com/ // November 2026 // // NASA Images is a read-only location made from the NASA Image and Video // Library (https://images.nasa.gov/). Each search you set up is a folder, and // each picture the search finds is two files in it: // // \Nebula\2011-08-10 Weighing in on the Dumbbell Nebula.jpg // \Nebula\2011-08-10 Weighing in on the Dumbbell Nebula.txt (who, what, where) // // Pictures are only downloaded when SyncBack copies them, and are then kept // (in the Root folder below), so a second run downloads nothing. // // Using it // -------- // Make a new Backup profile that copies FROM NASA Images, with the path \, TO // a folder such as D:\Pictures\NASA\. A location script is always the // destination of a profile, so SyncBack sets it up as "Backup, destination to // source" for you. A search's results change over time as NASA adds pictures: // a Backup keeps the ones that drop out, a Mirror removes them. // // Settings // -------- // Each profile that uses NASA Images has a NASA Images page in its profile // setup: // // Searches Separated by semicolons; each one is a folder // (blank = Nebula; Hubble; Apollo 11) // Pictures Pictures per search (1 to 100, default 25) // Size Small, Medium, Large or Original (can be huge) // Hours How long to keep search results before asking again // Folder Where downloads are kept (blank = %LOCALAPPDATA%\SyncBack NASA Images\) // // It needs curl.exe, which is part of Windows 10 (version 1803 or later) and // Windows 11, to download the pictures. // // Insider Access // -------------- // This script needs SyncBackPro V12 with Insider Access. It uses these // Insider Access functions (they will be in every SyncBackPro V13): // // SBSystem.HTTPRequest To ask the library for each search's results // JSON.parse To read the results // var gFSO, gRoot, gCurl, gSearches, gCount, gSize, gCacheHours; const READ_ONLY = 'NASA Images is read-only'; API = 'https://images-api.nasa.gov/search?media_type=image'; ASSETS = 'https://images-assets.nasa.gov/image/'; // // This is a location script // function Description(var ScriptType): String; begin Result:='NASA Images'; ScriptType:=SCRIPTTYPE_LOCATION + SCRIPTTYPE_CONFIG; end; function Install(Interactive); begin Result:=''; end; procedure Uninstall; begin end; function FilesToExport(Interactive, Cnt); begin Result:=''; end; //----------------------------------------------------------------------------- // Helpers //----------------------------------------------------------------------------- procedure ForceDir(D); var P; begin D:=ExcludeTrailingPathDelimiter(D); if (D = '') or DirectoryExists(D) then Exit; P:=ExtractFilePath(D); if (P <> '') and (ExcludeTrailingPathDelimiter(P) <> D) then ForceDir(P); CreateDir(D); end; // Make text safe to use as a file or folder name function SafeName(s); var i, c, r; begin r:=''; for i:=1 to Length(s) do begin c:=Copy(s, i, 1); if (Pos(c, '\/:*?"<>|') > 0) or (Ord(c) < 32) then r:=r + ' ' else r:=r + c; end; // No double spaces, and no space or dot at the end while (Pos(' ', r) > 0) do r:=ReplaceStr(r, ' ', ' '); r:=Trim(r); if (Length(r) > 100) then r:=Trim(Copy(r, 1, 100)); while (r <> '') and ((Copy(r, Length(r), 1) = '.') or (Copy(r, Length(r), 1) = ' ')) do r:=Copy(r, 1, Length(r) - 1); Result:=r; end; // Percent-encode text for a URL function UrlEncode(s); var i, c, r; begin r:=''; for i:=1 to Length(s) do begin c:=Copy(s, i, 1); if ((c >= 'A') and (c <= 'Z')) or ((c >= 'a') and (c <= 'z')) or ((c >= '0') and (c <= '9')) or (Pos(c, '-_.~') > 0) or (Ord(c) > 127) then r:=r + c else r:=r + '%' + IntToHex(Ord(c), 2); end; Result:=r; end; // Read the profile's NASA Images settings procedure LoadSettings; var s, p, Value, Shell; begin gRoot:=Trim(SBVariables.GetProperty('NasaRoot', '', FALSE)); gCount:=StrToIntDef(Trim(SBVariables.GetProperty('NasaCount', '', FALSE)), 25); gSize:=LowerCase(Trim(SBVariables.GetProperty('NasaSize', '', FALSE))); gCacheHours:=StrToIntDef(Trim(SBVariables.GetProperty('NasaCacheHours', '', FALSE)), 24); // The searches are separated by semicolons gSearches:=TStringList.Create; s:=SBVariables.GetProperty('NasaSearches', '', FALSE); while (s <> '') do begin p:=Pos(';', s); if (p = 0) then p:=Length(s) + 1; Value:=Trim(Copy(s, 1, p - 1)); s:=Copy(s, p + 1, Length(s)); if (SafeName(Value) <> '') and (gSearches.IndexOf(Value) < 0) then gSearches.Add(Value); end; if (gSearches.Count = 0) then begin gSearches.Add('Nebula'); gSearches.Add('Hubble'); gSearches.Add('Apollo 11'); end; if (gCount < 1) then gCount:=1; if (gCount > 100) then gCount:=100; if (gSize <> 'small') and (gSize <> 'medium') and (gSize <> 'large') and (gSize <> 'orig') then gSize:='medium'; Shell:=CreateOleObject('WScript.Shell'); if (gRoot = '') then gRoot:='%LOCALAPPDATA%\SyncBack NASA Images\'; gRoot:=IncludeTrailingPathDelimiter(Shell.ExpandEnvironmentStrings(gRoot)); gCurl:=Shell.ExpandEnvironmentStrings('%SystemRoot%\System32\curl.exe'); Shell:=Unassigned; end; // The search whose folder is called Folder, or blank function SearchFor(Folder); var i; begin Result:=''; for i:=0 to gSearches.Count - 1 do if SBSystem.SameFilenames(SafeName(gSearches[i]), Folder, FALSE) then begin Result:=gSearches[i]; Exit; end; end; // Split a location path such as \Nebula\name.jpg into its folder and name procedure SplitPath(P; var Folder, Name); var i; begin while (Copy(P, 1, 1) = '\') do P:=Copy(P, 2, Length(P)); i:=Pos('\', P); if (i = 0) then begin Folder:=P; Name:=''; end else begin Folder:=Copy(P, 1, i - 1); Name:=Copy(P, i + 1, Length(P)); if (Copy(Name, Length(Name), 1) = '\') then Name:=Copy(Name, 1, Length(Name) - 1); end; end; // Where a picture's description and the picture itself are kept function TextFile(Id); begin Result:=gRoot + 'text\' + SafeName(Id) + '.txt'; end; function ImageFile(Id); begin Result:=gRoot + 'images\' + SafeName(Id) + '~' + gSize + '.jpg'; end; //----------------------------------------------------------------------------- // Searching //----------------------------------------------------------------------------- // // The results of a search, from the cache if they are recent enough, else // from the library. Returns the JSON text, or blank with ErrMsg set. // function SearchResults(Search; var ErrMsg); var Cache, Status, Body, Age; begin Result:=''; ErrMsg:=''; Cache:=gRoot + 'searches\' + SafeName(Search) + '.json'; if gFSO.FileExists(Cache) then begin Age:=(Now - gFSO.GetFile(Cache).DateLastModified) * 24; if (Age < gCacheHours) then begin Result:=ReadStringFromFile(Cache); Exit; end; end; Body:=''; Status:=SBSystem.HTTPRequest('GET', API + '&page_size=' + IntToStr(gCount) + '&q=' + UrlEncode(Search), '', '', 60, Body); if (Status <> 200) then begin // Better old results than none if gFSO.FileExists(Cache) then Result:=ReadStringFromFile(Cache) else if (Status < 0) then ErrMsg:=Body else ErrMsg:='The NASA library said ' + IntToStr(Status) + ' for "' + Search + '"'; Exit; end; ForceDir(gRoot + 'searches\'); WriteStringToFile(Cache, Body); Result:=Body; end; // // The files in a search's folder, one line each: // Name nasa_id date (ISO 8601) kind (jpg or txt) // The text of each .txt file is written to \text\ as a side effect. // function FolderItems(Search, L; var ErrMsg); var Text, V, Items, i, Id, Title, Created, Base, Names, n, Info, Keys, k, KeyList; begin Result:=FALSE; L.Clear; Text:=SearchResults(Search, ErrMsg); if (Text = '') then Exit; ForceDir(gRoot + 'text\'); Names:=TStringList.Create; V:=JSON.parse(Text); try Items:=V.GetObject('collection.items'); try for i:=0 to Items.Count - 1 do begin Id:=VarToStr(Items.Get('[' + IntToStr(i) + '].data[0].nasa_id')); if (Id = '') then Continue; Title:=VarToStr(Items.Get('[' + IntToStr(i) + '].data[0].title')); Created:=VarToStr(Items.Get('[' + IntToStr(i) + '].data[0].date_created')); // , made unique within the folder Base:=SafeName(Copy(Created, 1, 10) + ' ' + Title); if (Base = '') then Base:=SafeName(Id); n:=1; while (Names.IndexOf(UpperCase(Base)) >= 0) do begin n:=n + 1; Base:=SafeName(Copy(Created, 1, 10) + ' ' + Title) + ' (' + IntToStr(n) + ')'; end; Names.Add(UpperCase(Base)); L.Add(Base + '.jpg' + #9 + Id + #9 + Created + #9 + 'jpg'); L.Add(Base + '.txt' + #9 + Id + #9 + Created + #9 + 'txt'); // The description file (only rewritten if it changed, to keep its date) KeyList:=''; if Items.Has('[' + IntToStr(i) + '].data[0].keywords') then begin Keys:=Items.GetObject('[' + IntToStr(i) + '].data[0].keywords'); try for k:=0 to Keys.Count - 1 do begin if (KeyList <> '') then KeyList:=KeyList + ', '; KeyList:=KeyList + VarToStr(Keys.Item(k)); end; finally Keys.Free; end; end; Info:='Title: ' + Title + #13#10 + 'Date: ' + Copy(Created, 1, 10) + #13#10 + 'NASA ID: ' + Id + #13#10 + 'Center: ' + VarToStr(Items.Get('[' + IntToStr(i) + '].data[0].center')) + #13#10 + 'Photographer: ' + VarToStr(Items.Get('[' + IntToStr(i) + '].data[0].photographer')) + #13#10 + 'Keywords: ' + KeyList + #13#10 + 'Link: https://images.nasa.gov/details/' + UrlEncode(Id) + #13#10 + #13#10 + VarToStr(Items.Get('[' + IntToStr(i) + '].data[0].description')) + #13#10; if not gFSO.FileExists(TextFile(Id)) or (ReadStringFromFile(TextFile(Id)) <> Info) then WriteStringToFile(TextFile(Id), Info); end; finally Items.Free; end; finally V.Free; Names.Free; end; Result:=TRUE; end; // Find a file in a folder. Returns the line, or blank. function FindItem(Path; var ErrMsg); var Folder, Name, Search, L, i; begin Result:=''; ErrMsg:=''; SplitPath(Path, Folder, Name); Search:=SearchFor(Folder); if (Search = '') or (Name = '') then Exit; L:=TStringList.Create; try if FolderItems(Search, L, ErrMsg) then for i:=0 to L.Count - 1 do if SBSystem.SameFilenames(Copy(L[i], 1, Pos(#9, L[i]) - 1), Name, FALSE) then begin Result:=L[i]; Exit; end; finally L.Free; end; end; // The Idx'th tab-separated field of a line function Field(Line, Idx); var i, p, s; begin s:=Line; for i:=1 to Idx do begin p:=Pos(#9, s); if (p = 0) then begin Result:=''; Exit; end; s:=Copy(s, p + 1, Length(s)); end; p:=Pos(#9, s); if (p = 0) then Result:=s else Result:=Copy(s, 1, p - 1); end; // Download a picture into the cache (if it is not already there) function Download(Id); var Url, Tmp, RetVal, ErrMsg, Sizes, i; begin Result:=''; if gFSO.FileExists(ImageFile(Id)) then Exit; if not gFSO.FileExists(gCurl) then begin Result:='Cannot download pictures: ' + gCurl + ' is missing (it is part of Windows 10 version 1803 and later)'; Exit; end; ForceDir(gRoot + 'images\'); Tmp:=ImageFile(Id) + '.part'; // Not every picture has every size, so fall back to the others Sizes:=TStringList.Create; try Sizes.Add(gSize); if (gSize <> 'medium') then Sizes.Add('medium'); if (gSize <> 'large') then Sizes.Add('large'); if (gSize <> 'orig') then Sizes.Add('orig'); if (gSize <> 'small') then Sizes.Add('small'); for i:=0 to Sizes.Count - 1 do begin Url:=ASSETS + UrlEncode(Id) + '/' + UrlEncode(Id) + '~' + Sizes[i] + '.jpg'; RetVal:=0; ErrMsg:=''; DeleteFile(Tmp); if SBSystem.Exec('/hide "' + gCurl + '" --silent --fail --location --max-time 600 --output "' + Tmp + '" "' + Url + '"', 660, RetVal, ErrMsg) and (RetVal = 0) and gFSO.FileExists(Tmp) then begin gFSO.MoveFile(Tmp, ImageFile(Id)); Exit; end; end; finally Sizes.Free; end; DeleteFile(Tmp); Result:='Cannot download the picture ' + Id; end; //----------------------------------------------------------------------------- // Connecting //----------------------------------------------------------------------------- function LocConnect(MainThread); begin gFSO:=CreateOleObject('Scripting.FileSystemObject'); LoadSettings; ForceDir(gRoot); if DirectoryExists(gRoot) then Result:='' else Result:='Cannot create the folder ' + gRoot; end; function LocDisconnect; begin gFSO:=Unassigned; try gSearches.Free; except end; gSearches:=Unassigned; Result:=''; end; function LocScanPrepare; begin Result:=''; end; function LocConnected; begin Result:=''; end; function LocReconnect; begin Result:=''; end; //----------------------------------------------------------------------------- // Reading //----------------------------------------------------------------------------- function LocDirExists(FullPath); var Folder, Name; begin SplitPath(FullPath, Folder, Name); if (Folder = '') or ((Name = '') and (SearchFor(Folder) <> '')) then Result:='' else Result:='Folder does not exist'; end; function LocFileExists(FullPath); var ErrMsg; begin if (FindItem(FullPath, ErrMsg) <> '') then Result:='' else Result:='File does not exist'; end; // // The root lists one folder per search; a search's folder lists its files. // A picture that has not been downloaded yet has an unknown size (-1). // function LocScanList(FullPath); var Folder, Name, Search, L, i, Line, Id, DT, Size; begin Result:=''; SplitPath(FullPath, Folder, Name); if (Folder = '') then begin for i:=0 to gSearches.Count - 1 do if not SBLocation.AddDirEx2(SafeName(gSearches[i]), 16, 1.0, 1.0, '') then Exit; Exit; end; Search:=SearchFor(Folder); if (Search = '') then begin Result:='Folder does not exist'; Exit; end; SBSystem.UpdateFileStatus('Searching the NASA library for "' + Search + '"...'); L:=TStringList.Create; try if not FolderItems(Search, L, Result) then Exit; for i:=0 to L.Count - 1 do begin Line:=L[i]; Id:=Field(Line, 1); DT:=SBSystem.ISO8601ToLocalDateTime(Field(Line, 2)); if (Field(Line, 3) = 'txt') then Size:=VarToInt64(gFSO.GetFile(TextFile(Id)).Size) else if gFSO.FileExists(ImageFile(Id)) then Size:=VarToInt64(gFSO.GetFile(ImageFile(Id)).Size) else Size:=-1; if not SBLocation.AddFileEx(Field(Line, 0), '', Size, 32, DT, DT, '') then Exit; end; finally L.Free; end; end; function LocGet(fromFName, toFName); var Line, ErrMsg, Id, Src, r; begin Line:=FindItem(fromFName, ErrMsg); if (Line = '') then begin if (ErrMsg <> '') then Result:=ErrMsg else Result:='File does not exist'; Exit; end; Id:=Field(Line, 1); if (Field(Line, 3) = 'txt') then Src:=TextFile(Id) else begin SBSystem.UpdateFileStatus('Downloading ' + Field(Line, 0) + '...'); Result:=Download(Id); if (Result <> '') then Exit; Src:=ImageFile(Id); end; r:=CopyFile(Src, toFName); if (r = 0) then Result:='' else Result:=SysErrorMessage(r); end; function LocGetAttributes(Filename; var Attrs); begin if (LocDirExists(Filename) = '') then Attrs:=16 else Attrs:=32; Result:=''; end; function LocFreeSpace; begin Result:=-1; end; function LocAbilities; begin Result:=CAN_HAVEEMPTYPATH; end; //----------------------------------------------------------------------------- // Writing: none of it is allowed //----------------------------------------------------------------------------- function LocMakeDir(FullPath); begin if (LocDirExists(FullPath) = '') then Result:='' else Result:=READ_ONLY; end; function LocRemoveDir(FullPath); begin Result:=READ_ONLY; end; function LocRenameDir(FromPath, ToPath); begin Result:=READ_ONLY; end; function LocRenameFile(FromName, ToName); begin Result:=READ_ONLY; end; function LocDeleteFile(FullPath; var DoesNotExist); begin DoesNotExist:=(LocFileExists(FullPath) <> ''); if DoesNotExist then Result:='' else Result:=READ_ONLY; end; function LocCRC32(FullPath; var CRC32); begin Result:='Not supported'; end; function LocSetModDateTime(FullPath, ModDateTime); begin Result:=READ_ONLY; end; function LocSetCreateDateTime(FullPath, CreateDateTime); begin Result:=READ_ONLY; end; function LocSetAttributes(Filename, Attrs); begin Result:=READ_ONLY; end; function LocPutEx(fromFName, toFName, fromAttrs, fromDateTime, fromCreateDateTime, fromFileSize, fromNTFSSec, DoSafeCopy; var SafeFName); begin SafeFName:=''; Result:=READ_ONLY; end; //----------------------------------------------------------------------------- // The NASA Images page in the profile setup //----------------------------------------------------------------------------- // Only in profiles that use NASA Images as their location function ConfigWantSetupNode(IsGroup); begin Result:=not IsGroup and SBProfile.UsesScript; end; function ConfigNodeCaption; begin Result:='NASA Images'; end; function ConfigCanRevert; begin Result:=TRUE; end; function ConfigCanClose; begin Result:=TRUE; end; procedure ConfigFactoryDefaults; begin SBVariables.DeleteProperty('NasaSearches'); SBVariables.DeleteProperty('NasaCount'); SBVariables.DeleteProperty('NasaSize'); SBVariables.DeleteProperty('NasaCacheHours'); SBVariables.DeleteProperty('NasaRoot'); end; procedure ConfigSetupDisplay; begin SBProfile.AddLabel('Pictures from images.nasa.gov. Each search is a folder.', 20); SBProfile.AddEdit('Searches, separated by semicolons', 1000, FALSE, FALSE, 1); SBProfile.AddEdit('Pictures per search (1 to 100)', 3, TRUE, FALSE, 2); SBProfile.AddRadioGroup('Picture size', 3); SBProfile.AddRadioGroupItem('Small', 3); SBProfile.AddRadioGroupItem('Medium', 3); SBProfile.AddRadioGroupItem('Large', 3); SBProfile.AddRadioGroupItem('Original (can be huge)', 3); SBProfile.AddEdit('Hours to keep search results before asking NASA again', 5, TRUE, FALSE, 4); SBProfile.AddEdit('Folder where downloads are kept (blank for %LOCALAPPDATA%\SyncBack NASA Images\)', 260, FALSE, FALSE, 5); end; function ConfigLoadSettings; var Size; begin Result:=''; SBProfile.SetEdit(SBVariables.GetProperty('NasaSearches', 'Nebula; Hubble; Apollo 11', FALSE), 1); SBProfile.SetEdit(SBVariables.GetProperty('NasaCount', '25', FALSE), 2); Size:=LowerCase(SBVariables.GetProperty('NasaSize', 'medium', FALSE)); if (Size = 'small') then SBProfile.SetRadioGroup(0, 3) else if (Size = 'large') then SBProfile.SetRadioGroup(2, 3) else if (Size = 'orig') then SBProfile.SetRadioGroup(3, 3) else SBProfile.SetRadioGroup(1, 3); SBProfile.SetEdit(SBVariables.GetProperty('NasaCacheHours', '24', FALSE), 4); SBProfile.SetEdit(SBVariables.GetProperty('NasaRoot', '', FALSE), 5); end; // Store a setting in the profile. One that has never been set and is still // the default is left unset, so just looking at this page and pressing Cancel // does not count as a change to the profile. procedure SaveSetting(Name, Value, Default); begin if (SBVariables.GetProperty(Name, '!NOTSET!', FALSE) = '!NOTSET!') and (Value = Default) then Exit; SBVariables.SetProperty(Name, Value); end; function ConfigSaveSettings(Silent); var Count, Idx, Size; begin Result:=''; Count:=StrToIntDef(Trim(SBProfile.GetEdit(2)), 0); if (Count < 1) or (Count > 100) then begin Result:='NASA Images: the pictures per search must be from 1 to 100'; Exit; end; SaveSetting('NasaSearches', Trim(SBProfile.GetEdit(1)), 'Nebula; Hubble; Apollo 11'); SaveSetting('NasaCount', IntToStr(Count), '25'); Idx:=SBProfile.GetRadioGroup(3); if (Idx = 0) then Size:='small' else if (Idx = 2) then Size:='large' else if (Idx = 3) then Size:='orig' else Size:='medium'; SaveSetting('NasaSize', Size, 'medium'); SaveSetting('NasaCacheHours', IntToStr(StrToIntDef(Trim(SBProfile.GetEdit(4)), 24)), '24'); SaveSetting('NasaRoot', Trim(SBProfile.GetEdit(5)), ''); end; procedure ConfigUpdateConditionals; begin end;