LazAutoUpdater/ru

From Free Pascal wiki
Jump to navigationJump to search

Template:MenuTranslate

Lazarus Auto-Updater

Резюме

  • LazAutoUpdate - это визуальный раскрывающийся компонент для IDE Lazarus / FPC, который делает обновление приложения из онлайн-источника более простым и интеллектуальным.
  • При создании приложения для распространения, написание процесса обновления для пользователей может быть проблематичным, однако пользователи ценят это средство (если оно не навязано им!), и поддержка проще, если вы знаете, что пользователь всегда имеет самую актуальную версию вашего приложения. LazAutoUpdate предназначен для хорошей интеграции с системой контроля версий SourceForge или GitHub, обеспечивая беспроблемную работу для вас и ваших пользователей.
  • LazAutoUpdate загружает через фоновый поток, чтобы пользователь мог продолжать использовать ваше приложение без перерыва
    • Это означает, например, что ваше приложение может «проверять наличие обновлений» при запуске без "зависаний".
  • Компонент предназначен для разработчиков Lazarus для Windows и Linux, которые размещают свои проекты в SourceForge или GitHub.
  • Вставьте компонент, установите пару свойств (имя вашего проекта SourceForge или некоторые свойства GitHub) и вызовите один простой метод:
    • LazAutoUpdate.AutoUpdate
  • Вы (разработчик) имеете достаточный контроль над поведением компонента, и он достаточно прост в использовании.
  • Конечные пользователи видят процесс обновления простым и прозрачным
  • Протестировано и разработано в Windows 10 64/32-битной и Linux 64/32-битной


botton lauobjinsp2.jpg


Загрузка

  • Установщик пакета LazAutoUpdate (Windows) или zip (Linux) можно загрузить с сайта проекта SourceForge
  • OnlinePackageManager Lazarus также содержит LazAutoUpdate



Установка

  • Загрузите установочный файл Windows или zip-файл linuxbinaries
  • Windows: установить, Linux: распаковать в запасную папку
  • Используйте UpdatePack для создания и распространения ваших файлов обновлений.
  • Используйте компонент LazAutoUpdate, чтобы добавить функциональность обновления в ваши Lazarus'овские приложения.
    • Вам нужно будет распространять updatehm<os>(.exe) вместе с вашим приложением, чтобы LazAutoUpdate работал правильно
    • Не забудьте устанавливать номера VersionInfo в опциях вашего проекта Lazarus



Пример приложения

  • В загруженном пакете находится проект «TestApp»
  • Скомпилируйте и запустите TestApp (не забудьте скомпилировать + скопировать соответствующее средство обновления консоли (updatehm_xxx) в исполняемую папку)
    • Это должно обновить себя "из коробки"
  • Проверьте исходный код TestApp, чтобы получить представление о том, как использовать LazAutoUpdate в полной мере



Интернационализация(локализация)

  • i8n: LazAutoUpdate имеет папку 'locale' со всеми файлами .po, необходимыми для перевода. Базовый язык английский



Использование

  • Установите номер версии для вашего приложения в Project(Проект)/Options(Настройки)/Versioninfo(Информация о версии)
  • Перетащите компонент в основную форму вашего приложения
  • Задайте для свойства SFProjectName имя проекта на SourceForge (тот же текст, который отображается в URL-адресе страницы вашего проекта).
  • или .. Установите свойства GitHub:
    • GitHubProjectname: Имя пользователя или Организация
    • GitHubRepositoryName: Ваш project(проект)/repository(хранилище)
    • GitHubBranchOrTag: 'master' для root или имя ветки GitHub или имя тэга
  • В обоих случаях укажите в UpdatesFolder расположение ваших файлов обновлений (вы можете оставить его пустым)
  • Используйте UpdatePack для загрузки вашего приложения в Интернет (SourceForge, GitHub и т.д.)
  • Затем позвольте компоненту позаботиться о деталях. Просто используйте его (возможно, как пункт меню справки «Проверка обновлений»)
