_common.sh 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. #!/bin/bash
  2. #=================================================
  3. # PERSONAL HELPERS
  4. #=================================================
  5. #=================================================
  6. # BACKUP
  7. #=================================================
  8. HUMAN_SIZE () { # Transforme une taille en Ko en une taille lisible pour un humain
  9. human=$(numfmt --to=iec --from-unit=1K $1)
  10. echo $human
  11. }
  12. CHECK_SIZE () { # Vérifie avant chaque backup que l'espace est suffisant
  13. file_to_analyse=$1
  14. backup_size=$(du --summarize "$file_to_analyse" | cut -f1)
  15. free_space=$(df --output=avail "/home/yunohost.backup" | sed 1d)
  16. if [ $free_space -le $backup_size ]
  17. then
  18. ynh_print_err "Espace insuffisant pour sauvegarder $file_to_analyse."
  19. ynh_print_err "Espace disponible: $(HUMAN_SIZE $free_space)"
  20. ynh_die "Espace nécessaire: $(HUMAN_SIZE $backup_size)"
  21. fi
  22. }
  23. #=================================================
  24. # PACKAGE CHECK BYPASSING...
  25. #=================================================
  26. IS_PACKAGE_CHECK () {
  27. if [ ${PACKAGE_CHECK_EXEC:-0} -eq 1 ]
  28. then
  29. return 0
  30. else
  31. return 1
  32. fi
  33. }
  34. #=================================================
  35. # BOOLEAN CONVERTER
  36. #=================================================
  37. bool_to_01 () {
  38. local var="$1"
  39. [ "$var" = "true" ] && var=1
  40. [ "$var" = "false" ] && var=0
  41. echo "$var"
  42. }
  43. bool_to_true_false () {
  44. local var="$1"
  45. [ "$var" = "1" ] && var=true
  46. [ "$var" = "0" ] && var=false
  47. echo "$var"
  48. }
  49. #=================================================
  50. # FUTUR OFFICIAL HELPERS
  51. #=================================================
  52. # Install or update the main directory yunohost.multimedia
  53. #
  54. # usage: ynh_multimedia_build_main_dir
  55. ynh_multimedia_build_main_dir () {
  56. local ynh_media_release="v1.2"
  57. local checksum="806a827ba1902d6911095602a9221181"
  58. # Download yunohost.multimedia scripts
  59. wget -nv https://github.com/YunoHost-Apps/yunohost.multimedia/archive/${ynh_media_release}.tar.gz
  60. # Check the control sum
  61. echo "${checksum} ${ynh_media_release}.tar.gz" | md5sum -c --status \
  62. || ynh_die "Corrupt source"
  63. # Check if the package acl is installed. Or install it.
  64. ynh_package_is_installed 'acl' \
  65. || ynh_package_install acl
  66. # Extract
  67. mkdir yunohost.multimedia-master
  68. tar -xf ${ynh_media_release}.tar.gz -C yunohost.multimedia-master --strip-components 1
  69. ./yunohost.multimedia-master/script/ynh_media_build.sh
  70. }
  71. # Add a directory in yunohost.multimedia
  72. # This "directory" will be a symbolic link to a existing directory.
  73. #
  74. # usage: ynh_multimedia_addfolder "Source directory" "Destination directory"
  75. #
  76. # | arg: -s, --source_dir= - Source directory - The real directory which contains your medias.
  77. # | arg: -d, --dest_dir= - Destination directory - The name and the place of the symbolic link, relative to "/home/yunohost.multimedia"
  78. ynh_multimedia_addfolder () {
  79. # Declare an array to define the options of this helper.
  80. declare -Ar args_array=( [s]=source_dir= [d]=dest_dir= )
  81. local source_dir
  82. local dest_dir
  83. # Manage arguments with getopts
  84. ynh_handle_getopts_args "$@"
  85. ./yunohost.multimedia-master/script/ynh_media_addfolder.sh --source="$source_dir" --dest="$dest_dir"
  86. }
  87. # Move a directory in yunohost.multimedia, and replace by a symbolic link
  88. #
  89. # usage: ynh_multimedia_movefolder "Source directory" "Destination directory"
  90. #
  91. # | arg: -s, --source_dir= - Source directory - The real directory which contains your medias.
  92. # It will be moved to "Destination directory"
  93. # A symbolic link will replace it.
  94. # | arg: -d, --dest_dir= - Destination directory - The new name and place of the directory, relative to "/home/yunohost.multimedia"
  95. ynh_multimedia_movefolder () {
  96. # Declare an array to define the options of this helper.
  97. declare -Ar args_array=( [s]=source_dir= [d]=dest_dir= )
  98. local source_dir
  99. local dest_dir
  100. # Manage arguments with getopts
  101. ynh_handle_getopts_args "$@"
  102. ./yunohost.multimedia-master/script/ynh_media_addfolder.sh --inv --source="$source_dir" --dest="$dest_dir"
  103. }
  104. # Allow an user to have an write authorisation in multimedia directories
  105. #
  106. # usage: ynh_multimedia_addaccess user_name
  107. #
  108. # | arg: -u, --user_name= - The name of the user which gain this access.
  109. ynh_multimedia_addaccess () {
  110. # Declare an array to define the options of this helper.
  111. declare -Ar args_array=( [u]=user_name=)
  112. local user_name
  113. # Manage arguments with getopts
  114. ynh_handle_getopts_args "$@"
  115. groupadd -f multimedia
  116. usermod -a -G multimedia $user_name
  117. }
  118. #=================================================
  119. # EXPERIMENTAL HELPERS
  120. #=================================================
  121. # Send an email to inform the administrator
  122. #
  123. # usage: ynh_send_readme_to_admin --app_message=app_message [--recipients=recipients] [--type=type]
  124. # | arg: -m --app_message= - The file with the content to send to the administrator.
  125. # | arg: -r, --recipients= - The recipients of this email. Use spaces to separate multiples recipients. - default: root
  126. # example: "root admin@domain"
  127. # If you give the name of a YunoHost user, ynh_send_readme_to_admin will find its email adress for you
  128. # example: "root admin@domain user1 user2"
  129. # | arg: -t, --type= - Type of mail, could be 'backup', 'change_url', 'install', 'remove', 'restore', 'upgrade'
  130. ynh_send_readme_to_admin() {
  131. # Declare an array to define the options of this helper.
  132. declare -Ar args_array=( [m]=app_message= [r]=recipients= [t]=type= )
  133. local app_message
  134. local recipients
  135. local type
  136. # Manage arguments with getopts
  137. ynh_handle_getopts_args "$@"
  138. app_message="${app_message:-}"
  139. recipients="${recipients:-root}"
  140. type="${type:-install}"
  141. # Get the value of admin_mail_html
  142. admin_mail_html=$(ynh_app_setting_get $app admin_mail_html)
  143. admin_mail_html="${admin_mail_html:-0}"
  144. # Retrieve the email of users
  145. find_mails () {
  146. local list_mails="$1"
  147. local mail
  148. local recipients=" "
  149. # Read each mail in argument
  150. for mail in $list_mails
  151. do
  152. # Keep root or a real email address as it is
  153. if [ "$mail" = "root" ] || echo "$mail" | grep --quiet "@"
  154. then
  155. recipients="$recipients $mail"
  156. else
  157. # But replace an user name without a domain after by its email
  158. if mail=$(ynh_user_get_info "$mail" "mail" 2> /dev/null)
  159. then
  160. recipients="$recipients $mail"
  161. fi
  162. fi
  163. done
  164. echo "$recipients"
  165. }
  166. recipients=$(find_mails "$recipients")
  167. # Subject base
  168. local mail_subject="☁️🆈🅽🅷☁️: \`$app\`"
  169. # Adapt the subject according to the type of mail required.
  170. if [ "$type" = "backup" ]; then
  171. mail_subject="$mail_subject has just been backup."
  172. elif [ "$type" = "change_url" ]; then
  173. mail_subject="$mail_subject has just been moved to a new URL!"
  174. elif [ "$type" = "remove" ]; then
  175. mail_subject="$mail_subject has just been removed!"
  176. elif [ "$type" = "restore" ]; then
  177. mail_subject="$mail_subject has just been restored!"
  178. elif [ "$type" = "upgrade" ]; then
  179. mail_subject="$mail_subject has just been upgraded!"
  180. else # install
  181. mail_subject="$mail_subject has just been installed!"
  182. fi
  183. local mail_message="This is an automated message from your beloved YunoHost server.
  184. Specific information for the application $app.
  185. $(if [ -n "$app_message" ]
  186. then
  187. cat "$app_message"
  188. else
  189. echo "...No specific information..."
  190. fi)
  191. ---
  192. Automatic diagnosis data from YunoHost
  193. __PRE_TAG1__$(yunohost tools diagnosis | grep -B 100 "services:" | sed '/services:/d')__PRE_TAG2__"
  194. # Store the message into a file for further modifications.
  195. echo "$mail_message" > mail_to_send
  196. # If a html email is required. Apply html tags to the message.
  197. if [ "$admin_mail_html" -eq 1 ]
  198. then
  199. # Insert 'br' tags at each ending of lines.
  200. ynh_replace_string "$" "<br>" mail_to_send
  201. # Insert starting HTML tags
  202. sed --in-place '1s@^@<!DOCTYPE html>\n<html>\n<head></head>\n<body>\n@' mail_to_send
  203. # Keep tabulations
  204. ynh_replace_string " " "\&#160;\&#160;" mail_to_send
  205. ynh_replace_string "\t" "\&#160;\&#160;" mail_to_send
  206. # Insert url links tags
  207. ynh_replace_string "__URL_TAG1__\(.*\)__URL_TAG2__\(.*\)__URL_TAG3__" "<a href=\"\2\">\1</a>" mail_to_send
  208. # Insert pre tags
  209. ynh_replace_string "__PRE_TAG1__" "<pre>" mail_to_send
  210. ynh_replace_string "__PRE_TAG2__" "<\pre>" mail_to_send
  211. # Insert finishing HTML tags
  212. echo -e "\n</body>\n</html>" >> mail_to_send
  213. # Otherwise, remove tags to keep a plain text.
  214. else
  215. # Remove URL tags
  216. ynh_replace_string "__URL_TAG[1,3]__" "" mail_to_send
  217. ynh_replace_string "__URL_TAG2__" ": " mail_to_send
  218. # Remove PRE tags
  219. ynh_replace_string "__PRE_TAG[1-2]__" "" mail_to_send
  220. fi
  221. # Define binary to use for mail command
  222. if [ -e /usr/bin/bsd-mailx ]
  223. then
  224. local mail_bin=/usr/bin/bsd-mailx
  225. else
  226. local mail_bin=/usr/bin/mail.mailutils
  227. fi
  228. if [ "$admin_mail_html" -eq 1 ]
  229. then
  230. content_type="text/html"
  231. else
  232. content_type="text/plain"
  233. fi
  234. # Send the email to the recipients
  235. cat mail_to_send | $mail_bin -a "Content-Type: $content_type; charset=UTF-8" -s "$mail_subject" "$recipients"
  236. }
  237. #=================================================
  238. ynh_debian_release () {
  239. lsb_release --codename --short
  240. }
  241. is_stretch () {
  242. if [ "$(ynh_debian_release)" == "stretch" ]
  243. then
  244. return 0
  245. else
  246. return 1
  247. fi
  248. }
  249. is_jessie () {
  250. if [ "$(ynh_debian_release)" == "jessie" ]
  251. then
  252. return 0
  253. else
  254. return 1
  255. fi
  256. }
  257. #=================================================
  258. ynh_maintenance_mode_ON () {
  259. # Load value of $path_url and $domain from the config if their not set
  260. if [ -z $path_url ]; then
  261. path_url=$(ynh_app_setting_get $app path)
  262. fi
  263. if [ -z $domain ]; then
  264. domain=$(ynh_app_setting_get $app domain)
  265. fi
  266. mkdir -p /var/www/html/
  267. # Create an html to serve as maintenance notice
  268. echo "<!DOCTYPE html>
  269. <html>
  270. <head>
  271. <meta http-equiv="refresh" content="3">
  272. <title>Your app $app is currently under maintenance!</title>
  273. <style>
  274. body {
  275. width: 70em;
  276. margin: 0 auto;
  277. }
  278. </style>
  279. </head>
  280. <body>
  281. <h1>Your app $app is currently under maintenance!</h1>
  282. <p>This app has been put under maintenance by your administrator at $(date)</p>
  283. <p>Please wait until the maintenance operation is done. This page will be reloaded as soon as your app will be back.</p>
  284. </body>
  285. </html>" > "/var/www/html/maintenance.$app.html"
  286. # Create a new nginx config file to redirect all access to the app to the maintenance notice instead.
  287. echo "# All request to the app will be redirected to ${path_url}_maintenance and fall on the maintenance notice
  288. rewrite ^${path_url}/(.*)$ ${path_url}_maintenance/? redirect;
  289. # Use another location, to not be in conflict with the original config file
  290. location ${path_url}_maintenance/ {
  291. alias /var/www/html/ ;
  292. try_files maintenance.$app.html =503;
  293. # Include SSOWAT user panel.
  294. include conf.d/yunohost_panel.conf.inc;
  295. }" > "/etc/nginx/conf.d/$domain.d/maintenance.$app.conf"
  296. # The current config file will redirect all requests to the root of the app.
  297. # To keep the full path, we can use the following rewrite rule:
  298. # rewrite ^${path_url}/(.*)$ ${path_url}_maintenance/\$1? redirect;
  299. # The difference will be in the $1 at the end, which keep the following queries.
  300. # But, if it works perfectly for a html request, there's an issue with any php files.
  301. # This files are treated as simple files, and will be downloaded by the browser.
  302. # Would be really be nice to be able to fix that issue. So that, when the page is reloaded after the maintenance, the user will be redirected to the real page he was.
  303. systemctl reload nginx
  304. }
  305. ynh_maintenance_mode_OFF () {
  306. # Load value of $path_url and $domain from the config if their not set
  307. if [ -z $path_url ]; then
  308. path_url=$(ynh_app_setting_get $app path)
  309. fi
  310. if [ -z $domain ]; then
  311. domain=$(ynh_app_setting_get $app domain)
  312. fi
  313. # Rewrite the nginx config file to redirect from ${path_url}_maintenance to the real url of the app.
  314. echo "rewrite ^${path_url}_maintenance/(.*)$ ${path_url}/\$1 redirect;" > "/etc/nginx/conf.d/$domain.d/maintenance.$app.conf"
  315. systemctl reload nginx
  316. # Sleep 4 seconds to let the browser reload the pages and redirect the user to the app.
  317. sleep 4
  318. # Then remove the temporary files used for the maintenance.
  319. rm "/var/www/html/maintenance.$app.html"
  320. rm "/etc/nginx/conf.d/$domain.d/maintenance.$app.conf"
  321. systemctl reload nginx
  322. }
  323. #=================================================
  324. # Download and check integrity of a file from app.src_file
  325. #
  326. # The file conf/app.src_file need to contains:
  327. #
  328. # FILE_URL=Address to download the file
  329. # FILE_SUM=Control sum
  330. # # (Optional) Program to check the integrity (sha256sum, md5sum...)
  331. # # default: sha256
  332. # FILE_SUM_PRG=sha256
  333. # # (Optionnal) Name of the local archive (offline setup support)
  334. # # default: Name of the downloaded file.
  335. # FILENAME=example.deb
  336. #
  337. # usage: ynh_download_file --dest_dir="/destination/directory" [--source_id=myfile]
  338. # | arg: -d, --dest_dir= - Directory where to download the file
  339. # | arg: -s, --source_id= - Name of the source file 'app.src_file' if it isn't '$app'
  340. ynh_download_file () {
  341. # Declare an array to define the options of this helper.
  342. declare -Ar args_array=( [d]=dest_dir= [s]=source_id= )
  343. local dest_dir
  344. local source_id
  345. # Manage arguments with getopts
  346. ynh_handle_getopts_args "$@"
  347. source_id=${source_id:-app} # If the argument is not given, source_id equals "$app"
  348. # Load value from configuration file (see above for a small doc about this file
  349. # format)
  350. local src_file="$YNH_CWD/../conf/${source_id}.src_file"
  351. # If the src_file doesn't exist, use the backup path instead, with a "settings" directory
  352. if [ ! -e "$src_file" ]
  353. then
  354. src_file="$YNH_CWD/../settings/conf/${source_id}.src_file"
  355. fi
  356. local file_url=$(grep 'FILE_URL=' "$src_file" | cut -d= -f2-)
  357. local file_sum=$(grep 'FILE_SUM=' "$src_file" | cut -d= -f2-)
  358. local file_sumprg=$(grep 'FILE_SUM_PRG=' "$src_file" | cut -d= -f2-)
  359. local filename=$(grep 'FILENAME=' "$src_file" | cut -d= -f2-)
  360. # Default value
  361. file_sumprg=${file_sumprg:-sha256sum}
  362. if [ "$filename" = "" ] ; then
  363. filename="$(basename "$file_url")"
  364. fi
  365. local local_src="/opt/yunohost-apps-src/${YNH_APP_ID}/${filename}"
  366. if test -e "$local_src"
  367. then # Use the local source file if it is present
  368. cp $local_src $filename
  369. else # If not, download the source
  370. local out=`wget -nv -O $filename $file_url 2>&1` || ynh_print_err $out
  371. fi
  372. # Check the control sum
  373. echo "${file_sum} ${filename}" | ${file_sumprg} -c --status \
  374. || ynh_die "Corrupt file"
  375. # Create the destination directory, if it's not already.
  376. mkdir -p "$dest_dir"
  377. # Move the file to its destination
  378. mv $filename $dest_dir
  379. }
  380. #=================================================
  381. # Create a changelog for an app after an upgrade.
  382. #
  383. # The changelog is printed into the file ./changelog for the time of the upgrade.
  384. #
  385. # In order to create a changelog, ynh_app_changelog will get info from /etc/yunohost/apps/$app/status.json
  386. # In order to find the current commit use by the app.
  387. # The remote repository, and the branch.
  388. # The changelog will be only the commits since the current revision.
  389. #
  390. # Because of the need of those info, ynh_app_changelog works only
  391. # with apps that have been installed from a list.
  392. #
  393. # usage: ynh_app_changelog
  394. ynh_app_changelog () {
  395. get_value_from_settings ()
  396. {
  397. local value="$1"
  398. # Extract a value from the status.json file of an installed app.
  399. grep "$value\": \"" /etc/yunohost/apps/$app/status.json | sed "s/.*$value\": \"\([^\"]*\).*/\1/"
  400. }
  401. local current_revision="$(get_value_from_settings revision)"
  402. local repo="$(get_value_from_settings url)"
  403. local branch="$(get_value_from_settings branch)"
  404. # ynh_app_changelog works only with an app installed from a list.
  405. if [ -z "$current_revision" ] || [ -z "$repo" ] || [ -z "$branch" ]
  406. then
  407. ynh_print_warn "Unable to build the changelog..."
  408. touch changelog
  409. return 0
  410. fi
  411. # Fetch the history of the repository, without cloning it
  412. mkdir git_history
  413. (cd git_history
  414. ynh_exec_warn_less git init
  415. ynh_exec_warn_less git remote add -f origin $repo
  416. # Get the line of the current commit of the installed app in the history.
  417. local line_to_head=$(git log origin/$branch --pretty=oneline | grep --line-number "$current_revision" | cut -d':' -f1)
  418. # Cut the history before the current commit, to keep only newer commits.
  419. # Then use sed to reorganise each lines and have a nice list of commits since the last upgrade.
  420. # This list is redirected into the file changelog
  421. git log origin/$branch --pretty=oneline | head --lines=$(($line_to_head-1)) | sed 's/^\([[:alnum:]]*\)\(.*\)/*(\1) -> \2/g' > ../changelog)
  422. # Remove 'Merge pull request' commits
  423. sed -i '/Merge pull request #[[:digit:]]* from/d' changelog
  424. # As well as conflict resolving commits
  425. sed -i '/Merge branch .* into/d' changelog
  426. # Get the value of admin_mail_html
  427. admin_mail_html=$(ynh_app_setting_get $app admin_mail_html)
  428. admin_mail_html="${admin_mail_html:-0}"
  429. # If a html email is required. Apply html to the changelog.
  430. if [ "$admin_mail_html" -eq 1 ]
  431. then
  432. sed -in-place "s@\*(\([[:alnum:]]*\)) -> \(.*\)@* __URL_TAG1__\2__URL_TAG2__${repo}/commit/\1__URL_TAG3__@g" changelog
  433. fi
  434. }