LazAutoUpdate1.AutoUpdate;
  • Вы не хотите, чтобы пользователь закрывал ваше приложение в середине обновления? Используйте этот код в обработчике Form.CloseQuery:
If LazAutoUpdate1.DownloadInProgress Then
  Begin
  CanClose := False;
  ShowMessage('Пожалуйста, подождите. Загрузка все еще продолжается.');
  End;
  • После обновления ваше приложение может автоматически показывать «Что нового». Поместите эту строку в событие OnShow вашей формы:
LazAutoUpdate1.ShowWhatsNewIfAvailable;
  • Это дает вам «каркасность»(бареюон-основу) кода обновления для вашего приложения. Как видите, все довольно просто и автоматизировано.

Больший контроль

  • Вы хотите, чтобы ваше приложение проверяло наличие обновлений при запуске? В этом случае, в вашем обработчике form.activate:
If LazAutoUpdate1.NewVersionAvailable Then
      MessageDlg(Application.Title, 'Новая версия ' + Application.Title +
        ' - доступна.' + LineEnding +
        'Нажмите «Проверить наличие новой версии» в меню «Справка», чтобы обновиться.', mtConfirmation,
        [mbOK], 0);
  • Если вы не используете метод автоматического обновления, вы можете контролировать процесс обновления поэтапно с помощью функций:
If LazAutoUpdate1.NewVersionAvailable then ..... else ...
If LazAutoUpdate1.DownloadNewVersion then ..... else ...
If LazAutoUpdate1.UpdateToNewVersion then ..... else ...

Отладка

  • Если вы установите
LazAutoUpdate1.DebugMode:=TRUE;

тогда вы можете использовать встроенный метод OnDebugEvent для отслеживания активности:

procedure TForm1.LazAutoUpdate1DebugEvent(Sender: TObject; lauMethodName,lauMessage: string);
begin
// используется TEventLog
   Logger.Info('('+lauMethodName+') - ' + lauMessage);
end;

Также возникают события: OnDownloaded и OnNewVersionAvailable, а также свойство LastError с информацией, которую вы можете использовать для отладки.


Поддержка

  • LazAutoUpdate поддерживается через форум Lazarus здесь.



Лицензия

  • LazaAutoUpdate: LGPLv2 (так же, как компоненты Lazarus)
  • Update Pack: GPLv2



Развертывание вашего приложения с помощью LazAutoUpdate

  • Используйте UpdatePack для управления процессом.
    • UpdatePack - это приложение с графическим интерфейсом, которое делает файлы обновления точными и быстрыми и даже предоставляет вам соответствующий код LazAutoUpdate для вашего приложения.
    • Оно использует 'profiles'(профили), которые позволяют вам развертывать будущие обновления, просто обновляя номер версии и нажимая «Создать пакет обновления».
    • Пользователям вашего приложения всегда будет полезна последняя версия программного обеспечения.
  • При тестировании помните, что ваше тестовое приложение должно иметь меньший номер версии, чем ваше приложение 'для обновления', хранящееся в сети :)
  • Если вы хотите создать (или добавить) обновление zip самостоятельно, оно должно содержать, как минимум, приложение и текстовый файл «whatsnew.txt»(что нового?).


updatepack1.jpg updatepack2.jpg


Использование [свойств] auOtherSourceFilename и auOtherSourceURL

  • Когда для ProjectType установлено значение auOther, LazAutoUpdate будет использовать эти свойства для всех методов. Смотрите пример приложения в архиве SVN.



LazAutoUpdate [в виде приложения] в системном трее

  • Пример можно найти в папке /trayicon исходника.
  • Когда он запускается, он находится в области панели задач и молча проверяет наличие обновлений по расписанию (настраивается разработчиком и пользователем)
    • Если он находит новую версию, появляется всплывающее уведомление для обновления:
      • Если приложение не запущено, обновление выполняется в фоновом режиме
      • Если приложение работает, оно закрывает его, а затем выполняет обновление. [Затем] приложение перезапускается.
  • Updater в системном трее имеет контекстное меню:
    • Настройка:
      • The user can edit the schedule - each app has a 'profile'
    • Runs at startup (Windows):
      • The systray loads silently at each Windows boot
  • Systray (lautraynotify) picks up entries from apps that use LazAutoupdate automatically, so it never needs to be configured - simply installed once and forgotten.
  • The schedule is flexible, from once every day to once every month
    • The UpdatePack takes care of producing the systray configuration file for your app. The default is to check every Monday at 9am.
  • The systray app works in both Windows and Linux - all you need to do is deploy it.



Making a generic online installer/updater

  • Once a LazAutoUpdate component has been dropped onto a form, it can be used for multiple updates, downloads etc. (see '/testinstaller' in package source)
  • For a generic installer/updater you need to set:
    • VersionsINIFilename
    • ZipFilename
    • AppFileWithPath
    • AppVersion
  • By setting these properties dynamically (perhaps via a menu) you can enable the user to update multiple applications hosted on a SourceForge/GitHub project site (or any site using auOther settings - see above)
  • Here's example code to use LazAutoUpdate to download then run an application.
  • The zipped files for the application (including 'whatsnew.txt') and the file 'mywizzyapp.ini' are located in the /updates subdirectory of the SourceForge project 'mywizzy'
  • The executable 'updatehm(ostype)(.exe)' is in the same directory as your updater app
    • ostype=[win32|win64|linux32|linux64]
    • Windows ext=(.exe)
  • The user would download a small InnoSetup installer with just the online installer/updater, which in turn would download application(s) and supporting files.
    • Of course, the "installer" could be your main application, with sister applications installable via a menu or some such.
procedure TForm1.Button1Click(Sender: TObject);
// Uses SysUtils,LazFileUtils,ulazautoupdate etc..
Var sDirectoryToInstallTo: string;
begin
sDirectoryToInstallTo := ProgramDirectory + 'installed';
Application.Title:='My whizzy app'
LazAutoUpdate1.WorkingMode := lauInstall;
LazAutoUpdate1.ProjectType := auSourceForge;
LazAutoUpdate1.SFProjectname:='mywizzy';
LazAutoUpdate1.VersionsININame:='mywizzyapp.ini';
LazAutoUpdate1.ZipfileName:='mywizzyapp.zip';
LazAutoUpdate1.AppFileWithPath := sDirectoryToInstallTo + DirectorySeparator + 'mywizzyapp.exe';
// Our responsibility to make the folder
if not DirectoryExistsUTF8(sDirectoryToInstallTo) then ForceDirectoriesUTF8(sDirectoryToInstallTo);
LazAutoUpdate1.Appversion:='0.0.0.0';
If LazAutoUpdate1.DownloadNewVersion then
  begin
    If LazAutoUpdate1.UpdateToNewVersion then
    begin
      LazAutoUpdate1.ShortCut.Category := scUtility;
      LazAutoUpdate1.ShortCut.Target := LazAutoUpdate1.AppFileWithPath;
      LazAutoUpdate1.ShortCut.ShortcutName := Application.Title;
      LazAutoUpdate1.MakeShortCut; // makes a desktop shortcut and a Start menu entry in Windows
    end;
  end;
end;
  • You can then programatically run the installed app easily enough:
// Uses asyncprocess
procedure TForm1.RunInstalledApp;
var
  AProcess: TAsyncProcess;
begin
  if not FileExistsUTF8(LazAutoUpdate1.AppFileWithPath) then
  begin
    ShowMessageFmt('%s does not exist! Install it first.',
      [LazAutoUpdate1.AppFileWithPath]);
    Exit;
  end;
  AProcess := TAsyncProcess.Create(nil);
  try
    AProcess.Executable := LazAutoUpdate1.AppFileWithPath;
    AProcess.Execute;
  finally
    Aprocess.Free;
  end;
end;



Public Methods List

  • Function NewVersionAvailable: Boolean;
  • Function DownloadNewVersion: Boolean;
  • Function UpdateToNewVersion: Boolean;
  • Procedure ShowWhatsNewIfAvailable;
  • Procedure AutoUpdate;
  • function AppIsActive
  • procedure ResetAppVersion;



Non-published Properties list

  • GUIOnlineVersion: String
  • ReturnCode: Integer
  • DownloadInprogress: Boolean
  • AppFileWithPath: String
  • AppVersion: String
  • LastError: String;
  • DebugMode: boolean
  • LCLVersion: string
  • WidgetSet: string
  • FPCVersion: string
  • LastCompiled: string
  • TargetOS: string
  • WindowsAdminCheck: boolean



Deploying multiple updates in a single project

  • By default, the ZipFilename is the same as your application, but you can set it to a unique value, and deploy it to your Online Files/updates irectory
  • Each application to be updated should have a unique name for the versions.ini file. Set the VersionsINIFilename property.



In case the download takes to long

  • VersionCountLimit property determines how long LazAutoUpdate will check for a new version before timing out.
  • DownloadCountLimit property determines how long LazAutoUpdate will try downloading the new version before timing out.



Versions.ini

The format is as follows:

;LazAutoUpdate versions file
[versions]
GUI=0.0.2
  • The file is small so that it is very quick to download



Source Code and latest versions



Security

Windows 10

  • Windows 10 security will not allow a non-admin user to update applications from the internet (unless it's a Windows Store App). This is a sensible policy in my opinion, and LazAutoUpdate adheres to it.
    • If an 'ordinary user' tries to update an app using LazAutoUpdate, all will go smoothly until the final 'Update app' phase. At that point LazAutoUpdate will pop up a dialog informing the user that an administrator account is needed for the actual update.
    • For an 'admin user', LazAutoUpdate will pop up a UAC dialog (the same as any installer) and proceed upon clicking 'yes' to do the update.
    • If you wish to circumvent this (perhaps with a manifest) LazAutoUpdate has the public property 'WindowsAdminCheck' which you can set to FALSE and avoid the dialog.

Linux

  • Linux will do the update without even showing the update console, and the user gets a seamless experience.



Workflow

(Technical explanation)

The Laz AutoUpdater workflow for updating a running application is as follows:

  • App downloads a small 'version.ini' file from sourceforge or github with version info (it can do this at start-up)
  • App compares with its own internal version
  • If new version available
    • App deletes any contents of local /updates folder
    • App downloads then unzips it from the web into a local /updates folder
  • App uses TAsyncProcess to start the console updater.exe, passing it the name of the file to be updated in the command line
  • updater.exe copies a downloaded 'whatsnew.txt' into the App folder and enters Sleep for a few seconds
  • Meanwhile App has entered loop checking whether a 'whatsnew.txt' file has been copied into it's directory
  • App detects 'whatsnew.txt' and Closes. (in other words the TProcess has started successfully)
  • Updater copies /updates/UpdatedApp to App directory.
  • Updater uses TProcess to start the updated app
  • On Form.Show, App displays 'whatsnew.txt' then deletes it

The User sees:

  • Dialog: 'There's a new version of xxx available. Would you like to download it?' Yes/No
  • If Yes clicked:
    • Download happens in the background (via a background thread) Optional 'download counter' is shown to indicate progress.
    • User is prevented from closing the app whilst the download is in progress (in Form.CloseQuery)
    • Dialog: 'The update is downloaded. Click OK to install it and restart xxx now' OK
    • User clicks OK
    • A console (DOS window in Windows) opens automatically and the Application closes. The console says 'Please wait updating xxx'
    • After a couple of seconds the console disappears, and the new version of the App starts
    • As soon as the main window is shown, a 'What's New' info box is shown with an OK button
    • User clicks OK button, and never sees the info again



Minesadorada