├── .gitignore ├── LICENSE ├── README.md ├── dart ├── .gitignore ├── compress_image │ ├── README.md │ ├── lib │ │ └── main.dart │ └── pubspec.yaml ├── convert-phone-number-to-country-name │ ├── README.md │ ├── lib │ │ └── main.dart │ └── pubspec.yaml ├── deepgram_Topic_Detection │ ├── README.md │ ├── lib │ │ └── main.dart │ └── pubspec.yaml ├── deepgram_audio_summary │ ├── README.md │ ├── lib │ │ └── main.dart │ └── pubspec.yaml ├── deepgram_language_detection │ ├── README.md │ ├── lib │ │ └── main.dart │ └── pubspec.yaml ├── deepgram_transcribe_audio │ ├── README.md │ ├── lib │ │ └── main.dart │ └── pubspec.yaml ├── deepgram_transcribe_video │ ├── README.md │ ├── lib │ │ └── main.dart │ └── pubspec.yaml ├── generate-website-screenshot │ ├── README.md │ ├── lib │ │ └── main.dart │ └── pubspec.yaml ├── generate_giphy_gif │ ├── README.md │ ├── lib │ │ └── main.dart │ └── pubspec.yaml ├── generate_map │ ├── README.md │ ├── lib │ │ └── main.dart │ └── pubspec.yaml ├── generate_short_url │ ├── README.md │ ├── lib │ │ └── main.dart │ └── pubspec.yaml ├── object_detection │ ├── README.md │ ├── lib │ │ └── main.dart │ └── pubspec.yaml ├── send-email-with-mailgun │ ├── README.md │ ├── lib │ │ └── main.dart │ └── pubspec.yaml └── send_push_notification │ ├── README.md │ ├── lib │ ├── fcm_service.dart │ └── main.dart │ ├── pubspec.yaml │ └── test │ └── send_push_notification_test.dart ├── deno ├── .gitignore ├── compress_image │ ├── README.md │ └── src │ │ ├── deps.ts │ │ └── mod.ts ├── convert-phone-number-to-country-name │ ├── README.md │ ├── deps.ts │ └── mod.ts ├── deepgram-language-detection │ ├── README.md │ └── src │ │ └── mod.ts ├── deepgram-topic-detection │ ├── README.md │ └── src │ │ ├── deps.ts │ │ └── mod.ts ├── deepgram-transcribe-audio │ ├── README.md │ └── src │ │ ├── deps.ts │ │ └── mod.ts ├── deepgram-transcribe-video │ ├── README.md │ └── src │ │ └── mod.ts ├── deepgram_audio_summary │ ├── README.md │ └── src │ │ └── mod.ts ├── generate_giphy_gif │ ├── README.md │ └── src │ │ └── mod.ts ├── generate_short_url │ ├── README.md │ └── src │ │ └── mod.ts ├── generate_website_screenshot │ ├── README.md │ └── src │ │ ├── deps.ts │ │ └── mod.ts ├── get_price │ ├── README.md │ └── src │ │ └── mod.ts ├── object_detection │ ├── README.md │ └── src │ │ └── mod.ts ├── send_email_with_mailgun │ ├── README.md │ └── src │ │ └── mod.ts ├── send_http_request │ ├── README.md │ └── src │ │ └── mod.ts ├── send_sms_with_twilio │ ├── README.md │ └── src │ │ └── mod.ts ├── translate_text_with_google │ ├── README.md │ └── src │ │ └── mod.ts └── wipe_appwrite_bucket │ ├── README.md │ └── src │ ├── deps.ts │ └── mod.ts ├── dotnet ├── generateShortUrl │ ├── .gitignore │ ├── Function.csproj │ ├── README.md │ └── src │ │ └── Index.cs └── wipe_appwrite_collection │ ├── AppwriteDatabaseClient.cs │ ├── Index.cs │ ├── Models │ ├── Document.cs │ └── ListDocumentsResponse.cs │ ├── README.md │ └── wipeAppwriteCollection.csproj ├── java ├── deepgramLanguageDetection │ ├── Index.java │ ├── README.md │ └── deps.gradle ├── deepgram_audio_summary │ ├── Index.java │ ├── README.md │ └── deps.gradle ├── generate_invoice │ ├── Index.java │ ├── README.md │ └── deps.gradle ├── generate_qr_code │ ├── Index.java │ ├── README.md │ ├── deps.gradle │ └── images │ │ └── successful_response.png ├── get_price │ ├── Index.java │ ├── README.md │ └── deps.gradle └── short_url_generator │ ├── Index.java │ ├── README.md │ └── deps.gradle ├── kotlin ├── deepgram-transcribe-audio │ ├── README.md │ ├── deps.gradle │ └── src │ │ └── Index.kt ├── generate-short-url │ ├── README.md │ ├── deps.gradle │ └── src │ │ └── Index.kt └── wipeAppwriteBucket │ ├── README.md │ ├── deps.gradle │ └── src │ └── Index.kt ├── node ├── .gitignore ├── convert-phone-number-to-country-name │ ├── README.md │ ├── index.js │ ├── package-lock.json │ └── package.json ├── deepgram-transcribe-video │ ├── README.md │ ├── index.js │ ├── package-lock.json │ └── package.json ├── deepgram_audio_summary │ ├── README.md │ ├── package-lock.json │ ├── package.json │ └── src │ │ └── index.js ├── deepgram_topic_detection │ ├── README.md │ ├── package-lock.json │ ├── package.json │ └── src │ │ └── index.js ├── generate_giphy_gif │ ├── README.md │ ├── package-lock.json │ ├── package.json │ └── src │ │ └── index.js ├── generate_invoice │ ├── README.md │ ├── Screenshot from 2022-10-03 23-09-25.png │ ├── Screenshot from 2022-10-03 23-10-49.png │ ├── package-lock.json │ ├── package.json │ └── src │ │ └── index.js ├── generate_map │ ├── README.md │ ├── package.json │ └── src │ │ └── index.js ├── get_covid_stats │ ├── README.md │ ├── package-lock.json │ ├── package.json │ └── src │ │ └── index.js ├── object_detection │ ├── README.md │ ├── package-lock.json │ ├── package.json │ └── src │ │ └── index.js ├── send_email_with_mailgun │ ├── README.md │ ├── package.json │ └── src │ │ └── index.js ├── send_http_request │ ├── README.md │ ├── index.js │ ├── package-lock.json │ └── package.json ├── send_sms_with_twilio │ ├── README.md │ ├── package-lock.json │ ├── package.json │ └── src │ │ └── index.js ├── translate_text │ ├── README.md │ ├── package-lock.json │ ├── package.json │ └── src │ │ ├── aws_provider.js │ │ ├── azure_provider.js │ │ ├── google_provider.js │ │ └── index.js ├── translate_text_with_google │ ├── README.md │ ├── package-lock.json │ ├── package.json │ └── src │ │ └── index.js ├── url-shortener │ ├── README.md │ ├── index.js │ └── package.json ├── wipe_appwrite_bucket │ ├── .gitignore │ ├── README.md │ ├── package-lock.json │ ├── package.json │ └── src │ │ └── index.js └── wipe_appwrite_collection │ ├── README.md │ ├── index.js │ ├── package-lock.json │ └── package.json ├── php ├── .gitignore ├── convert-phone-number-to-country-name │ ├── README.md │ ├── composer.json │ └── index.php ├── deepgram-audio-summary │ ├── README.md │ └── index.php ├── deepgram_language_detection │ ├── README.md │ ├── composer.json │ └── index.php ├── deepgram_transcribe_audio │ ├── README.md │ ├── composer.json │ └── index.php ├── generate-short-url │ ├── README.md │ └── index.php ├── generate_giphy_gif │ ├── README.md │ ├── composer.json │ └── index.php ├── object_detection │ ├── README.md │ ├── composer.json │ └── index.php ├── send-http-request │ ├── README.md │ ├── composer.json │ └── index.php ├── send_message │ ├── README.md │ ├── composer.json │ ├── index.php │ └── src │ │ ├── Contracts │ │ ├── Channel.php │ │ └── Validator.php │ │ ├── DiscordChannel.php │ │ ├── EmailChannel.php │ │ ├── NullChannel.php │ │ ├── SMSChannel.php │ │ ├── Traits │ │ └── HasReceiver.php │ │ ├── TwitterChannel.php │ │ └── Validators │ │ ├── EmailValidator.php │ │ └── PhoneNumberValidator.php └── wipe_appwrite_bucket │ ├── README.md │ ├── composer.json │ └── index.php ├── python ├── .gitignore ├── convert-phone-number-to-country-name │ ├── README.md │ ├── main.py │ └── requirements.txt ├── deepgram-audio-summary │ ├── README.md │ ├── main.py │ └── requirements.txt ├── deepgram-language-detection │ ├── README.md │ ├── main.py │ └── requirements.txt ├── deepgram-topic-detection │ ├── README.md │ ├── main.py │ └── requirements.txt ├── deepgram-transcribe-audio │ ├── README.md │ ├── main.py │ └── requirements.txt ├── deepgram-transcribe-video │ ├── README.md │ ├── main.py │ └── requirements.txt ├── generate-giphy-gif │ ├── README.md │ ├── main.py │ └── requirements.txt ├── generate-map │ ├── README.md │ ├── main.py │ └── requirements.txt ├── generate-short-url │ ├── README.md │ ├── main.py │ └── requirements.txt ├── object-detection │ ├── README.md │ ├── main.py │ └── requirements.txt ├── send-http-request │ ├── README.md │ ├── main.py │ └── requirements.txt └── send_message │ ├── README.md │ ├── functions │ ├── send_email_mailgun.py │ ├── send_message_discord_webhook.py │ ├── send_sms_twilio.py │ └── send_tweet.py │ ├── main.py │ └── requirements.txt ├── ruby ├── .gitignore ├── compress-image │ ├── Gemfile │ ├── README.md │ └── index.rb ├── convert-phone-number-to-country-name │ ├── Gemfile │ ├── README.md │ └── index.rb ├── deepgram-audio-summary │ ├── Gemfile │ ├── README.md │ └── index.rb ├── deepgram-transcribe-video │ ├── Gemfile │ ├── README.md │ └── index.rb ├── send-http-request │ ├── Gemfile │ ├── README.md │ └── index.rb ├── send-sms-with-twilio │ ├── Gemfile │ ├── README.md │ └── index.rb ├── translate-text-with-google │ ├── Gemfile │ ├── README.md │ └── index.rb ├── wipe-appwrite-bucket │ ├── Gemfile │ ├── README.md │ └── index.rb └── wipe-appwrite-collection │ ├── Gemfile │ ├── README.md │ └── index.rb └── swift ├── .gitignore ├── convert-phone-number-to-country-name ├── Package.swift ├── README.md └── Sources │ └── index.swift ├── get-covid-stats ├── CovidData.swift ├── Index.swift ├── Package.swift └── README.md └── send-email-with-mailgun ├── .gitignore ├── Index.swift ├── MultipartUtils.swift ├── Package.swift └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | ## Open-Runtime specific rules 2 | code.tar.gz 3 | 4 | ## General rules, taken from https://gist.github.com/octocat/9257657 5 | 6 | # Compiled source # 7 | ################### 8 | *.com 9 | *.dll 10 | *.exe 11 | *.o 12 | *.so 13 | 14 | # Logs and databases # 15 | ###################### 16 | *.log 17 | *.sql 18 | *.sqlite 19 | 20 | # OS generated files # 21 | ###################### 22 | .DS_Store 23 | .DS_Store? 24 | ._* 25 | .Spotlight-V100 26 | .Trashes 27 | ehthumbs.db 28 | Thumbs.db -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Open Runtimes 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /dart/.gitignore: -------------------------------------------------------------------------------- 1 | ## Dart Gitignore 2 | # See https://www.dartlang.org/guides/libraries/private-files 3 | 4 | # Files and directories created by pub 5 | .dart_tool/ 6 | .packages 7 | build/ 8 | # If you're building an application, you may want to check-in your pubspec.lock 9 | pubspec.lock 10 | 11 | # Directory created by dartdoc 12 | # If you don't generate documentation locally you can remove this line. 13 | doc/api/ 14 | 15 | # dotenv environment variables file 16 | .env* 17 | 18 | # Avoid committing generated Javascript files: 19 | *.dart.js 20 | *.info.json # Produced by the --dump-info flag. 21 | *.js # When generated by dart2js. Don't specify *.js if your 22 | # project includes source files written in JavaScript. 23 | *.js_ 24 | *.js.deps 25 | *.js.map 26 | 27 | .flutter-plugins 28 | .flutter-plugins-dependencies -------------------------------------------------------------------------------- /dart/compress_image/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: compress_image 2 | description: "" 3 | version: 1.0.0 4 | 5 | environment: 6 | sdk: ">=2.14.0 <3.0.0" 7 | 8 | dependencies: 9 | http: ^0.13.5 10 | -------------------------------------------------------------------------------- /dart/convert-phone-number-to-country-name/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: convert_phone_number_to_country_name 2 | description: "" 3 | version: 1.0.0 4 | 5 | environment: 6 | sdk: '>=2.14.0 <3.0.0' 7 | 8 | dependencies: 9 | dart_appwrite: ^4.0.0 -------------------------------------------------------------------------------- /dart/deepgram_Topic_Detection/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: appwrite_function 2 | description: Dart starter for Appwrite function. 3 | version: 1.0.0 4 | publish_to: "none" 5 | 6 | environment: 7 | sdk: '>=2.14.0 <3.0.0' 8 | 9 | dependencies: 10 | http: ^0.13.5 11 | -------------------------------------------------------------------------------- /dart/deepgram_audio_summary/lib/main.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | import 'package:http/http.dart' as http; 3 | 4 | //custom success message 5 | void returnSuccess(final res, final data) { 6 | res.json({ 7 | 'success': true, 8 | 'deepgramData': data, 9 | }); 10 | } 11 | 12 | //custom failure message 13 | void returnFailure(final res, final message) { 14 | res.json({ 15 | 'success': false, 16 | 'message': message, 17 | }); 18 | } 19 | 20 | Future start(final req, final res) async { 21 | var fileUrl; 22 | var apiKey; 23 | 24 | //getting data from payload 25 | try { 26 | final data = jsonDecode(req.payload); 27 | fileUrl = data["fileUrl"]; 28 | apiKey = req.variables["DEEPGRAM_API_KEY"]; 29 | } catch (err) { 30 | returnFailure(res, err.toString()); 31 | return; 32 | } 33 | 34 | //checks 35 | if (fileUrl == null) { 36 | returnFailure(res, "Provide a valid file URL in payload"); 37 | return; 38 | } 39 | 40 | if (apiKey == null) { 41 | returnFailure(res, "Provide the API key as an environment variable"); 42 | return; 43 | } 44 | 45 | //making the request 46 | try { 47 | final endPoint = Uri.parse( 48 | "https://api.deepgram.com/v1/listen?summarize=true&punctuate=true"); 49 | final headers = { 50 | "Authorization": "Token $apiKey", 51 | 'content-type': 'application/json', 52 | }; 53 | final body = {"url": fileUrl}; 54 | final result = 55 | await http.post(endPoint, headers: headers, body: jsonEncode(body)); 56 | if (result.statusCode != 200) { 57 | returnFailure(res, jsonDecode(result.body)); 58 | return; 59 | } 60 | returnSuccess(res, jsonDecode(result.body)); 61 | return; 62 | } catch (err) { 63 | returnFailure(res, err.toString()); 64 | return; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /dart/deepgram_audio_summary/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: deepgram_audio_summary 2 | description: "" 3 | version: 1.0.0 4 | 5 | environment: 6 | sdk: '>=2.14.0 <3.0.0' 7 | 8 | dependencies: 9 | http: ^0.13.4 -------------------------------------------------------------------------------- /dart/deepgram_language_detection/lib/main.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | import 'package:http/http.dart' as http; 3 | 4 | //custom success message 5 | 6 | void returnSuccess(final res, final data) { 7 | res.json({ 8 | 'success': true, 9 | 'deepgramData': data, 10 | }); 11 | } 12 | 13 | //custom failure message 14 | 15 | void returnFailure(final res, final message) { 16 | res.json({ 17 | 'success': false, 18 | 'message': message, 19 | }); 20 | } 21 | 22 | Future start(final req, final res) async { 23 | var fileUrl; 24 | var apiKey; 25 | 26 | //getting data from payload 27 | 28 | try { 29 | final data = jsonDecode(req.payload); 30 | fileUrl = data["fileUrl"]; 31 | apiKey = req.variables["DEEPGRAM_API_KEY"]; 32 | } catch (err) { 33 | returnFailure(res, err.toString()); 34 | return; 35 | } 36 | 37 | //checks 38 | 39 | if (fileUrl == null) { 40 | returnFailure(res, "Provide a valid file URL in payload"); 41 | return; 42 | } 43 | 44 | if (apiKey == null) { 45 | returnFailure(res, "Provide the API key as an environment variable"); 46 | } 47 | 48 | //making the request 49 | 50 | try { 51 | final endPoint = Uri.parse( 52 | "https://api.deepgram.com/v1/listen?detect_language=true&punctuate=true"); 53 | final headers = { 54 | "Authorization": "Token $apiKey", 55 | 'content-type': 'application/json', 56 | }; 57 | final body = {"url": fileUrl}; 58 | final result = 59 | await http.post(endPoint, headers: headers, body: jsonEncode(body)); 60 | if (result.statusCode != 200) { 61 | returnFailure(res, jsonDecode(result.body)); 62 | return; 63 | } 64 | returnSuccess(res, jsonDecode(result.body)); 65 | return; 66 | } catch (err) { 67 | returnFailure(res, err.toString()); 68 | return; 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /dart/deepgram_language_detection/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: language_detection 2 | description: "" 3 | version: 1.0.0 4 | 5 | environment: 6 | sdk: '>=2.14.0 <3.0.0' 7 | 8 | dependencies: 9 | http: ^0.13.4 -------------------------------------------------------------------------------- /dart/deepgram_transcribe_audio/lib/main.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | import 'package:http/http.dart' as http; 3 | 4 | void returnSuccess(final res, final data) { 5 | res.json({ 6 | 'success': true, 7 | 'deepgramData': data, 8 | }); 9 | } 10 | 11 | void returnFailure(final res, final message) { 12 | res.json({ 13 | 'success': false, 14 | 'message': message, 15 | }); 16 | } 17 | 18 | Future start(final req, final res) async { 19 | var fileUrl; 20 | var deepgramApiKey; 21 | 22 | //getting data from payload 23 | try { 24 | final data = jsonDecode(req.payload); 25 | fileUrl = data["fileUrl"]; 26 | deepgramApiKey = req.variables["DEEPGRAM_API_KEY"]; 27 | } catch (err) { 28 | returnFailure(res, err.toString()); 29 | return; 30 | } 31 | 32 | //checks 33 | if (fileUrl == null || deepgramApiKey == null) { 34 | if (fileUrl == null) 35 | returnFailure(res, "Please provide a file url in payload"); 36 | else 37 | returnFailure(res, "Please provide the api key in environment variables"); 38 | return; 39 | } 40 | 41 | //making the request 42 | try { 43 | final endPoint = 44 | Uri.parse("https://api.deepgram.com/v1/listen?model=general"); 45 | final headers = { 46 | "Authorization": "Token $deepgramApiKey", 47 | 'content-type': 'application/json', 48 | }; 49 | final body = {"url": fileUrl}; 50 | final result = 51 | await http.post(endPoint, headers: headers, body: jsonEncode(body)); 52 | if (result.statusCode != 200) { 53 | returnFailure(res, jsonDecode(result.body)); 54 | return; 55 | } 56 | returnSuccess(res, jsonDecode(result.body)); 57 | return; 58 | } catch (err) { 59 | returnFailure(res, err.toString()); 60 | return; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /dart/deepgram_transcribe_audio/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: deepgram_transcribe_audio 2 | description: "" 3 | version: 1.0.0 4 | 5 | environment: 6 | sdk: '>=2.14.0 <3.0.0' 7 | dependencies: 8 | http: ^0.13.5 9 | -------------------------------------------------------------------------------- /dart/deepgram_transcribe_video/lib/main.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | import 'package:http/http.dart' as http; 3 | 4 | //custom success message 5 | void returnSuccess(final res, final data) { 6 | res.json({ 7 | 'success': true, 8 | 'deepgramData': data, 9 | }); 10 | } 11 | 12 | //custom failure message 13 | void returnFailure(final res, final message) { 14 | res.json({ 15 | 'success': false, 16 | 'message': message, 17 | }); 18 | } 19 | 20 | Future start(final req, final res) async { 21 | var fileUrl; 22 | var apiKey; 23 | 24 | //getting data from payload 25 | try { 26 | final data = jsonDecode(req.payload); 27 | fileUrl = data["fileUrl"]; 28 | apiKey = req.variables["DEEPGRAM_API_KEY"]; 29 | } catch (err) { 30 | returnFailure(res, err.toString()); 31 | return; 32 | } 33 | 34 | //checks 35 | 36 | if (fileUrl == null) { 37 | returnFailure(res, "Provide a valid file URL in payload"); 38 | return; 39 | } 40 | 41 | if (apiKey == null) { 42 | returnFailure(res, "Provide the API key as an environment variable"); 43 | return; 44 | } 45 | 46 | //making the request 47 | try { 48 | final endPoint = 49 | Uri.parse("https://api.deepgram.com/v1/listen?model=video"); 50 | final headers = { 51 | "Authorization": "Token $apiKey", 52 | 'content-type': 'application/json', 53 | }; 54 | final body = {"url": fileUrl}; 55 | final result = 56 | await http.post(endPoint, headers: headers, body: jsonEncode(body)); 57 | if (result.statusCode != 200) { 58 | returnFailure(res, jsonDecode(result.body)); 59 | return; 60 | } 61 | returnSuccess(res, jsonDecode(result.body)); 62 | return; 63 | } catch (err) { 64 | returnFailure(res, err.toString()); 65 | return; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /dart/deepgram_transcribe_video/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: transcribe_video 2 | description: "" 3 | version: 1.0.0 4 | 5 | environment: 6 | sdk: '>=2.14.0 <3.0.0' 7 | 8 | dependencies: 9 | http: ^0.13.4 -------------------------------------------------------------------------------- /dart/generate-website-screenshot/lib/main.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | import 'package:http/http.dart' as http; 3 | 4 | Future start(final req, final res) async { 5 | // Validating payload 6 | Map data; 7 | try { 8 | data = jsonDecode(req.payload); 9 | } on FormatException { 10 | res.json({ 11 | "success": false, 12 | "message": "Invalid Payload.", 13 | }); 14 | return; 15 | } 16 | 17 | // Checking if url Parameter is present in the payload 18 | if (!data.containsKey("url")) { 19 | res.json({ 20 | "success": false, 21 | "message": "Missing parameter url.", 22 | }); 23 | return; 24 | } 25 | 26 | final url = data["url"]; 27 | 28 | // Checking if SCREEENLY_API_KEY is provided in Variables. 29 | if (req.variables['SCREEENLY_API_KEY'] == null) { 30 | res.json({ 31 | "success": false, 32 | "message": "Missing Screeenly API Key in variables", 33 | }); 34 | return; 35 | } 36 | 37 | final api_key = req.variables['SCREEENLY_API_KEY']; 38 | 39 | var parsedUrl = Uri.parse( 40 | "http://screeenly.com/api/v1/fullsize?key=${api_key}&url=${url}"); 41 | 42 | // Sending Post request to Screenly to get the screenshot. 43 | var response = await http.post(parsedUrl); 44 | 45 | // Response if the request was a success 46 | if (response.statusCode == 200) { 47 | Map parsedBody = jsonDecode(response.body); 48 | res.json({"success": true, "screenshot": parsedBody["base64_raw"]}); 49 | } 50 | 51 | // Response otherwise 52 | else { 53 | Map parsedBody = jsonDecode(response.body); 54 | final title = parsedBody['title']; 55 | final message = parsedBody['message']; 56 | res.json({"success": false, "message": '$title: $message'}); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /dart/generate-website-screenshot/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: generate_website_screenshot 2 | description: "" 3 | version: 1.0.0 4 | 5 | environment: 6 | sdk: '>=2.14.0 <3.0.0' 7 | 8 | dependencies: 9 | http: ^0.13.4 10 | -------------------------------------------------------------------------------- /dart/generate_giphy_gif/README.md: -------------------------------------------------------------------------------- 1 | # 🖼️ Get Giphy GIF 2 | 3 | A Dart Cloud Function for generating Giphy GIF from the [Giphy API](https://developers.giphy.com/docs/api#quick-start-guide). 4 | 5 | _Example input:_ 6 | 7 | ```json 8 | { 9 | "search": "good morning" 10 | } 11 | ``` 12 | 13 | _Example output:_ 14 | 15 | 16 | ```json 17 | { 18 | "search": "good morning", 19 | "gif": "https://giphy.com/gifs/text-gif-sticker-brittdoesdesign-MS9Yq6Y718CSiDTxR5" 20 | } 21 | ``` 22 | 23 | ## 📝 Environment Variables 24 | 25 | List of environment variables used by this cloud function: 26 | 27 | **GIPHY_API_KEY** - Your Giphy API key. 28 | 29 | ## 🚀 Deployment 30 | 31 | 1. Clone this repository, and enter this function folder: 32 | 33 | ``` 34 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 35 | $ cd dart/generate_giphy_gif 36 | ``` 37 | 38 | 2. Enter this function folder and build the code: 39 | ``` 40 | docker run -e INTERNAL_RUNTIME_ENTRYPOINT=lib/main.dart --rm --interactive --tty --volume $PWD:/usr/code openruntimes/dart:v2-2.16 sh /usr/local/src/build.sh 41 | ``` 42 | As a result, a `code.tar.gz` file will be generated. 43 | 44 | 3. Start the Open Runtime: 45 | ``` 46 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_KEY=secret-key --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/dart:v2-2.16 sh /usr/local/src/start.sh 47 | ``` 48 | 49 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit Dart runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/dart-2.16). 50 | 51 | ## 📝 Notes 52 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 53 | - This example is compatible with Dart 2.16. Other versions may work but are not guaranteed to work as they haven't been tested. Versions below Dart 2.14 will not work, because Apwrite SDK requires Dart 2.14, -------------------------------------------------------------------------------- /dart/generate_giphy_gif/lib/main.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | import 'dart:io'; 3 | import 'package:http/http.dart' as http; 4 | 5 | Future start(final req, final res) async { 6 | final APIKey = req.variables["GIPHY_API_KEY"]; 7 | 8 | Map data = jsonDecode(req.payload); 9 | 10 | if (!data.containsKey("search")) { 11 | throw new Exception("Missing Search Query"); 12 | } 13 | 14 | if (req.variables['GIPHY_API_KEY'] == null) { 15 | throw new Exception("Missing Giphy API Key in environment variables"); 16 | } 17 | 18 | final search = data["search"]; 19 | 20 | // Download image into buffer 21 | var parsedUrl = Uri.parse("https://api.giphy.com/v1/gifs/search?api_key=${APIKey}&q=${search}&limit=1"); 22 | var response = await http.get(parsedUrl); 23 | 24 | if (response.statusCode != 200) { 25 | throw new Exception("Failed to get GIF"); 26 | } 27 | 28 | // Parse response 29 | Map parsedBody = jsonDecode(response.body); 30 | 31 | Map result = { 32 | "search": search, 33 | "url": parsedBody["data"][0]['url'] 34 | }; 35 | 36 | res.json(result); 37 | } -------------------------------------------------------------------------------- /dart/generate_giphy_gif/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: object_detection 2 | description: "" 3 | version: 1.0.0 4 | 5 | environment: 6 | sdk: '>=2.14.0 <3.0.0' 7 | 8 | dependencies: 9 | http: ^0.13.4 -------------------------------------------------------------------------------- /dart/generate_map/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: generate_map 2 | description: "" 3 | version: 1.0.0 4 | 5 | environment: 6 | sdk: ">=2.14.0 <3.0.0" 7 | 8 | dependencies: 9 | http: ^0.13.4 10 | -------------------------------------------------------------------------------- /dart/generate_short_url/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: generate_short_url 2 | description: "" 3 | version: 1.0.0 4 | 5 | environment: 6 | sdk: '>=2.14.0 <3.0.0' 7 | dependencies: 8 | http: ^0.13.5 9 | -------------------------------------------------------------------------------- /dart/object_detection/README.md: -------------------------------------------------------------------------------- 1 | # 📷 Object Detection using Cloudmersive Vision API 2 | 3 | A Dart Cloud Function for object detection from an image URL. 4 | 5 | _Example input:_ 6 | 7 | ```json 8 | { 9 | "url": "https://picsum.photos/seed/open___runtimes/1000/1000" 10 | } 11 | ``` 12 | 13 | _Example output:_ 14 | 15 | 16 | ```json 17 | { 18 | "url": "https://picsum.photos/seed/open___runtimes/1000/1000", 19 | "name": "cake", 20 | "confidence": 0.7977721691131592, 21 | "x": 21, 22 | "y": 5, 23 | "width": 494, 24 | "height": 333 25 | } 26 | ``` 27 | 28 | ## 📝 Environment Variables 29 | 30 | List of environment variables used by this cloud function: 31 | 32 | **CLOUDMERSIVE_API_KEY** - Your Cloudmersive API key. 33 | 34 | ## 🚀 Deployment 35 | 36 | 1. Clone this repository, and enter this function folder: 37 | 38 | ``` 39 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 40 | $ cd dart/object_detection 41 | ``` 42 | 43 | 2. Enter this function folder and build the code: 44 | ``` 45 | docker run -e INTERNAL_RUNTIME_ENTRYPOINT=lib/main.dart --rm --interactive --tty --volume $PWD:/usr/code openruntimes/dart:v2-2.16 sh /usr/local/src/build.sh 46 | ``` 47 | As a result, a `code.tar.gz` file will be generated. 48 | 49 | 3. Start the Open Runtime: 50 | ``` 51 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_KEY=secret-key --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/dart:v2-2.16 sh /usr/local/src/start.sh 52 | ``` 53 | 54 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit Dart runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/dart-2.16). 55 | 56 | ## 📝 Notes 57 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 58 | - This example is compatible with Dart 2.16. Other versions may work but are not guaranteed to work as they haven't been tested. Versions below Dart 2.14 will not work, because Apwrite SDK requires Dart 2.14, -------------------------------------------------------------------------------- /dart/object_detection/lib/main.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | import 'dart:io'; 3 | import 'package:http/http.dart' as http; 4 | 5 | Future start(final req, final res) async { 6 | final APIKey = req.variables["CLOUDMERSIVE_API_KEY"]; 7 | 8 | Map data = jsonDecode(req.payload); 9 | 10 | if (!data.containsKey("url")) { 11 | throw new Exception("Missing url"); 12 | } 13 | 14 | if (req.variables['CLOUDMERSIVE_API_KEY'] == null) { 15 | throw new Exception("Missing Cloudmersive API Key in environment variables"); 16 | } 17 | 18 | final url = data["url"]; 19 | 20 | // Download image into buffer 21 | var parsedUrl = Uri.parse(url); 22 | var response = await http.get(parsedUrl); 23 | 24 | if (response.statusCode != 200) { 25 | throw new Exception("Failed to download image"); 26 | } 27 | 28 | var imageBuffer = response.bodyBytes; 29 | 30 | var request = new http.MultipartRequest('POST', Uri.parse("https://api.cloudmersive.com/image/recognize/detect-objects")) 31 | ..files.add(new http.MultipartFile.fromBytes('imageFile', imageBuffer)) 32 | ..headers['Apikey'] = APIKey; 33 | 34 | // Call Cloudmersive OCR API 35 | var cloudmersiveResponse = await request.send(); 36 | 37 | // Parse response 38 | var responseBody = await cloudmersiveResponse.stream.bytesToString(); 39 | Map parsedBody = jsonDecode(responseBody); 40 | 41 | if (parsedBody["Objects"] == null) { 42 | throw new Exception("No objects detected"); 43 | } 44 | 45 | res.json(parsedBody["Objects"][0]); 46 | } -------------------------------------------------------------------------------- /dart/object_detection/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: object_detection 2 | description: "" 3 | version: 1.0.0 4 | 5 | environment: 6 | sdk: '>=2.14.0 <3.0.0' 7 | 8 | dependencies: 9 | http: ^0.13.4 -------------------------------------------------------------------------------- /dart/send-email-with-mailgun/README.md: -------------------------------------------------------------------------------- 1 | # 📧 Sending Welcome Emails using Mailgun's Email API 2 | 3 | 4 | 5 | A sample Dart Cloud Function for sending emails using the Mailgun API. 6 | 7 | 8 | _Example input:_ 9 | 10 | ```json 11 | { 12 | "name": "John Doe", 13 | "email": "johndoe@gmail.com" 14 | } 15 | ``` 16 | 17 | 18 | _Example output:_ 19 | 20 | 21 | ``` 22 | email sent successfully. 23 | ``` 24 | 25 | ## 📝 Environment Variables 26 | 27 | List of environment variables used by this cloud function: 28 | 29 | * **MAILGUN_API_KEY** - API Key for Mailgun 30 | * **MAILGUN_DOMAIN** - Domain Name from Mailgun 31 | 32 | ## 🚀 Deployment 33 | 34 | 1. Clone this repository, and enter this function folder: 35 | 36 | ``` 37 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 38 | $ cd dart/send-email-with-mailgun 39 | ``` 40 | 41 | 2. Enter this function folder and build the code: 42 | ``` 43 | docker run -e INTERNAL_RUNTIME_ENTRYPOINT=lib/main.dart --rm --interactive --tty --volume $PWD:/usr/code openruntimes/dart:v2-2.15 sh /usr/local/src/build.sh 44 | ``` 45 | As a result, a `code.tar.gz` file will be generated. 46 | 47 | 3. Start the Open Runtime: 48 | ``` 49 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_KEY=secret-key --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/dart:v2-2.15 sh /usr/local/src/start.sh 50 | ``` 51 | 52 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit Dart runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/dart-2.15). 53 | 54 | ## 📝 Notes 55 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 56 | - This example is compatible with Dart 2.13, 2.14 and 2.15. Other versions may work but are not guaranteed to work as they haven't been tested. 57 | -------------------------------------------------------------------------------- /dart/send-email-with-mailgun/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: send_email_with_mailgun 2 | description: "" 3 | version: 1.0.0 4 | 5 | environment: 6 | sdk: '>=2.12.0 <3.0.0' 7 | 8 | dependencies: 9 | http: ^0.13.3 10 | -------------------------------------------------------------------------------- /dart/send_push_notification/lib/fcm_service.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | 3 | import 'package:http/http.dart' as http; 4 | 5 | class FCMService { 6 | Future sendFCMToUser( 7 | {required String serverKey, 8 | required String userFCMToken, 9 | required Map notificationData}) async { 10 | try { 11 | await http.post( 12 | Uri.parse('https://fcm.googleapis.com/fcm/send'), 13 | headers: { 14 | 'Content-Type': 'application/json; charset=UTF-8', 15 | 'Authorization': 'key=$serverKey' 16 | }, 17 | body: jsonEncode({ 18 | 'to': userFCMToken, 19 | 'notification': notificationData 20 | }), 21 | ); 22 | } catch (e) { 23 | print(e); 24 | return false; 25 | } 26 | return true; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /dart/send_push_notification/lib/main.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | import 'fcm_service.dart'; 3 | 4 | void returnSuccess(final res, final message) { 5 | res.json({ 6 | 'success': true, 7 | 'message': message, 8 | }, status: 200); 9 | } 10 | 11 | void returnFailure(final res, final String message) { 12 | res.json({ 13 | 'success': false, 14 | 'message': message, 15 | }, status: 500); 16 | } 17 | 18 | bool checkEnvVariables(final req, final res) { 19 | if (req.variables['FMC_SERVER_KEY'] == null) { 20 | returnFailure(res, "Some Environment variables are not set"); 21 | return false; 22 | } 23 | return true; 24 | } 25 | 26 | bool checkPayload(Map payload, final res) { 27 | if (payload['user_token'] == null) { 28 | returnFailure(res, "Payload has incorrect data, user_token is empty"); 29 | return false; 30 | } 31 | return true; 32 | } 33 | 34 | FCMService? mockFCMService; 35 | 36 | Future start(final req, final res) async { 37 | if (!checkEnvVariables(req, res)) { 38 | return; 39 | } 40 | final String serverKey = req.variables['FMC_SERVER_KEY']; 41 | 42 | final payload = jsonDecode(req.payload == '' ? '{}' : req.payload); 43 | if (!checkPayload(payload, res)) { 44 | return; 45 | } 46 | 47 | final String userToken = payload['user_token']; 48 | 49 | final fcmService = mockFCMService ?? FCMService(); 50 | 51 | final Map notificationData = { 52 | 'title': "Awesome title!", 53 | 'body': "Awesome body", 54 | }; 55 | 56 | final isPushSent = await fcmService.sendFCMToUser( 57 | serverKey: serverKey, 58 | userFCMToken: userToken, 59 | notificationData: notificationData); 60 | 61 | if (isPushSent) { 62 | returnSuccess(res, "Push notification successfully sent"); 63 | } else { 64 | returnFailure(res, "Error while sending push notification"); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /dart/send_push_notification/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: send_push_notification 2 | description: "" 3 | version: 1.0.0 4 | 5 | environment: 6 | sdk: '>=2.17.0 <3.0.0' 7 | 8 | dependencies: 9 | http: ^0.13.5 10 | 11 | dev_dependencies: 12 | test: ^1.21.4 13 | mocktail: ^0.3.0 14 | -------------------------------------------------------------------------------- /deno/.gitignore: -------------------------------------------------------------------------------- 1 | *.orig 2 | *.pyc 3 | *.swp 4 | 5 | /.cargo_home/ 6 | /.idea/ 7 | /.vscode/ 8 | gclient_config.py_entries 9 | /gh-pages/ 10 | /target/ 11 | /std/hash/_wasm/target 12 | /tools/wpt/manifest.json 13 | 14 | # Files that help ensure VSCode can work but we don't want checked into the 15 | # repo 16 | /node_modules 17 | /tsconfig.json 18 | 19 | # compiled wasm files 20 | std/wasi/testdata/snapshot_preview1/ 21 | 22 | # generated v8 coverage files 23 | cli/tests/.test_coverage/ 24 | 25 | # MacOS generated files 26 | .DS_Store 27 | .DS_Store? 28 | 29 | # Flamegraphs 30 | /flamebench*.svg 31 | /flamegraph*.svg 32 | 33 | # WPT generated cert files 34 | /tools/wpt/certs/index.txt* 35 | /tools/wpt/certs/serial* -------------------------------------------------------------------------------- /deno/compress_image/README.md: -------------------------------------------------------------------------------- 1 | # 🔗 Compressing an image 2 | 3 | A Deno Cloud Function for compressing an image with two providers: 4 | - [Tinypng](https://tinypng.com/) 5 | - [Kraken.io](https://kraken.io/) 6 | 7 | _Example input:_ 8 | 9 | ```json 10 | { 11 | "provider": "tinypng", 12 | "image": "https://www.youtube.com/watch?v=Par3nEq739o" 13 | } 14 | ``` 15 | 16 | _Example output:_ 17 | 18 | ```json 19 | { 20 | "success":true, 21 | "image":"https:\/\/dl.kraken.io\/api\/3a\/4c\/93\/41fb5a7b65703c40965b7b727f\/9c75adab-2253-4d0f-ae31-09c94f265238.png" 22 | } 23 | ``` 24 | 25 | ## 📝 Variables 26 | 27 | For the provider Tinypng: 28 | - TINIFY_API_KEY 29 | 30 | For the provider Kraken.io: 31 | - KRAKEN_API_KEY 32 | - KRAKEN_API_SECRET 33 | 34 | ## 🚀 Deployment 35 | 36 | 1. Clone this repository, and enter this function folder: 37 | 38 | ``` 39 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 40 | $ cd deno/compress_image 41 | ``` 42 | 43 | 2. Enter this function folder and build the code: 44 | ``` 45 | docker run -e INTERNAL_RUNTIME_ENTRYPOINT=src/mod.ts --rm --interactive --tty --volume $PWD:/usr/code openruntimes/deno:v2-1.24 sh /usr/local/src/build.sh 46 | ``` 47 | As a result, a `code.tar.gz` file will be generated. 48 | 49 | 3. Start the Open Runtime: 50 | ``` 51 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_ENTRYPOINT=src/mod.ts -e INTERNAL_RUNTIME_KEY=secret-key --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/deno:v2-1.24 sh /usr/local/src/start.sh 52 | ``` 53 | 54 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit Deno runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/deno-1.24). 55 | 56 | ## 📝 Notes 57 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 58 | - This example is compatible with Deno 1.24. Other versions may work but are not guaranteed to work as they haven't been tested. -------------------------------------------------------------------------------- /deno/compress_image/src/deps.ts: -------------------------------------------------------------------------------- 1 | import { 2 | encode as base64Encode, 3 | decode as base64Decode 4 | } from "https://deno.land/std@0.82.0/encoding/base64.ts" 5 | 6 | export { base64Encode, base64Decode } -------------------------------------------------------------------------------- /deno/convert-phone-number-to-country-name/deps.ts: -------------------------------------------------------------------------------- 1 | export * as sdk from "https://deno.land/x/appwrite@3.0.0/mod.ts"; 2 | -------------------------------------------------------------------------------- /deno/deepgram-language-detection/src/mod.ts: -------------------------------------------------------------------------------- 1 | export default async function (req: any, res: any) { 2 | try { 3 | const APIkey = req.variables["DEEPGRAM_API_KEY"]; 4 | const fileUrl = JSON.parse(req.payload)["fileUrl"]; 5 | 6 | if (!APIkey) { 7 | return res.json({ 8 | success: false, 9 | message: "DEEPGRAM_API_KEY is not set", 10 | }); 11 | } 12 | 13 | if (!fileUrl) { 14 | return res.json({ 15 | success: false, 16 | message: "fileUrl is not provided", 17 | }); 18 | } 19 | 20 | const response = await fetch( 21 | "https://api.deepgram.com/v1/listen?model=general&detect_language=true&punctuate=true", 22 | { 23 | method: "POST", 24 | headers: { 25 | "Content-Type": "application/json", 26 | Authorization: `Token ${APIkey}`, 27 | }, 28 | body: JSON.stringify({ url: fileUrl }), 29 | } 30 | ); 31 | 32 | if (response.status !== 200) { 33 | if (response.status === 401) { 34 | return res.json({ 35 | success: false, 36 | message: `Status code: ${response.status}, Data: ${response.statusText} - Please check your Deepgram API key`, 37 | }); 38 | } 39 | 40 | const error = await response.json(); 41 | return res.json({ 42 | success: false, 43 | message: error.reason, 44 | }); 45 | } 46 | 47 | const data = await response.json(); 48 | 49 | res.json({ 50 | success: true, 51 | deepgramData: data, 52 | }); 53 | } catch (err) { 54 | console.log(err); 55 | res.json({ 56 | success: false, 57 | message: err.message, 58 | }); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /deno/deepgram-topic-detection/src/deps.ts: -------------------------------------------------------------------------------- 1 | export * as sdk from "https://raw.githubusercontent.com/MoskalykA/deepgram-deno-sdk/main/mod.ts" -------------------------------------------------------------------------------- /deno/deepgram-topic-detection/src/mod.ts: -------------------------------------------------------------------------------- 1 | import { sdk } from "./deps.ts" 2 | 3 | export default async function (req: any, res: any) { 4 | if (!req.variables.DEEPGRAM_API_KEY) { 5 | return res.json({ 6 | success: false, 7 | message: "The environment variables (DEEPGRAM_API_KEY) are required." 8 | }) 9 | } 10 | 11 | const { fileUrl } = req.payload 12 | if (!fileUrl) { 13 | return res.json({ 14 | success: false, 15 | message: "The link to the audio file is missing." 16 | }) 17 | } 18 | 19 | try { 20 | const deepgram = await sdk.default(req.variables.DEEPGRAM_API_KEY) 21 | const transcription = await deepgram.transcription.preRecorded({ 22 | url: fileUrl 23 | }, { 24 | punctuate: true, 25 | detect_topics: true 26 | }) 27 | 28 | res.json({ 29 | success: true, 30 | deepgramData: transcription.results 31 | }) 32 | } catch(e) { 33 | res.json({ 34 | success: false, 35 | message: e.toString() 36 | }) 37 | } 38 | } -------------------------------------------------------------------------------- /deno/deepgram-transcribe-audio/src/deps.ts: -------------------------------------------------------------------------------- 1 | export * as sdk from "https://raw.githubusercontent.com/deepgram-devs/deepgram-deno-sdk/main/mod.ts" -------------------------------------------------------------------------------- /deno/deepgram-transcribe-audio/src/mod.ts: -------------------------------------------------------------------------------- 1 | import { sdk } from "./deps.ts" 2 | 3 | export default async function (req: any, res: any) { 4 | if (!req.variables.DEEPGRAM_API_KEY) { 5 | return res.json({ 6 | success: false, 7 | message: "The environment variables (DEEPGRAM_API_KEY) are required." 8 | }) 9 | } 10 | 11 | const { fileUrl } = req.payload 12 | if (!fileUrl) { 13 | return res.json({ 14 | success: false, 15 | message: "The link to the audio file is missing." 16 | }) 17 | } 18 | 19 | try { 20 | const deepgram = await sdk.default(req.variables.DEEPGRAM_API_KEY) 21 | const transcription = await deepgram.transcription.preRecorded({ 22 | url: fileUrl 23 | }, { 24 | punctuate: true 25 | }) 26 | 27 | res.json({ 28 | success: true, 29 | deepgramData: transcription.results 30 | }) 31 | } catch(e) { 32 | res.json({ 33 | success: false, 34 | message: e.toString() 35 | }) 36 | } 37 | } -------------------------------------------------------------------------------- /deno/deepgram-transcribe-video/src/mod.ts: -------------------------------------------------------------------------------- 1 | export default async function (req: any, res: any) { 2 | // try catch everything 3 | try { 4 | const apikey = req.variables["DEEPGRAM_API_KEY"]; 5 | const fileUrl = JSON.parse(req.payload)["fileUrl"]; 6 | 7 | // error handling 8 | if (!apikey) { 9 | return res.json({ 10 | success: false, 11 | message: "Missing Deepgram API key", 12 | }); 13 | } 14 | 15 | if (!fileUrl) { 16 | return res.json({ 17 | success: false, 18 | message: "Missing fileUrl", 19 | }); 20 | } 21 | 22 | const response = await fetch( 23 | "https://api.deepgram.com/v1/listen?model=video", 24 | { 25 | method: "POST", 26 | headers: { 27 | "Content-Type": "application/json", 28 | Authorization: `Token ${apikey}`, 29 | }, 30 | body: JSON.stringify({ url: fileUrl }), 31 | } 32 | ); 33 | 34 | if (response.status !== 200) { 35 | if (response.status === 401) { 36 | return res.json({ 37 | success: false, 38 | message: `Status code: ${response.status}, Data: ${response.statusText} - Please check your Deepgram API key`, 39 | }); 40 | } 41 | 42 | const error = await response.json(); 43 | return res.json({ 44 | success: false, 45 | message: error.reason, 46 | }); 47 | } 48 | 49 | const data = await response.json(); 50 | 51 | return res.json({ 52 | success: true, 53 | deepgramData: data, 54 | }); 55 | } catch (error) { 56 | return res.json({ 57 | success: false, 58 | message: error.message, 59 | }); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /deno/deepgram_audio_summary/src/mod.ts: -------------------------------------------------------------------------------- 1 | export default async function (req: any, res: any) { 2 | try { 3 | const apikey = req.variables["DEEPGRAM_API_KEY"]; 4 | const fileUrl = JSON.parse(req.payload)["fileUrl"]; 5 | 6 | if (!apikey) { 7 | return res.json({ 8 | success: false, 9 | message: "Missing Deepgram API key", 10 | }); 11 | } 12 | 13 | if (!fileUrl) { 14 | return res.json({ 15 | success: false, 16 | message: "Missing fileUrl", 17 | }); 18 | } 19 | 20 | const response = await fetch( 21 | "https://api.deepgram.com/v1/listen?", 22 | { 23 | method: "POST", 24 | headers: { 25 | "Content-Type": "application/json", 26 | Authorization: `Token ${apikey}`, 27 | }, 28 | body: JSON.stringify({ url: fileUrl }), 29 | } 30 | ); 31 | 32 | if (response.status !== 200) { 33 | if (response.status === 401) { 34 | return res.json({ 35 | success: false, 36 | message: `Encountered an error trying to make a request: ${response.statusText}`, 37 | }); 38 | } 39 | 40 | const error = await response.json(); 41 | return res.json({ 42 | success: false, 43 | message: error.reason, 44 | }); 45 | } 46 | 47 | const data = await response.json(); 48 | 49 | return res.json({ 50 | success: true, 51 | deepgramData: data, 52 | }); 53 | } catch (error) { 54 | return res.json({ 55 | success: false, 56 | message: error.message, 57 | }); 58 | } 59 | } -------------------------------------------------------------------------------- /deno/generate_giphy_gif/README.md: -------------------------------------------------------------------------------- 1 | # 🖼️ Get Giphy GIF 2 | 3 | A Deno Cloud Function for generating Giphy GIF from the [Giphy API](https://developers.giphy.com/docs/api#quick-start-guide). 4 | 5 | _Example input:_ 6 | 7 | ```json 8 | { 9 | "search": "good morning" 10 | } 11 | ``` 12 | 13 | _Example output:_ 14 | 15 | 16 | ```json 17 | { 18 | "search": "good morning", 19 | "gif": "https://giphy.com/gifs/text-gif-sticker-brittdoesdesign-MS9Yq6Y718CSiDTxR5" 20 | } 21 | ``` 22 | 23 | ## 📝 Environment Variables 24 | 25 | List of environment variables used by this cloud function: 26 | 27 | **GIPHY_API_KEY** - Your Giphy API key. 28 | 29 | ## 🚀 Deployment 30 | 31 | 1. Clone this repository, and enter this function folder: 32 | 33 | ``` 34 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 35 | $ cd deno/generate_giphy_gif 36 | ``` 37 | 38 | 2. Enter this function folder and build the code: 39 | ``` 40 | docker run -e INTERNAL_RUNTIME_ENTRYPOINT=src/mod.ts --rm --interactive --tty --volume $PWD:/usr/code openruntimes/deno:v2-1.14 sh /usr/local/src/build.sh 41 | ``` 42 | As a result, a `code.tar.gz` file will be generated. 43 | 44 | 3. Start the Open Runtime: 45 | ``` 46 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_ENTRYPOINT=src/mod.ts -e INTERNAL_RUNTIME_KEY=secret-key --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/deno:v2-1.14 sh /usr/local/src/start.sh 47 | ``` 48 | 49 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit Deno runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/deno-1.14). 50 | 51 | ## 📝 Notes 52 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 53 | - This example is compatible with Deno 1.13 and 1.14. Other versions may work but are not guarenteed to work as they haven't been tested. -------------------------------------------------------------------------------- /deno/generate_giphy_gif/src/mod.ts: -------------------------------------------------------------------------------- 1 | export default async function(req: any, res: any) { 2 | const APIkey = req.variables["GIPHY_API_KEY"] 3 | 4 | const { search } = JSON.parse(req.payload); 5 | 6 | if (!search) { 7 | throw new Error("search is required"); 8 | } 9 | 10 | if (!APIkey) { 11 | throw new Error("API key is required"); 12 | } 13 | 14 | // Fetch the gif 15 | const response = await fetch(`https://api.giphy.com/v1/gifs/search?api_key=${APIkey}&q=${search}&limit=1`, 16 | { 17 | method: "GET", 18 | headers: { 19 | "Apikey": APIkey, 20 | } 21 | }); 22 | 23 | // Check status code 24 | if (response.status !== 200) { 25 | throw new Error(`Status code: ${response.status}, Data: ${await response.text()}`); 26 | } 27 | 28 | // Parse the response 29 | const dataJson = await response.json(); 30 | 31 | res.json(dataJson["data"][0]['url']); 32 | } -------------------------------------------------------------------------------- /deno/generate_short_url/src/mod.ts: -------------------------------------------------------------------------------- 1 | export default async function (req: any, res: any) { 2 | const { provider, url } = JSON.parse(req.payload); 3 | 4 | if (!provider) { 5 | res.json({ success: false, message: "provider is required" }); 6 | return; 7 | } 8 | 9 | if (!url) { 10 | res.json({ success: false, message: "url is required" }); 11 | return; 12 | } 13 | 14 | if (provider === "bitly") { 15 | const BITLY_TOKEN = req.variables["BITLY_TOKEN"]; 16 | 17 | if (!BITLY_TOKEN) { 18 | res.json({ success: false, message: "BITLY_TOKEN is required" }); 19 | return; 20 | } 21 | 22 | const response = await fetch(`https://api-ssl.bitly.com/v4/shorten`, { 23 | method: "POST", 24 | headers: { 25 | "Content-Type": "application/json", 26 | Authorization: `Bearer ${BITLY_TOKEN}`, 27 | }, 28 | body: JSON.stringify({ 29 | long_url: url, 30 | }), 31 | }); 32 | 33 | if (response.status >= 400) { 34 | res.json({ success: false, code: response.status, message: `${await response.text()}` }); 35 | return; 36 | } 37 | 38 | const data = await response.json(); 39 | res.json({ success: true, url: data["link"] }); 40 | } else if (provider === "tinyurl") { 41 | const TINYURL_TOKEN = req.variables["TINYURL_TOKEN"]; 42 | 43 | if (!TINYURL_TOKEN) { 44 | res.json({ success: false, message: "TINYURL_TOKEN is required" }); 45 | return; 46 | } 47 | 48 | const response = await fetch(`https://api.tinyurl.com/create`, { 49 | method: "POST", 50 | headers: { 51 | "Content-Type": "application/json", 52 | Authorization: `Bearer ${TINYURL_TOKEN}`, 53 | }, 54 | body: JSON.stringify({ 55 | url: url, 56 | }), 57 | }); 58 | 59 | if (response.status !== 200) { 60 | res.json({ success: false, message: `${await response.text()}` }); 61 | return; 62 | } 63 | 64 | const data = await response.json(); 65 | res.json({ success: true, url: data.data.tiny_url }); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /deno/generate_website_screenshot/src/deps.ts: -------------------------------------------------------------------------------- 1 | import { 2 | decode as base64Decode, 3 | encode as base64Encode, 4 | } from 'https://deno.land/std@0.82.0/encoding/base64.ts'; 5 | 6 | export { base64Decode, base64Encode }; -------------------------------------------------------------------------------- /deno/generate_website_screenshot/src/mod.ts: -------------------------------------------------------------------------------- 1 | import { base64Encode } from "./deps.ts"; 2 | 3 | const getBase64FromUrl = async (url: string) => { 4 | const data = await fetch(url); 5 | 6 | if (data.ok) { 7 | const blob = await data.blob(); 8 | const arr = await blob.arrayBuffer(); 9 | const base64String = base64Encode(arr); 10 | return base64String; 11 | } else { 12 | throw new Error(await data.text()); 13 | } 14 | }; 15 | 16 | export default async function (req: any, res: any) { 17 | let APIkey: any; 18 | let url: any; 19 | 20 | try { 21 | const payload = JSON.parse(req.payload ?? '{}'); 22 | url = payload.url; 23 | } catch(error) { 24 | res.json({ success: false, message: "Please provide URL." }); 25 | return; 26 | } 27 | try { 28 | APIkey = req.variables["SCREEN_SHOT_API_KEY"]; 29 | } catch(error) { 30 | res.json({ success: false, message: "Please API key." }); 31 | return; 32 | } 33 | 34 | const fetchURL = `https://shot.screenshotapi.net/screenshot?token=${APIkey}&url=${url}&output=image&file_type=png&wait_for_event=load`; 35 | 36 | try { 37 | const response = await getBase64FromUrl(fetchURL); 38 | res.json({ success: true, screenshot: response }); 39 | return; 40 | } catch(error) { 41 | res.json({ success: false, message: error }); 42 | return; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /deno/object_detection/README.md: -------------------------------------------------------------------------------- 1 | # 📷 Object Detection using Cloudmersive Vision API 2 | 3 | A Deno Cloud Function for object detection from an image URL. 4 | 5 | _Example input:_ 6 | 7 | ```json 8 | { 9 | "url": "https://picsum.photos/id/237/200/300" 10 | } 11 | ``` 12 | 13 | _Example output:_ 14 | 15 | ```json 16 | [{ 17 | "ObjectClassName": "dog", 18 | "Height": 293, 19 | "Width": 198, 20 | "Score": 0.9331955909729004, 21 | "X": 1, 22 | "Y": 9 23 | }] 24 | ``` 25 | 26 | ## 📝 Environment Variables 27 | 28 | List of environment variables used by this cloud function: 29 | 30 | **CLOUDMERSIVE_API_KEY** - Your Cloudmersive API key. 31 | 32 | ## 🚀 Deployment 33 | 34 | 1. Clone this repository, and enter this function folder: 35 | 36 | ``` 37 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 38 | $ cd deno/object_detection 39 | ``` 40 | 41 | 2. Enter this function folder and build the code: 42 | ``` 43 | docker run -e INTERNAL_RUNTIME_ENTRYPOINT=src/mod.ts --rm --interactive --tty --volume $PWD:/usr/code openruntimes/deno:v2-1.14 sh /usr/local/src/build.sh 44 | ``` 45 | As a result, a `code.tar.gz` file will be generated. 46 | 47 | 3. Start the Open Runtime: 48 | ``` 49 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_ENTRYPOINT=src/mod.ts -e INTERNAL_RUNTIME_KEY=secret-key --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/deno:v2-1.14 sh /usr/local/src/start.sh 50 | ``` 51 | 52 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit Deno runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/deno-1.14). 53 | 54 | ## 📝 Notes 55 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 56 | - This example is compatible with Deno 1.13 and 1.14. Other versions may work but are not guarenteed to work as they haven't been tested. -------------------------------------------------------------------------------- /deno/object_detection/src/mod.ts: -------------------------------------------------------------------------------- 1 | export default async function(req: any, res: any) { 2 | const APIkey = req.variables["CLOUDMERSIVE_API_KEY"] 3 | 4 | const { url } = JSON.parse(req.payload); 5 | 6 | if (!url) { 7 | throw new Error("URL is required"); 8 | } 9 | 10 | if (!APIkey) { 11 | throw new Error("API key is required"); 12 | } 13 | 14 | // Download the image 15 | const image = await fetch(url).then((response) => response.blob()); 16 | 17 | // Run the image through the Cloudmersive OCR API 18 | var data = new FormData(); 19 | data.append('imageFile', image, 'file'); 20 | 21 | const response = await fetch("https://api.cloudmersive.com/image/recognize/detect-objects", 22 | { 23 | method: "POST", 24 | headers: { 25 | "Apikey": APIkey, 26 | }, 27 | body: data, 28 | }); 29 | 30 | // Check status code 31 | if (response.status !== 200) { 32 | throw new Error(`Status code: ${response.status}, Data: ${await response.text()}`); 33 | } 34 | 35 | // Parse the response 36 | const dataJson = await response.json(); 37 | 38 | res.json(dataJson["Objects"]); 39 | } -------------------------------------------------------------------------------- /deno/send_email_with_mailgun/README.md: -------------------------------------------------------------------------------- 1 | # 📧 Sending Welcome Emails using Mailgun's Email API 2 | 3 | A sample Deno Cloud Function for sending emails using the Mailgun API. 4 | 5 | _Example input:_ 6 | 7 | ```json 8 | { 9 | "name": "John Doe", 10 | "email": "johndoe@gmail.com" 11 | } 12 | ``` 13 | 14 | 15 | _Example output:_ 16 | 17 | 18 | ``` 19 | email sent successfully. 20 | ``` 21 | 22 | ## 📝 Environment Variables 23 | 24 | List of environment variables used by this cloud function: 25 | 26 | * **MAILGUN_API_KEY** - API Key for Mailgun 27 | * **MAILGUN_DOMAIN** - Domain Name from Mailgun 28 | 29 | ## 🚀 Deployment 30 | 31 | 1. Clone this repository, and enter this function folder: 32 | 33 | ``` 34 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 35 | $ cd deno/send_email_with_mailgun 36 | ``` 37 | 38 | 2. Enter this function folder and build the code: 39 | ``` 40 | docker run -e INTERNAL_RUNTIME_ENTRYPOINT=src/mod.ts --rm --interactive --tty --volume $PWD:/usr/code openruntimes/deno:v2-1.14 sh /usr/local/src/build.sh 41 | ``` 42 | As a result, a `code.tar.gz` file will be generated. 43 | 44 | 3. Start the Open Runtime: 45 | ``` 46 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_ENTRYPOINT=src/mod.ts -e INTERNAL_RUNTIME_KEY=secret-key --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/deno:v2-1.14 sh /usr/local/src/start.sh 47 | ``` 48 | 49 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit Deno runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/deno-1.14). 50 | 51 | ## 📝 Notes 52 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 53 | - This example is compatible with Deno 1.13 and 1.14. Other versions may work but are not guarenteed to work as they haven't been tested. -------------------------------------------------------------------------------- /deno/send_email_with_mailgun/src/mod.ts: -------------------------------------------------------------------------------- 1 | export default async function(req: any, res: any) { 2 | // Create a new MailGunClient and pass it your API key and API domain 3 | const domain = req.variables["MAILGUN_DOMAIN"]; 4 | const apiKey = req.variables["MAILGUN_API_KEY"]; 5 | 6 | // Get the name and email of the newly created user from Appwrite's environment variable 7 | const payload = JSON.parse(req.payload); 8 | const userName = payload["name"]; 9 | const email = payload["email"]; 10 | 11 | // Create your email 12 | const form = new FormData(); 13 | form.append("from", "Welcome to My Awesome App "); 14 | form.append("to", email); 15 | form.append("subject", `Welcome on board ${userName}!`); 16 | form.append("text", `Hi ${userName}\nGreat to have you with us. !`); 17 | 18 | // Send the email! 19 | fetch(`https://api.mailgun.net/v3/${domain}/messages`, { 20 | method: "POST", 21 | headers: { 22 | Authorization: `Basic ${btoa("api:" + apiKey)}`, 23 | }, 24 | body: form, 25 | }); 26 | 27 | res.send("Success"); 28 | } -------------------------------------------------------------------------------- /deno/send_http_request/src/mod.ts: -------------------------------------------------------------------------------- 1 | export default async function (req: any, res: any) { 2 | const { url, headers, method, body } = JSON.parse(req.payload); 3 | 4 | if (!url) { 5 | throw new Error("url is required"); 6 | } 7 | 8 | if (!method) { 9 | throw new Error("method is required"); 10 | } 11 | 12 | const response = await fetch(url, { method, headers, body: body ? JSON.stringify(body) : undefined }); 13 | 14 | if (response.status !== 200) { 15 | res.json({ success: false, message: "URL could not be reached." }); 16 | } 17 | 18 | const data = await response.json(); 19 | 20 | res.json({ 21 | success: true, 22 | response: { code: response.status, headers: response.headers, body: JSON.stringify(data) }, 23 | }); 24 | } -------------------------------------------------------------------------------- /deno/send_sms_with_twilio/src/mod.ts: -------------------------------------------------------------------------------- 1 | export default async function test(req: any, res: any) { 2 | const accountSID = req.variables["TWILIO_ACCOUNT_SID"]; 3 | const authToken = req.variables["TWILIO_AUTH_TOKEN"]; 4 | const sender = req.variables["TWILIO_SENDER"]; 5 | 6 | const { 7 | phoneNumber, 8 | text, 9 | } = JSON.parse(req.payload); 10 | 11 | let response = await fetch( 12 | `https://api.twilio.com/2010-04-01/Accounts/${accountSID}/Messages.json`, 13 | { 14 | method: "POST", 15 | headers: { 16 | "Content-Type": "application/x-www-form-urlencoded", 17 | "Authorization": `Basic ${btoa(`${accountSID}:${authToken}`)}`, 18 | }, 19 | body: new URLSearchParams({ 20 | To: phoneNumber, 21 | From: sender, 22 | Body: text, 23 | }), 24 | }, 25 | ).then((res) => res.json()).then((data) => { 26 | return JSON.stringify(data); 27 | }).catch(console.error); 28 | 29 | res.send(response); 30 | } -------------------------------------------------------------------------------- /deno/translate_text_with_google/README.md: -------------------------------------------------------------------------------- 1 | # 🌐 Translate text from one language to another 2 | 3 | A Deno Cloud Function for translating text from one language to another using [Google Translate](https://translate.google.com/). 4 | 5 | _Example input:_ 6 | 7 | ```json 8 | { 9 | "text": "Hello from Open Runtimes 👋", 10 | "source": "en", 11 | "target": "es" 12 | } 13 | ``` 14 | 15 | _Example output:_ 16 | 17 | ```json 18 | { 19 | "text": "Hello from Open Runtimes 👋", 20 | "translation": "Saludos desde Open Runtime 👋" 21 | } 22 | ``` 23 | 24 | ## 📝 Environment Variables 25 | 26 | No environment variables needed. 27 | 28 | ## 🚀 Deployment 29 | 30 | 1. Clone this repository, and enter this function folder: 31 | 32 | ``` 33 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 34 | $ cd deno/translate_text_with_google 35 | ``` 36 | 37 | 2. Enter this function folder and build the code: 38 | ``` 39 | docker run -e INTERNAL_RUNTIME_ENTRYPOINT=src/mod.ts --rm --interactive --tty --volume $PWD:/usr/code openruntimes/deno:v2-1.14 sh /usr/local/src/build.sh 40 | ``` 41 | As a result, a `code.tar.gz` file will be generated. 42 | 43 | 3. Start the Open Runtime: 44 | ``` 45 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_ENTRYPOINT=src/mod.ts -e INTERNAL_RUNTIME_KEY=secret-key --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/deno:v2-1.14 sh /usr/local/src/start.sh 46 | ``` 47 | 48 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit Deno runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/deno-1.14). 49 | 50 | ## 📝 Notes 51 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 52 | - This example is compatible with Deno 1.13 and 1.14. Other versions may work but are not guarenteed to work as they haven't been tested. -------------------------------------------------------------------------------- /deno/translate_text_with_google/src/mod.ts: -------------------------------------------------------------------------------- 1 | import { GTR } from "https://deno.land/x/gtr/mod.ts"; 2 | 3 | export default async function (req: any, res: any) { 4 | const gtr = new GTR(); 5 | 6 | // Get the query parameters from Appwrite's environment variable 7 | const payload = JSON.parse(req.payload); 8 | const { text, source, target } = payload; 9 | 10 | // Send request 11 | try { 12 | const { trans } = await gtr.translate( 13 | text, 14 | { 15 | sourceLang: source, 16 | targetLang: target 17 | }, 18 | ); 19 | 20 | // Parse response 21 | res.send({ 22 | text: text, 23 | translation: trans 24 | }); 25 | } catch (e) { 26 | console.error(e); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /deno/wipe_appwrite_bucket/README.md: -------------------------------------------------------------------------------- 1 | # 🗑 Wipe Appwrite Bucket 2 | 3 | A Deno cloud function to wipe a complete bucket in Appwrite by passing the bucket id as a payload. 4 | 5 | _Example input:_ 6 | 7 | ```json 8 | { 9 | "bucketId":"profilePictures" 10 | } 11 | ``` 12 | 13 | _Example output:_ 14 | 15 | ```json 16 | { 17 | "success":true 18 | } 19 | ``` 20 | 21 | ## 📝 Environment Variables 22 | 23 | List of environment variables used by this cloud function: 24 | 25 | - **APPWRITE_FUNCTION_ENDPOINT** - Endpoint of Appwrite project 26 | - **APPWRITE_FUNCTION_API_KEY** - Appwrite API Key 27 | - **APPWRITE_FUNCTION_PROJECT_ID** - Appwrite project ID. If running on Appwrite, this variable is provided automatically. 28 | 29 | ## 🚀 Deployment 30 | 31 | There are two ways of deploying the Appwrite function, both having the same results, but each using a different process. We highly recommend using CLI deployment to achieve the best experience. 32 | 33 | ### Using CLI 34 | 35 | Make sure you have [Appwrite CLI](https://appwrite.io/docs/command-line#installation) installed, and you have successfully logged into your Appwrite server. To make sure Appwrite CLI is ready, you can use the command `appwrite client --debug` and it should respond with green text `✓ Success`. 36 | 37 | Make sure you are in the same folder as your `appwrite.json` file and run `appwrite deploy function` to deploy your function. You will be prompted to select which functions you want to deploy. 38 | 39 | ### Manual using tar.gz 40 | 41 | Manual deployment has no requirements and uses Appwrite Console to deploy the tag. First, enter the folder of your function. Then, create a tarball of the whole folder and gzip it. After creating `.tar.gz` file, visit Appwrite Console, click on the `Deploy Tag` button and switch to the `Manual` tab. There, set the `entrypoint` to `src/mod.ts`, and upload the file we just generated. 42 | -------------------------------------------------------------------------------- /deno/wipe_appwrite_bucket/src/deps.ts: -------------------------------------------------------------------------------- 1 | export * as sdk from "https://deno.land/x/appwrite@6.0.0/mod.ts"; 2 | -------------------------------------------------------------------------------- /deno/wipe_appwrite_bucket/src/mod.ts: -------------------------------------------------------------------------------- 1 | import { sdk } from "./deps.ts"; 2 | 3 | export default async function (req: any, res: any) { 4 | if ( 5 | !req.variables["APPWRITE_FUNCTION_ENDPOINT"] || 6 | !req.variables["APPWRITE_FUNCTION_PROJECT_ID"] || 7 | !req.variables["APPWRITE_FUNCTION_API_KEY"] || 8 | !req.payload 9 | ) { 10 | return res.json({ 11 | success: false, 12 | message: "Missing required environment variables or payload.", 13 | }); 14 | } 15 | let bucketId = ""; 16 | try { 17 | const payload = JSON.parse(req.payload); 18 | bucketId = payload.bucketId; 19 | } catch (_err) { 20 | return res.json({ 21 | success: false, 22 | message: "Payload is invalid.", 23 | }); 24 | } 25 | const client = new sdk.Client(); 26 | const storage = new sdk.Storage(client); 27 | 28 | client 29 | .setEndpoint(req.variables["APPWRITE_FUNCTION_ENDPOINT"]) 30 | .setProject(req.variables["APPWRITE_FUNCTION_PROJECT_ID"]) 31 | .setKey(req.variables["APPWRITE_FUNCTION_API_KEY"]); 32 | 33 | try { 34 | while (true) { 35 | const listFiles = await storage.listFiles(bucketId); 36 | if (listFiles.total === 0) { 37 | return res.json({ 38 | success: true, 39 | }); 40 | } 41 | const promises = listFiles.files.map((file) => storage.deleteFile(bucketId, file.$id)); 42 | await Promise.all(promises); 43 | } 44 | } catch (_err) { 45 | return res.json({ 46 | success: false, 47 | message: "Bucket not found.", 48 | }); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /dotnet/generateShortUrl/Function.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | Exe 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /dotnet/generateShortUrl/README.md: -------------------------------------------------------------------------------- 1 | # generateShortUrl 2 | 3 | Welcome to the documentation of this function 👋 4 | 5 | ## 🤖 Documentation 6 | 7 | Generates a short URL using the `bitly` and `tinyurl` APIs. 8 | 9 | _Example payload:_ 10 | 11 | ```json 12 | { 13 | "provider":"bitly", 14 | "url":"https://google.com/" 15 | } 16 | ``` 17 | 18 | _Example successful response:_ 19 | 20 | ```json 21 | { 22 | "success":true, 23 | "url":"https:\/\/bit.ly\/3DGAJF8" 24 | } 25 | ``` 26 | 27 | _Example failure response:_ 28 | 29 | ```json 30 | { 31 | "success":false, 32 | "message":"The value provided is invalid." 33 | } 34 | ``` 35 | 36 | ## 📝 Environment Variables 37 | 38 | This cloud function needs the following environment variables: 39 | 40 | - `BITLY_API_KEY`: Bitly API Access Token 41 | - `TINYURL_API_KEY`: Tinyurl API Key 42 | 43 | ℹ️ *Note: Learn how to create the [Bitly](https://dev.bitly.com/) and [Tinyurl](https://tinyurl.com/app/dev) API Keys via their docs.* 44 | 45 | ## 🚀 Deployment 46 | 47 | There are two ways of deploying the Appwrite function, both having the same results, but each using a different process. We highly recommend using CLI deployment to achieve the best experience. 48 | 49 | ### Using CLI 50 | 51 | Make sure you have [Appwrite CLI](https://appwrite.io/docs/command-line#installation) installed, and you have successfully logged into your Appwrite server. To make sure Appwrite CLI is ready, you can use the command `appwrite client --debug` and it should respond with green text `✓ Success`. 52 | 53 | Make sure you are in the same folder as your `appwrite.json` file and run `appwrite deploy function` to deploy your function. You will be prompted to select which functions you want to deploy. 54 | 55 | ### Manual using tar.gz 56 | 57 | Manual deployment has no requirements and uses Appwrite Console to deploy the tag. First, enter the folder of your function. Then, create a tarball of the whole folder and gzip it. After creating `.tar.gz` file, visit Appwrite Console, click on the `Deploy Tag` button and switch to the `Manual` tab. There, set the `entrypoint` to `src/Index.cs`, and upload the file we just generated. 58 | -------------------------------------------------------------------------------- /dotnet/wipe_appwrite_collection/AppwriteDatabaseClient.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using wipeAppwriteCollection.Models; 3 | 4 | namespace wipeAppwriteCollection; 5 | 6 | public class AppwriteDatabaseClient 7 | { 8 | private readonly HttpClient httpClient; 9 | 10 | public AppwriteDatabaseClient(string baseUrl, string apiKey, string projectId) 11 | { 12 | httpClient = new HttpClient 13 | { 14 | BaseAddress = new Uri(baseUrl), 15 | }; 16 | 17 | httpClient.DefaultRequestHeaders.Add("X-Appwrite-Key", apiKey); 18 | httpClient.DefaultRequestHeaders.Add("X-Appwrite-Project", projectId); 19 | } 20 | 21 | public async Task ListDocuments(string databaseId, string collectionId, int? limit = 25) 22 | { 23 | var response = await httpClient.GetAsync($"/v1/databases/{databaseId}/collections/{collectionId}/documents?limit={limit}"); 24 | var responseStr = await response.Content.ReadAsStringAsync(); 25 | var parsedResponse = JsonConvert.DeserializeObject(responseStr); 26 | return parsedResponse; 27 | } 28 | 29 | public async Task DeleteDocument(string databaseId, string collectionId, string documentId) 30 | { 31 | await httpClient.DeleteAsync($"/v1/databases/{databaseId}/collections/{collectionId}/documents/{documentId}"); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /dotnet/wipe_appwrite_collection/Models/Document.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace wipeAppwriteCollection.Models; 4 | 5 | public class Document 6 | { 7 | [JsonProperty("$id")] 8 | public string Id { get; set; } 9 | } 10 | -------------------------------------------------------------------------------- /dotnet/wipe_appwrite_collection/Models/ListDocumentsResponse.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace wipeAppwriteCollection.Models; 4 | 5 | public class ListDocumentsResponse 6 | { 7 | [JsonProperty("total")] 8 | public int Total { get; set; } 9 | 10 | [JsonProperty("documents")] 11 | public Document[] Documents { get; set; } 12 | } 13 | -------------------------------------------------------------------------------- /dotnet/wipe_appwrite_collection/wipeAppwriteCollection.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net6.0 5 | enable 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /java/deepgramLanguageDetection/deps.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | implementation 'com.google.code.gson:gson:2.9.0' 3 | implementation 'commons-validator:commons-validator:1.7' 4 | } -------------------------------------------------------------------------------- /java/deepgram_audio_summary/deps.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | implementation 'com.google.code.gson:gson:2.9.0' 3 | implementation 'commons-validator:commons-validator:1.7' 4 | } -------------------------------------------------------------------------------- /java/generate_invoice/deps.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | implementation 'com.google.code.gson:gson:2.9.0' 3 | implementation 'com.itextpdf:itextpdf:5.5.13.3' 4 | } -------------------------------------------------------------------------------- /java/generate_qr_code/README.md: -------------------------------------------------------------------------------- 1 | # 🖼️ Generate QR Code 2 | 3 | A Java Cloud Function to generate QR code for the given text. 4 | 5 | ``` 6 | http://localhost:3000/?text=https://github.com/open-runtimes 7 | ``` 8 | 9 | _Example output:_ 10 | 11 | ![successful_response](images/successful_response.png) 12 | 13 | 14 | _Error Example output:_ 15 | 16 | ```json 17 | { 18 | "success": false, 19 | "message": "Required fields are not present: text" 20 | } 21 | ``` 22 | 23 | ## 📝 Environment Variables 24 | 25 | This function does not require any variables. 26 | 27 | ## 🚀 Deployment 28 | 29 | 1. Clone this repository, and enter this function folder: 30 | 31 | ``` 32 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 33 | $ cd java/generate_qr_code 34 | ``` 35 | 36 | 2. Build the code using Docker: 37 | ``` 38 | docker run -e OPEN_RUNTIMES_ENTRYPOINT=Index.java --rm --interactive --tty --volume $PWD:/mnt/code openruntimes/java:v4-8.0 sh helpers/build.sh 39 | ``` 40 | As a result, a `code.tar.gz` file will be generated. 41 | 42 | 3. Start the Open Runtime: 43 | ``` 44 | docker run -p 3000:3000 -e OPEN_RUNTIMES_SECRET="" --rm --interactive --tty --volume $PWD/code.tar.gz:/mnt/code/code.tar.gz:ro openruntimes/java:v4-8.0 sh helpers/start.sh "java -jar /usr/local/server/src/function/java-runtime-1.0.0.jar" 45 | ``` 46 | 47 | Your function is now listening on port `3000`, and you can execute it using curl request with appropriate authorization headers. To learn more about runtime, you can visit Java runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/java-18.0). 48 | 49 | 4. In a new terminal window, execute function: 50 | 51 | ``` 52 | curl http://localhost:3000/?text=https://github.com/open-runtimes 53 | ``` 54 | 55 | ## 📝 Notes 56 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 57 | - This example is compatible with Java 18.0. Other versions may work but are not guaranteed to work as they haven't been tested. 58 | -------------------------------------------------------------------------------- /java/generate_qr_code/deps.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | implementation 'io.nayuki:qrcodegen:1.4.0' 3 | } 4 | -------------------------------------------------------------------------------- /java/generate_qr_code/images/successful_response.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/open-runtimes/examples/835a1194d3af546a9a6fc08cfbc66f29f3024db8/java/generate_qr_code/images/successful_response.png -------------------------------------------------------------------------------- /java/get_price/Index.java: -------------------------------------------------------------------------------- 1 | import com.google.gson.Gson; 2 | import yahoofinance.Stock; 3 | import yahoofinance.YahooFinance; 4 | 5 | import java.io.IOException; 6 | import java.math.BigDecimal; 7 | import java.util.HashMap; 8 | import java.util.Map; 9 | 10 | final Gson gson = new Gson(); 11 | 12 | final Map SYMBOLS = Map.of( 13 | "amazon", "AMZN", 14 | "bitcoin", "BTC-USD", 15 | "ethereum", "ETH-USD", 16 | "gold", "GC=F", 17 | "google", "GOOG", 18 | "silver", "SI=F" 19 | ); 20 | 21 | public RuntimeResponse main(RuntimeRequest req, RuntimeResponse res) { 22 | String payloadString = req.getPayload(); 23 | Map payload = gson.fromJson(payloadString, Map.class); 24 | Map responseData = new HashMap<>(); 25 | 26 | String type = payload.get("type").toString(); 27 | String symbol = SYMBOLS.get(type); 28 | 29 | if (symbol == null) { 30 | responseData.put("success", false); 31 | responseData.put("message", "Type is not supported."); 32 | return res.json(responseData); 33 | } 34 | 35 | try { 36 | BigDecimal price = getPrice(symbol); 37 | responseData.put("success", true); 38 | responseData.put("price", price); 39 | 40 | return res.json(responseData); 41 | } catch (IOException ex) { 42 | responseData.put("success", false); 43 | responseData.put("message", ex.getMessage()); 44 | return res.json(responseData); 45 | } 46 | } 47 | 48 | private BigDecimal getPrice(String symbol) throws IOException { 49 | Stock stock = YahooFinance.get(symbol); 50 | BigDecimal price = stock.getQuote().getPrice(); 51 | return price; 52 | } -------------------------------------------------------------------------------- /java/get_price/README.md: -------------------------------------------------------------------------------- 1 | # 💻 Get Short URL 2 | 3 | A Java Cloud Function to get price of crypto. 4 | 5 | ```json 6 | { 7 | "payload": { 8 | "type": "gold" 9 | } 10 | } 11 | ``` 12 | 13 | _Example output:_ 14 | 15 | 16 | ```json 17 | { 18 | "success":true, 19 | "price":1643.1 20 | } 21 | ``` 22 | 23 | _Error Example output:_ 24 | 25 | ```json 26 | { 27 | "success": false, 28 | "message":"Type is not supported." 29 | } 30 | ``` 31 | 32 | 33 | ## 📝 Environment Variables 34 | 35 | List of environment variables used by this cloud function. 36 | 37 | ## 🚀 Deployment 38 | 39 | 1. Clone this repository, and enter this function folder: 40 | 41 | ``` 42 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 43 | $ cd java/get_price 44 | ``` 45 | 46 | 2. Enter this function folder and build the code: 47 | ``` 48 | docker run -e INTERNAL_RUNTIME_ENTRYPOINT=Index.java --rm --interactive --tty --volume $PWD:/usr/code openruntimes/java:v2-18.0 sh /usr/local/src/build.sh 49 | ``` 50 | As a result, a `code.tar.gz` file will be generated. 51 | 52 | 3. Start the Open Runtime: 53 | ``` 54 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_KEY=secret-key --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/java:v2-18.0 sh /usr/local/src/start.sh 55 | ``` 56 | 57 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit Java runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/java-18.0). 58 | 59 | ## 📝 Notes 60 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 61 | - This example is compatible with Java 18.0. Other versions may work but are not guarenteed to work as they haven't been tested. -------------------------------------------------------------------------------- /java/get_price/deps.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | implementation 'com.google.code.gson:gson:2.9.0' 3 | implementation 'com.yahoofinance-api:YahooFinanceAPI:3.16.0' 4 | } -------------------------------------------------------------------------------- /java/short_url_generator/deps.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | implementation 'com.google.code.gson:gson:2.9.0' 3 | implementation 'commons-validator:commons-validator:1.7' 4 | } -------------------------------------------------------------------------------- /kotlin/deepgram-transcribe-audio/README.md: -------------------------------------------------------------------------------- 1 | # 🧹 Deepgram Transcribe Audio 2 | 3 | A Cloud Function for transcribing audio using [Deepgram](https://deepgram.com/) 4 | 5 | _Example input:_ 6 | 7 | ```json 8 | { 9 | "fileUrl": "https://static.deepgram.com/examples/Bueller-Life-moves-pretty-fast.wav" 10 | } 11 | ``` 12 | 13 | _Example output:_ 14 | 15 | 16 | ```json 17 | { 18 | "deepgramData": {}, 19 | "success": true 20 | } 21 | ``` 22 | 23 | _Example error output:_ 24 | 25 | 26 | ```json 27 | { 28 | "success":false, 29 | "message":"Error Message" 30 | } 31 | ``` 32 | 33 | ## 📝 Environment Variables 34 | 35 | **DEEPGRAM_API_KEY** - Your Deepgram secret API key. 36 | Details are under link: [Deepgram_getting_started](https://developers.deepgram.com/documentation/getting-started/) 37 | 38 | ## 🚀 Deployment 39 | 40 | 1. Clone this repository, and enter this function folder: 41 | 42 | ``` 43 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 44 | $ cd kotlin/deepgram-transcribe-audio 45 | ``` 46 | 47 | 2. Build the code: 48 | 49 | ```bash 50 | docker run -e INTERNAL_RUNTIME_ENTRYPOINT=src/Index.kt --rm --interactive --tty --volume $PWD:/usr/code openruntimes/kotlin:v2-1.6 sh /usr/local/src/build.sh 51 | ``` 52 | 53 | 3. Spin-up open-runtime: 54 | 55 | ```bash 56 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_KEY=secret-key --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/kotlin:v2-1.6 sh /usr/local/src/start.sh 57 | ``` 58 | 59 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit Kotlin runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/kotlin-1.6). 60 | 61 | ## 📝 Notes 62 | 63 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 64 | -------------------------------------------------------------------------------- /kotlin/deepgram-transcribe-audio/deps.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | implementation 'com.google.code.gson:gson:2.9.0' 3 | } 4 | -------------------------------------------------------------------------------- /kotlin/generate-short-url/deps.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | implementation 'com.google.code.gson:gson:2.9.0' 3 | } -------------------------------------------------------------------------------- /kotlin/wipeAppwriteBucket/README.md: -------------------------------------------------------------------------------- 1 | # wipeAppwriteBucket() - Kotlin 2 | 3 | ## ⚡ Function Details 4 | 5 | Delete all files inside an Appwrite Storage bucket. 6 | Bucket ID should be received as payload. 7 | 8 | Gets list of files in batches and continue until files returned equals files available. 9 | Appwrite API will return at most 100 records at a time. 10 | 11 | Adds a 1 second delay after each batch of deletion to avoid overwhelming the server. 12 | 13 | ## 📝 Environment Variables 14 | 15 | List of environment variables used by this cloud function: 16 | 17 | - **APPWRITE_FUNCTION_ENDPOINT** - Endpoint of Appwrite project 18 | - **APPWRITE_FUNCTION_API_KEY** - Appwrite API Key 19 | 20 | ## Example input: 21 | 22 | ```json 23 | { 24 | "bucketId": "profilePictures" 25 | } 26 | ``` 27 | 28 | ## Example output: 29 | 30 | Successful response: 31 | 32 | ```json 33 | { 34 | "success": true 35 | } 36 | ``` 37 | 38 | Error response: 39 | 40 | ```json 41 | { 42 | "success": false, 43 | "message": "Error description" 44 | } 45 | ``` 46 | 47 | ## 🚀 Deployment 48 | 49 | There are two ways of deploying the Appwrite function, both having the same results, but each using a different process. It is highly recommended to use CLI deployment to achieve the best experience. 50 | 51 | ### Using CLI 52 | 53 | For instrunctions on using the Appwrite CLI check https://appwrite.io/docs/functions#deployFunction 54 | 55 | ### Manual using tar.gz 56 | 57 | Manual deployment has no requirements and uses Appwrite Console to deploy the tag. First, enter the folder of your function. Then, create a tarball of the whole folder and gzip it. After creating `.tar.gz` file, visit Appwrite Console, click on the `Deploy Tag` button and switch to the `Manual` tab. There, set the `entrypoint` to `src/Index.kt`, and upload the file just generated. 58 | -------------------------------------------------------------------------------- /kotlin/wipeAppwriteBucket/deps.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | implementation 'io.appwrite:sdk-for-kotlin:1.1.0' 3 | implementation 'com.google.code.gson:gson:2.9.0' 4 | } -------------------------------------------------------------------------------- /node/convert-phone-number-to-country-name/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "convert_phone_number_to_country_name", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "node-appwrite": "^5.0.0" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /node/deepgram-transcribe-video/index.js: -------------------------------------------------------------------------------- 1 | const axios = require("axios").default; 2 | 3 | module.exports = async (req, res) => { 4 | let fileUrl; 5 | try { 6 | const payload = JSON.parse(req.payload); 7 | fileUrl = payload.fileUrl; 8 | } catch (err) { 9 | res.json({ 10 | success: false, 11 | message: "Payload does not have a proper structure.", 12 | }); 13 | return; 14 | } 15 | let deepgramApiKey = req.variables["DEEPGRAM_API_KEY"]; 16 | 17 | //checks 18 | if (!deepgramApiKey) { 19 | res.json({ 20 | success: false, 21 | message: "Please provide Deepgram Api Key as an environment variable.", 22 | }); 23 | return; 24 | } 25 | if (!fileUrl) { 26 | res.json({ 27 | success: false, 28 | message: "Please provide a valid file URL.", 29 | }); 30 | return; 31 | } 32 | //setting headers 33 | let headers = { 34 | "content-type": "application/json", 35 | Authorization: `Token ${deepgramApiKey}`, 36 | }; 37 | 38 | //setting our file url 39 | let data = JSON.stringify({ 40 | url: fileUrl, 41 | }); 42 | 43 | //making the request 44 | try { 45 | const response = await axios.post( 46 | `https://api.deepgram.com/v1/listen?model=video`, 47 | data, 48 | { 49 | headers: headers, 50 | } 51 | ); 52 | if (response.status !== 200) { 53 | res.json({ 54 | success: false, 55 | message: response.data, 56 | }); 57 | return; 58 | } 59 | res.json({ 60 | success: true, 61 | deepgramData: response.data, 62 | }); 63 | } catch (error) { 64 | res.json({ success: false, message: error.toString() }); 65 | } 66 | }; 67 | -------------------------------------------------------------------------------- /node/deepgram-transcribe-video/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "deepgram-transcribe-video", 3 | "version": "1.0.0", 4 | "lockfileVersion": 2, 5 | "requires": true, 6 | "packages": { 7 | "": { 8 | "name": "deepgram-transcribe-video", 9 | "version": "1.0.0", 10 | "license": "ISC", 11 | "dependencies": { 12 | "axios": "0.26.1" 13 | } 14 | }, 15 | "node_modules/axios": { 16 | "version": "0.26.1", 17 | "resolved": "https://registry.npmjs.org/axios/-/axios-0.26.1.tgz", 18 | "integrity": "sha512-fPwcX4EvnSHuInCMItEhAGnaSEXRBjtzh9fOtsE6E1G6p7vl7edEeZe11QHf18+6+9gR5PbKV/sGKNaD8YaMeA==", 19 | "dependencies": { 20 | "follow-redirects": "^1.14.8" 21 | } 22 | }, 23 | "node_modules/follow-redirects": { 24 | "version": "1.15.2", 25 | "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.2.tgz", 26 | "integrity": "sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA==", 27 | "funding": [ 28 | { 29 | "type": "individual", 30 | "url": "https://github.com/sponsors/RubenVerborgh" 31 | } 32 | ], 33 | "engines": { 34 | "node": ">=4.0" 35 | }, 36 | "peerDependenciesMeta": { 37 | "debug": { 38 | "optional": true 39 | } 40 | } 41 | } 42 | }, 43 | "dependencies": { 44 | "axios": { 45 | "version": "0.26.1", 46 | "resolved": "https://registry.npmjs.org/axios/-/axios-0.26.1.tgz", 47 | "integrity": "sha512-fPwcX4EvnSHuInCMItEhAGnaSEXRBjtzh9fOtsE6E1G6p7vl7edEeZe11QHf18+6+9gR5PbKV/sGKNaD8YaMeA==", 48 | "requires": { 49 | "follow-redirects": "^1.14.8" 50 | } 51 | }, 52 | "follow-redirects": { 53 | "version": "1.15.2", 54 | "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.2.tgz", 55 | "integrity": "sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA==" 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /node/deepgram-transcribe-video/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "deepgram-transcribe-video", 3 | "version": "1.0.0", 4 | "description": "", 5 | "type": "commonjs", 6 | "main": "index.js", 7 | "scripts": { 8 | "test": "echo \"Error: no test specified\" && exit 1" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "axios": "0.26.1" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /node/deepgram_audio_summary/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "deepgram_audio_summary", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "axios": "^1.2.1" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /node/deepgram_audio_summary/src/index.js: -------------------------------------------------------------------------------- 1 | const axios = require('axios').default; 2 | 3 | module.exports = async (req, res) => { 4 | const APIkey = req.variables['DEEPGRAM_API_KEY']; 5 | const { fileUrl } = req.payload; 6 | 7 | if (!APIkey) { 8 | throw new Error('Deepgram API Key is required'); 9 | } 10 | 11 | if (!fileUrl) { 12 | throw new Error('fileUrl is required'); 13 | } 14 | 15 | const resp = await axios.post( 16 | 'https://api.deepgram.com/v1/listen?summarize=true&punctuate=true', 17 | { 18 | url: fileUrl, 19 | }, 20 | { 21 | headers: { 22 | 'content-type': 'application/json', 23 | Authorization: `Token ${APIkey}`, 24 | }, 25 | }, 26 | ); 27 | 28 | if (resp.status === 200) { 29 | res.json({ 30 | success: true, 31 | deepgramData: resp.data.results, 32 | }); 33 | } else { 34 | res.json({ success: false, message: 'Please provide a valid file URL.' }); 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /node/deepgram_topic_detection/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "deepgram_topic_detection", 3 | "version": "1.0.0", 4 | "description": "A Node Cloud Function that detect list of topic from spoken audio using [Deepgram API](https://developers.deepgram.com/documentation/).", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "@deepgram/sdk": "^1.10.1" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /node/deepgram_topic_detection/src/index.js: -------------------------------------------------------------------------------- 1 | const { Deepgram } = require("@deepgram/sdk"); 2 | 3 | module.exports = async (req, res) => { 4 | const { fileUrl } = JSON.parse(req.payload); 5 | const apiKey = req.variables["DEEPGRAM_API_KEY"]; 6 | 7 | if (!apiKey) { 8 | res.json({ 9 | success: false, 10 | message: "API key is required.", 11 | }); 12 | } 13 | 14 | if (!fileUrl) { 15 | res.json({ 16 | success: false, 17 | message: "wav file url is required.", 18 | }); 19 | } 20 | 21 | const deepgram = new Deepgram(apiKey); 22 | 23 | try { 24 | const response = await deepgram.transcription.preRecorded( 25 | { url: fileUrl, mimetype: "audio/wav" }, 26 | { detect_topics: true, punctuate: true } 27 | ); 28 | 29 | res.json({ 30 | success: true, 31 | deepgramData: response, 32 | }); 33 | } catch (error) { 34 | res.json({ 35 | success: false, 36 | message: "Please check file URL and API key.", 37 | error: error, 38 | }); 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /node/generate_giphy_gif/README.md: -------------------------------------------------------------------------------- 1 | # 🖼️ Get Giphy GIF 2 | 3 | A Node Cloud Function for generating Giphy GIF from the [Giphy API](https://developers.giphy.com/docs/api#quick-start-guide). 4 | 5 | _Example input:_ 6 | 7 | ```json 8 | { 9 | "search": "good morning" 10 | } 11 | ``` 12 | 13 | _Example output:_ 14 | 15 | 16 | ```json 17 | { 18 | "search": "good morning", 19 | "gif": "https://giphy.com/gifs/text-gif-sticker-brittdoesdesign-MS9Yq6Y718CSiDTxR5" 20 | } 21 | ``` 22 | 23 | ## 📝 Environment Variables 24 | 25 | List of environment variables used by this cloud function: 26 | 27 | **GIPHY_API_KEY** - Your Giphy API key. 28 | 29 | ## 🚀 Deployment 30 | 31 | 1. Clone this repository, and enter this function folder: 32 | 33 | ``` 34 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 35 | $ cd node/generate_giphy_gif 36 | ``` 37 | 38 | 2. Enter this function folder and build the code: 39 | ``` 40 | docker run --rm --interactive --tty --volume $PWD:/usr/code openruntimes/node:v2-17.0 sh /usr/local/src/build.sh 41 | ``` 42 | As a result, a `code.tar.gz` file will be generated. 43 | 44 | 3. Start the Open Runtime: 45 | ``` 46 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_ENTRYPOINT=src/index.js -e INTERNAL_RUNTIME_KEY=secret-key --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/node:v2-17.0 sh /usr/local/src/start.sh 47 | ``` 48 | 49 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit NodeJS runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/node-17.0). 50 | 51 | ## 📝 Notes 52 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 53 | - This example is compatible with NodeJS 17.0. Other versions may work but are not guarenteed to work as they haven't been tested. -------------------------------------------------------------------------------- /node/generate_giphy_gif/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "generate_giphy_gif", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "src/index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "axios": "^0.26.1" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /node/generate_giphy_gif/src/index.js: -------------------------------------------------------------------------------- 1 | const axios = require('axios').default; 2 | 3 | module.exports = async function (req, res) { 4 | const APIkey = req.variables["GIPHY_API_KEY"] 5 | 6 | const { 7 | search 8 | } = JSON.parse(req.payload); 9 | 10 | if (!search) { 11 | throw new Error("search is required"); 12 | } 13 | 14 | if (!APIkey) { 15 | throw new Error("API key is required"); 16 | } 17 | 18 | const response = await axios.get(`https://api.giphy.com/v1/gifs/search?api_key=${APIkey}&q=${search}&limit=1`, { 19 | headers: {'Apikey': APIkey} 20 | }) 21 | 22 | if (response.status !== 200) { 23 | throw new Error(`Status code: ${response.status}, Data: ${response.data}`); 24 | } 25 | 26 | const dataJson = response.data; 27 | 28 | res.json({ 29 | search: search, 30 | gif: dataJson["data"][0]['url'] 31 | }); 32 | }; -------------------------------------------------------------------------------- /node/generate_invoice/README.md: -------------------------------------------------------------------------------- 1 | # 🧾 Generate Invoice 2 | 3 | A Node Cloud Function for generating invoice. 4 | 5 | _Example input:_ 6 | 7 | ```json 8 | { 9 | 10 | "payload": { 11 | "currency":"EUR", 12 | "items":[{"name":"Web development","price":15}], 13 | "issuer":"Some\nIssuer", 14 | "customer":"Some\nCustomer", 15 | "vat":21 16 | } 17 | } 18 | ``` 19 | 20 | _Example output:_ 21 | 22 | 23 | ```json 24 | { 25 | "success":true, 26 | "invoice":"iVBORw0KGgoAAAANSUhEUgAAAaQAAALiCAY...QoH9hbkTPQAAAABJRU5ErkJggg==" 27 | } 28 | ``` 29 | 30 | ## 📝 Environment Variables 31 | 32 | List of environment variables used by this cloud function: 33 | 34 | 35 | ## 🚀 Deployment 36 | 37 | 1. Clone this repository, and enter this function folder: 38 | 39 | ``` 40 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 41 | $ cd node/generate_invoice 42 | ``` 43 | 44 | 2. Enter this function folder and build the code: 45 | ``` 46 | docker run --rm --interactive --tty --volume $PWD:/usr/code openruntimes/node:v2-16.0 sh /usr/local/src/build.sh 47 | ``` 48 | As a result, a `code.tar.gz` file will be generated. 49 | 50 | 3. Start the Open Runtime: 51 | ``` 52 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_ENTRYPOINT=src/index.js -e INTERNAL_RUNTIME_KEY=secret-key --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/node:v2-17.0 sh /usr/local/src/start.sh 53 | ``` 54 | 55 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit NodeJS runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/node-17.0). 56 | 57 | ## 📝 Notes 58 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 59 | - This example is compatible with NodeJS 17.0. Other versions may work but are not guarenteed to work as they haven't been tested. 60 | -------------------------------------------------------------------------------- /node/generate_invoice/Screenshot from 2022-10-03 23-09-25.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/open-runtimes/examples/835a1194d3af546a9a6fc08cfbc66f29f3024db8/node/generate_invoice/Screenshot from 2022-10-03 23-09-25.png -------------------------------------------------------------------------------- /node/generate_invoice/Screenshot from 2022-10-03 23-10-49.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/open-runtimes/examples/835a1194d3af546a9a6fc08cfbc66f29f3024db8/node/generate_invoice/Screenshot from 2022-10-03 23-10-49.png -------------------------------------------------------------------------------- /node/generate_invoice/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "invoice", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "pdfkit": "^0.13.0" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /node/generate_invoice/src/index.js: -------------------------------------------------------------------------------- 1 | const PDFDOC = require("pdfkit") 2 | const doc = new PDFDOC(); 3 | module.exports =(req,res)=>{ 4 | const {currency,items,issuer,customer,vat} = req.payload; 5 | console.log(issuer); 6 | if(!issuer || issuer ==="") return {status:false,message:"Please provide Issuer"} 7 | if(!customer || customer ==="") return {status:false,message:"Please provide Customer"} 8 | if(!vat) return {status:false,message:"Please provide Vat"} 9 | if(!currency || currency ==="") return {status:false,message:"Please provide Currency"} 10 | if(!items) return {status:false,message:"Please provide Items"} 11 | doc 12 | .fontSize(26).text("Invoice",{ 13 | align:"center", 14 | underline:true, 15 | lineGap:10, 16 | 17 | } ,100, 100); 18 | 19 | doc.moveDown(); 20 | doc.fontSize(15).text(`Issuer: ${issuer}`,{align:"left"}); 21 | doc.moveDown(); 22 | doc.text(`Customer: ${customer}`,{align:"left"}); 23 | doc.moveDown(); 24 | doc.text(`Currency: ${currency}`,{align:"left"}); 25 | doc.moveDown(); 26 | doc.text(`VAT: ${vat}%`,{align:"left"}); 27 | let totalPrice=0; 28 | doc.moveDown(); 29 | for (let index = 0; index < items.length; index++) { 30 | doc.text( 31 | `Items:${items[index].name} Price:${items[index].price}`, 32 | { 33 | x: 50, 34 | }, 35 | ); 36 | totalPrice += items[index].price; 37 | if (index === items.length - 1) { 38 | doc.moveDown(); 39 | doc.fontSize(20).text(`Total:${totalPrice}`, { 40 | x: 50, 41 | }); 42 | } 43 | doc.moveDown(); 44 | } 45 | doc.end(); 46 | const output = doc.read(); 47 | const string = output.toString("base64"); 48 | res.send({status:true,invoice:string}) 49 | } -------------------------------------------------------------------------------- /node/generate_map/README.md: -------------------------------------------------------------------------------- 1 | # 📱 Generate Map 2 | 3 | A Node Generate Map Function for generate a screenshot of map location using [OpenStreetMap](https://www.openstreetmap.org/). 4 | 5 | _Example input:_ 6 | 7 | ```json 8 | { 9 | "provider": "openstreets", 10 | "lat": 41.909986, 11 | "lng": 12.3959136 12 | } 13 | ``` 14 | 15 | _Example output:_ 16 | 17 | ```json 18 | { 19 | "success": "true", 20 | "image":"iVBORw0KGgoAAAANSUhEUgAAAaQAAALiCAY...QoH9hbkTPQAAAABJRU5ErkJggg==" 21 | } 22 | ``` 23 | 24 | ## 🚀 Deployment 25 | 26 | 1. Clone this repository, and enter this function folder: 27 | 28 | ``` 29 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 30 | $ cd node/generate_map 31 | ``` 32 | 33 | 2. Enter this function folder and build the code: 34 | ``` 35 | docker run --rm --interactive --tty --volume $PWD:/usr/code openruntimes/node:v2-17.0 sh /usr/local/src/build.sh 36 | ``` 37 | As a result, a `code.tar.gz` file will be generated. 38 | 39 | 3. Start the Open Runtime: 40 | ``` 41 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_ENTRYPOINT=src/index.js -e INTERNAL_RUNTIME_KEY=secret-key --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/node:v2-17.0 sh /usr/local/src/start.sh 42 | ``` 43 | 44 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit NodeJS runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/node-17.0). 45 | 46 | ## 📝 Notes 47 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 48 | - This example is compatible with NodeJS 17.0. Other versions may work but are not guarenteed to work as they haven't been tested. -------------------------------------------------------------------------------- /node/generate_map/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "generate_map", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "ajv": "^8.11.0", 14 | "ajv-errors": "^3.0.0", 15 | "undici": "^5.11.0" 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /node/get_covid_stats/README.md: -------------------------------------------------------------------------------- 1 | # 🦠 Get COVID-19 stats from an API 2 | 3 | A Node Cloud Function for fetching COVID information using [Covid19Api](https://covid19api.com/). 4 | 5 | _Example input:_ 6 | 7 | ```json 8 | { 9 | "country": "NZ" 10 | } 11 | ``` 12 | 13 | _Example output:_ 14 | 15 | 16 | ```json 17 | { 18 | "country": "New Zealand", 19 | "confirmedCasesToday": 2, 20 | "recoveredToday": 4, 21 | "deathsToday": 0 22 | } 23 | ``` 24 | 25 | ## 📝 Environment Variables 26 | 27 | No environment variables needed. 28 | 29 | ## 🚀 Deployment 30 | 31 | 1. Clone this repository, and enter this function folder: 32 | 33 | ``` 34 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 35 | $ cd node/get_covid_stats 36 | ``` 37 | 38 | 2. Enter this function folder and build the code: 39 | ``` 40 | docker run --rm --interactive --tty --volume $PWD:/usr/code openruntimes/node:v2-17.0 sh /usr/local/src/build.sh 41 | ``` 42 | As a result, a `code.tar.gz` file will be generated. 43 | 44 | 3. Start the Open Runtime: 45 | ``` 46 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_ENTRYPOINT=src/index.js -e INTERNAL_RUNTIME_KEY=secret-key --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/node:v2-17.0 sh /usr/local/src/start.sh 47 | ``` 48 | 49 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit NodeJS runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/node-17.0). 50 | 51 | ## 📝 Notes 52 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 53 | - This example is compatible with NodeJS 17.0. Other versions may work but are not guarenteed to work as they haven't been tested. 54 | -------------------------------------------------------------------------------- /node/get_covid_stats/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "get_covid_stats", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "src/index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "axios": "^0.26.1" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /node/get_covid_stats/src/index.js: -------------------------------------------------------------------------------- 1 | const axios = require('axios').default; 2 | 3 | module.exports = async function (req, res) { 4 | let countryId = ''; 5 | if (req.payload) { 6 | countryId = JSON.parse(req.payload).country; 7 | } 8 | 9 | const response = await axios.get(`https://api.covid19api.com/summary`); 10 | 11 | if (response.status !== 200) { 12 | throw new Error(`Status code: ${response.status}, Data: ${response.data}`); 13 | } 14 | 15 | const dataJson = response.data; 16 | 17 | if (countryId) { 18 | dataJson.Countries = dataJson.Countries.filter(country => 19 | country['Country'] === countryId || 20 | country['CountryCode'] === countryId || 21 | country['Slug'] === countryId); 22 | } 23 | 24 | let country = dataJson.Countries[0]['Country'] ?? 'The World'; 25 | let confirmedCasesToday = dataJson.Countries[0]['NewConfirmed'] ?? dataJson.Global.NewConfirmed; 26 | let deathsToday = dataJson.Countries[0]['NewDeaths'] ?? dataJson.Global.NewDeaths; 27 | let recoveredCasesToday = dataJson.Countries[0]['NewRecovered'] ?? dataJson.Global.NewRecovered; 28 | 29 | res.json({ 30 | country: country, 31 | confirmedCasesToday: confirmedCasesToday, 32 | deathsToday: deathsToday, 33 | recoveredCasesToday: recoveredCasesToday 34 | }); 35 | }; -------------------------------------------------------------------------------- /node/object_detection/README.md: -------------------------------------------------------------------------------- 1 | # 📷 Object Detection using Cloudmersive Vision API 2 | 3 | A Node Cloud Function for object detection from an image URL. 4 | 5 | _Example input:_ 6 | 7 | ```json 8 | { 9 | "url": "https://picsum.photos/seed/open___runtimes/1000/1000" 10 | } 11 | ``` 12 | 13 | _Example output:_ 14 | 15 | 16 | ```json 17 | { 18 | "url": "https://picsum.photos/seed/open___runtimes/1000/1000", 19 | "name": "cake", 20 | "confidence": 0.7977721691131592, 21 | "x": 21, 22 | "y": 5, 23 | "width": 494, 24 | "height": 333 25 | } 26 | ``` 27 | 28 | ## 📝 Environment Variables 29 | 30 | List of environment variables used by this cloud function: 31 | 32 | **CLOUDMERSIVE_API_KEY** - Your Cloudmersive API key. 33 | 34 | ## 🚀 Deployment 35 | 36 | 1. Clone this repository, and enter this function folder: 37 | 38 | ``` 39 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 40 | $ cd node/object_detection 41 | ``` 42 | 43 | 2. Enter this function folder and build the code: 44 | ``` 45 | docker run --rm --interactive --tty --volume $PWD:/usr/code openruntimes/node:v2-17.0 sh /usr/local/src/build.sh 46 | ``` 47 | As a result, a `code.tar.gz` file will be generated. 48 | 49 | 3. Start the Open Runtime: 50 | ``` 51 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_ENTRYPOINT=src/index.js -e INTERNAL_RUNTIME_KEY=secret-key --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/node:v2-17.0 sh /usr/local/src/start.sh 52 | ``` 53 | 54 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit NodeJS runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/node-17.0). 55 | 56 | ## 📝 Notes 57 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 58 | - This example is compatible with NodeJS 17.0. Other versions may work but are not guarenteed to work as they haven't been tested. -------------------------------------------------------------------------------- /node/object_detection/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "object_detection", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "src/index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "axios": "^0.26.1", 14 | "cloudmersive-image-api-client": "^1.3.1" 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /node/object_detection/src/index.js: -------------------------------------------------------------------------------- 1 | const CloudmersiveImageApiClient = require('cloudmersive-image-api-client'); 2 | const axios = require('axios').default; 3 | 4 | module.exports = async function(req, res) { 5 | let defaultClient = CloudmersiveImageApiClient.ApiClient.instance; 6 | let Apikey = defaultClient.authentications['Apikey']; 7 | Apikey.apiKey = req.variables["CLOUDMERSIVE_API_KEY"]; 8 | let payload = JSON.parse(req.payload); 9 | 10 | let apiInstance = new CloudmersiveImageApiClient.RecognizeApi(); 11 | 12 | let imageBlob = await axios.get(payload.url, { responseType: 'arraybuffer' }); 13 | 14 | let recognizeDetectObjectsPromise = (imageBlob) => { 15 | return new Promise ((resolve, reject) => { 16 | apiInstance.recognizeDetectObjects(imageBlob, (error, data, response) => { 17 | if (error) return reject(error); 18 | resolve(data); 19 | }); 20 | }) 21 | } 22 | 23 | let result = await recognizeDetectObjectsPromise(imageBlob.data); 24 | 25 | res.json(result.Objects); 26 | }; -------------------------------------------------------------------------------- /node/send_email_with_mailgun/README.md: -------------------------------------------------------------------------------- 1 | # 📧 Sending Welcome Emails using Mailgun's Email API 2 | 3 | A sample NodeJS Cloud Function for sending emails using the Mailgun API. 4 | 5 | 6 | _Example input:_ 7 | 8 | ```json 9 | { 10 | "name": "John Doe", 11 | "email": "johndoe@gmail.com" 12 | } 13 | ``` 14 | 15 | 16 | _Example output:_ 17 | 18 | 19 | ``` 20 | {"id":"","message":"Queued. Thank you."} 21 | ``` 22 | 23 | ## 📝 Environment Variables 24 | 25 | List of environment variables used by this cloud function: 26 | 27 | * **MAILGUN_API_KEY** - API Key for Mailgun 28 | * **MAILGUN_DOMAIN** - Domain Name from Mailgun 29 | 30 | ## 🚀 Deployment 31 | 32 | 1. Clone this repository, and enter this function folder: 33 | 34 | ``` 35 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 36 | $ cd node/send_email_with_mailgun 37 | ``` 38 | 39 | 2. Enter this function folder and build the code: 40 | ``` 41 | docker run --rm --interactive --tty --volume $PWD:/usr/code openruntimes/node:v2-17.0 sh /usr/local/src/build.sh 42 | ``` 43 | As a result, a `code.tar.gz` file will be generated. 44 | 45 | 3. Start the Open Runtime: 46 | ``` 47 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_ENTRYPOINT=src/index.js -e INTERNAL_RUNTIME_KEY=secret-key --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/node:v2-17.0 sh /usr/local/src/start.sh 48 | ``` 49 | 50 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit NodeJS runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/node-17.0). 51 | 52 | ## 📝 Notes 53 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 54 | - This example is compatible with NodeJS 17.0. Other versions may work but are not guarenteed to work as they haven't been tested. -------------------------------------------------------------------------------- /node/send_email_with_mailgun/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "send_email_with_mailgun", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "src/index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "mailgun-js": "^0.22.0" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /node/send_email_with_mailgun/src/index.js: -------------------------------------------------------------------------------- 1 | const mailgun = require("mailgun-js"); 2 | 3 | module.exports = async function (req, res) { 4 | const emailConfig = { 5 | apiKey: req.variables.MAILGUN_API_KEY, 6 | domain: req.variables.MAILGUN_DOMAIN 7 | }; 8 | const mg = mailgun(emailConfig); 9 | 10 | // Get the name and email of the newly created user from Appwrite's environment variable 11 | const payload = JSON.parse(req.payload) 12 | const name = payload['name'] 13 | const email = payload['email'] 14 | 15 | // Create your email 16 | const data = { 17 | from: 'Welcome to My Awesome App ', 18 | to: email, 19 | subject: `Welcome on board ${name}!`, 20 | text: `Hi ${name}\nGreat to have you with us. !` 21 | }; 22 | 23 | // Send the email! 24 | mg.messages().send(data, function (error, body) { 25 | res.send(body); 26 | }); 27 | }; -------------------------------------------------------------------------------- /node/send_http_request/README.md: -------------------------------------------------------------------------------- 1 | # 📱 Send Http Request 2 | 3 | A Node Cloud Function that send http request. 4 | 5 | _Example input function payload:_ 6 | 7 | ```json 8 | { 9 | "url": "https://demo.appwrite.io/v1/locale/countries/eu", 10 | "method": "GET", 11 | "headers": { "x-client-version": "1.0.0" }, 12 | "body": "" 13 | } 14 | ``` 15 | 16 | _Successful function response:_ 17 | 18 | ```json 19 | { 20 | "success":true, 21 | "response":{"headers":{},"code":200,"body":"{\"total\":27,\"countries\":[]}"} 22 | } 23 | ``` 24 | 25 | _Error function response:_ 26 | 27 | ```json 28 | { 29 | "success":false, 30 | "message":"URL could not be reached." 31 | } 32 | 33 | ``` 34 | 35 | ## 🚀 Deployment 36 | 37 | 1. Clone this repository, and enter this function folder: 38 | 39 | ```bash 40 | git clone https://github.com/open-runtimes/examples.git && cd examples 41 | cd node/send_http_request 42 | ``` 43 | 44 | 2. Enter this function folder and build the code: 45 | 46 | ```bash 47 | docker run --rm --interactive --tty --volume $PWD:/usr/code openruntimes/node:v2-16.0 sh /usr/local/src/build.sh 48 | ``` 49 | 50 | As a result, a `code.tar.gz` file will be generated. 51 | 52 | 1. Start the Open Runtime: 53 | 54 | ``` 55 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_KEY=secret-key -e INTERNAL_RUNTIME_ENTRYPOINT=index.js --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/node:v2-18.0 sh /usr/local/src/start.sh 56 | ``` 57 | 58 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit Node runtime [README](https://github.com/open-runtimes/open-runtimes/tree/6d07f73a5984a0014a3bd297499ecb4dcc0e38f4/runtimes/node-18.0). 59 | 60 | ## 📝 Notes 61 | 62 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 63 | - This example is compatible with Node 16.0. Other versions may work but are not guaranteed to work as they haven't been tested. 64 | -------------------------------------------------------------------------------- /node/send_http_request/index.js: -------------------------------------------------------------------------------- 1 | const axios = require("axios"); 2 | module.exports = async (req, res) => { 3 | let url, method, body, headers; 4 | 5 | try { 6 | const payload = JSON.parse(req.payload); 7 | url = payload.url; 8 | method = payload.method || undefined; 9 | headers = payload.headers || undefined; 10 | body = payload.body || undefined; 11 | } catch (err) { 12 | 13 | res.json({ success: false, message: "Payload does not have a proper structure." }); 14 | } 15 | 16 | const config = { 17 | method, 18 | url, 19 | data: body, 20 | headers, 21 | }; 22 | 23 | try { 24 | const response = await axios(config); // Request to Server 25 | 26 | res.json({ 27 | success: true, 28 | response: { 29 | headers: response.headers, 30 | code: response.status, 31 | body: response.data, 32 | }, 33 | }); 34 | } catch (error) { 35 | res.json({ success: false, message: "URL could not be reached." }); 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /node/send_http_request/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "send_http_request", 3 | "version": "1.0.0", 4 | "description": "", 5 | "type": "commonjs", 6 | "main": "index.js", 7 | "scripts": { 8 | "test": "echo \"Error: no test specified\" && exit 1" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "axios": "^1.0.0" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /node/send_sms_with_twilio/README.md: -------------------------------------------------------------------------------- 1 | # 📱 Send SMS with Twilio 2 | 3 | A Node Cloud Function for sending message to a phone number using [Twilio API](https://www.twilio.com/docs/usage/api). 4 | 5 | _Example input:_ 6 | 7 | ```json 8 | { 9 | "text": "Hello from Open Runtimes 👋", 10 | "phoneNumber": "+421XXXXXXXXX" 11 | } 12 | ``` 13 | 14 | _Example output:_ 15 | 16 | ```json 17 | { 18 | "messageId": "SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" 19 | } 20 | ``` 21 | 22 | ## 📝 Environment Variables 23 | 24 | List of environment variables used by this cloud function: 25 | 26 | - **TWILIO_ACCOUNT_SID** - Twilio account SID 27 | - **TWILIO_AUTH_TOKEN** - Twilio auth token 28 | - **TWILIO_SENDER** - Sender's phone number from Twilio 29 | 30 | ℹ️ _Find your Account SID and Auth Token at twilio.com/console._ 31 | 32 | ## 🚀 Deployment 33 | 34 | 1. Clone this repository, and enter this function folder: 35 | 36 | ``` 37 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 38 | $ cd node/send_sms_with_twilio 39 | ``` 40 | 41 | 2. Enter this function folder and build the code: 42 | ``` 43 | docker run --rm --interactive --tty --volume $PWD:/usr/code openruntimes/node:v2-17.0 sh /usr/local/src/build.sh 44 | ``` 45 | As a result, a `code.tar.gz` file will be generated. 46 | 47 | 3. Start the Open Runtime: 48 | ``` 49 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_ENTRYPOINT=src/index.js -e INTERNAL_RUNTIME_KEY=secret-key --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/node:v2-17.0 sh /usr/local/src/start.sh 50 | ``` 51 | 52 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit NodeJS runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/node-17.0). 53 | 54 | ## 📝 Notes 55 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 56 | - This example is compatible with NodeJS 17.0. Other versions may work but are not guarenteed to work as they haven't been tested. -------------------------------------------------------------------------------- /node/send_sms_with_twilio/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "send_sms_with_twilio", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "src/index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "axios": "^0.26.1" 14 | } 15 | } -------------------------------------------------------------------------------- /node/send_sms_with_twilio/src/index.js: -------------------------------------------------------------------------------- 1 | const axios = require('axios').default; 2 | 3 | module.exports = async function test(req, res) { 4 | const accountSID = req.variables["TWILIO_ACCOUNT_SID"]; 5 | const authToken = req.variables["TWILIO_AUTH_TOKEN"]; 6 | const sender = req.variables["TWILIO_SENDER"]; 7 | 8 | const { 9 | phoneNumber, 10 | text, 11 | } = JSON.parse(req.payload); 12 | 13 | let response = await axios({ 14 | method: 'POST', 15 | url: `https://api.twilio.com/2010-04-01/Accounts/${accountSID}/Messages.json`, 16 | auth: { 17 | username: accountSID, 18 | password: authToken 19 | }, 20 | data: new URLSearchParams({ 21 | From: sender, 22 | To: phoneNumber, 23 | Body: text 24 | }), 25 | }).then((data) => { 26 | return data; 27 | }).catch((e) => console.error(e)); 28 | 29 | res.json(response.data); 30 | }; -------------------------------------------------------------------------------- /node/translate_text/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "translate_text", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "src/index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "@vitalets/google-translate-api": "^8.0.0", 13 | "aws-sdk": "^2.1229.0", 14 | "axios": "^0.27.2" 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /node/translate_text/src/aws_provider.js: -------------------------------------------------------------------------------- 1 | const aws = require('aws-sdk') 2 | 3 | 4 | module.exports = async function(payload,variables){ 5 | const { 6 | text, 7 | from, 8 | to 9 | } = JSON.parse(payload); 10 | 11 | 12 | const { 13 | AWS_ACCESS_KEY, 14 | AWS_SECRET_KEY 15 | } = JSON.parse(variables); 16 | 17 | aws.config.region = 'us-east-1' 18 | aws.config.credentials = new aws.Credentials(AWS_ACCESS_KEY, AWS_SECRET_KEY) 19 | const params = { 20 | SourceLanguageCode: from, 21 | TargetLanguageCode: to, 22 | Text: text 23 | }; 24 | const translateService = new aws.Translate() 25 | 26 | const response = await translateService.translateText(params, (err, data) => { 27 | return data; 28 | }).promise().then(data => {return {success :true , message: data.TranslatedText, from: from};}).catch(e =>{return {success :false , message: e.message};} ) 29 | 30 | return response; 31 | } -------------------------------------------------------------------------------- /node/translate_text/src/azure_provider.js: -------------------------------------------------------------------------------- 1 | const axios = require('axios').default; 2 | 3 | module.exports = async function(payload, variables){ 4 | 5 | const { 6 | text, 7 | from, 8 | to 9 | } = JSON.parse(payload); 10 | 11 | const { 12 | TRANSLATOR_KEY, 13 | LOCATION 14 | } = JSON.parse(variables); 15 | 16 | 17 | 18 | let key = TRANSLATOR_KEY; 19 | let endpoint = "https://api.cognitive.microsofttranslator.com"; 20 | 21 | let location = LOCATION; 22 | const response = await axios({ 23 | baseURL: endpoint, 24 | url: '/translate', 25 | method: 'post', 26 | headers: { 27 | 'Ocp-Apim-Subscription-Key': key, 28 | 'Ocp-Apim-Subscription-Region': location, 29 | 'Content-type': 'application/json' 30 | }, 31 | params: { 32 | 'api-version': '3.0', 33 | 'from': from, 34 | 'to': [to] 35 | }, 36 | data: [{ 37 | 'text': text 38 | }], 39 | responseType: 'json' 40 | }).then((response) => {return {success: true, message: response.data[0]['translations'][0]['text'], from:from}}).catch(e => {console.error(e); return {success: false, message:e.message}}) 41 | 42 | return response; 43 | } -------------------------------------------------------------------------------- /node/translate_text/src/google_provider.js: -------------------------------------------------------------------------------- 1 | const translate = require('@vitalets/google-translate-api'); 2 | 3 | module.exports = async function(payload){ 4 | const { 5 | text, 6 | from, 7 | to 8 | } = JSON.parse(payload); 9 | 10 | let response = await translate(text, {to: to, from: from}).then((data) => { 11 | return {message: data.text, success: true, from: from}; 12 | }).catch((e) => {console.error(e); return {message: e.message, success: false}}); 13 | return response; 14 | } -------------------------------------------------------------------------------- /node/translate_text/src/index.js: -------------------------------------------------------------------------------- 1 | const googleProvider = require('./google_provider') 2 | const azureProvider = require('./azure_provider') 3 | const awsProvider = require('./aws_provider'); 4 | 5 | module.exports = async function(req, res) { 6 | const { 7 | provider, 8 | text 9 | } = JSON.parse(req.payload); 10 | 11 | let response ={}; 12 | 13 | if(provider==='google'){ 14 | response = await googleProvider(req.payload).catch((e)=>console.log(e)); 15 | } 16 | 17 | else if(provider==='azure'){ 18 | response = await azureProvider(req.payload, req.variables).catch((e)=>console.log(e)); 19 | } 20 | 21 | else if(provider==='aws'){ 22 | response = await awsProvider(req.payload, req.variables).catch((e)=>console.log(e)); 23 | } 24 | 25 | else{ 26 | response = { 27 | success : false, 28 | message : "The provider does not match the available providers" 29 | } 30 | } 31 | // console.log(response); 32 | res.json(response); 33 | }; -------------------------------------------------------------------------------- /node/translate_text_with_google/README.md: -------------------------------------------------------------------------------- 1 | # 🌐 Translate text from one language to another 2 | 3 | A NodeJS Cloud Function for translating text from one language to another using [Google Translate](https://translate.google.com/). 4 | 5 | _Example input:_ 6 | 7 | ```json 8 | { 9 | "text": "Hello from Open Runtimes 👋", 10 | "source": "en", 11 | "target": "es" 12 | } 13 | ``` 14 | 15 | _Example output:_ 16 | 17 | ```json 18 | { 19 | "text": "Hello from Open Runtimes 👋", 20 | "translation": "Saludos desde Open Runtime 👋" 21 | } 22 | ``` 23 | 24 | ## 📝 Environment Variables 25 | 26 | No environment variables needed. 27 | 28 | ## 🚀 Deployment 29 | 30 | 1. Clone this repository, and enter this function folder: 31 | 32 | ``` 33 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 34 | $ cd node/translate_text_with_google 35 | ``` 36 | 37 | 2. Enter this function folder and build the code: 38 | ``` 39 | docker run --rm --interactive --tty --volume $PWD:/usr/code openruntimes/node:v2-17.0 sh /usr/local/src/build.sh 40 | ``` 41 | As a result, a `code.tar.gz` file will be generated. 42 | 43 | 3. Start the Open Runtime: 44 | ``` 45 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_ENTRYPOINT=src/index.js -e INTERNAL_RUNTIME_KEY=secret-key --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/node:v2-17.0 sh /usr/local/src/start.sh 46 | ``` 47 | 48 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit NodeJS runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/node-17.0). 49 | 50 | ## 📝 Notes 51 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 52 | - This example is compatible with NodeJS 17.0. Other versions may work but are not guarenteed to work as they haven't been tested. -------------------------------------------------------------------------------- /node/translate_text_with_google/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "translate_text_with_google", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "src/index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "@vitalets/google-translate-api": "^8.0.0" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /node/translate_text_with_google/src/index.js: -------------------------------------------------------------------------------- 1 | const translate = require('@vitalets/google-translate-api'); 2 | 3 | module.exports = async function(req, res) { 4 | const { 5 | text, 6 | source, 7 | target 8 | } = JSON.parse(req.payload); 9 | 10 | let translation = await translate(text, {to: target, from: source}).then((data) => { 11 | return data; 12 | }).catch((e) => console.error(e)); 13 | 14 | res.json({ 15 | text: text, 16 | translation: translation.text 17 | }); 18 | }; -------------------------------------------------------------------------------- /node/url-shortener/index.js: -------------------------------------------------------------------------------- 1 | const bitly = require("bitly") 2 | const tinyurl = require("turl") 3 | 4 | module.exports = async function(req, res) { 5 | const { provider, url } = req.payload 6 | if (!provider) { 7 | return res.json({ 8 | success: false, 9 | message: "The provider is missing." 10 | }) 11 | } 12 | 13 | if (!url) { 14 | return res.json({ 15 | success: false, 16 | message: "The link is missing." 17 | }) 18 | } 19 | 20 | switch (provider) { 21 | case "bitly": { 22 | const bitlyClient = new bitly.BitlyClient(req.variables.BITLY_API_KEY, {}) 23 | bitlyClient.shorten(url) 24 | .then((url) => { 25 | return res.json({ 26 | success: true, 27 | url: url.link 28 | }) 29 | }) 30 | .catch((e) => { 31 | return res.json({ 32 | success: false, 33 | message: e.toString() 34 | }) 35 | }) 36 | 37 | break 38 | } 39 | 40 | case "tinyurl": { 41 | tinyurl.shorten(url) 42 | .then((url) => { 43 | return res.json({ 44 | success: true, 45 | url 46 | }) 47 | }) 48 | .catch((e) => { 49 | return res.json({ 50 | success: false, 51 | message: e.toString() 52 | }) 53 | }) 54 | 55 | break 56 | } 57 | 58 | default: { 59 | res.json({ 60 | success: false, 61 | message: "The provider is invalid." 62 | }) 63 | } 64 | } 65 | } -------------------------------------------------------------------------------- /node/url-shortener/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "url-shortener", 3 | "version": "1.0.0", 4 | "main": "index.js", 5 | "license": "MIT", 6 | "dependencies": { 7 | "bitly": "^7.1.2", 8 | "turl": "^1.1.2" 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /node/wipe_appwrite_bucket/README.md: -------------------------------------------------------------------------------- 1 | # 🚮 Wipe Appwrite Bucket 2 | 3 | This function deletes every file from a specified Appwrite Storage Bucket. 4 | 5 | ## 🤖 Documentation 6 | 7 | _Example input:_ 8 | 9 | ```JSON 10 | {"bucketId":"profilePictures"} 11 | ``` 12 | 13 | _Example output:_ 14 | 15 | ```json 16 | {"success":true} 17 | ``` 18 | 19 | ## 📝 Environment Variables 20 | 21 | List of environment variables used by this cloud function: 22 | 23 | - **APPWRITE_FUNCTION_ENDPOINT** - Endpoint of Appwrite project 24 | - **APPWRITE_FUNCTION_API_KEY** - Appwrite API Key 25 | 26 | ## 🚀 Deployment 27 | 28 | There are two ways of deploying the Appwrite function, both having the same results, but each using a different process. We highly recommend using CLI deployment to achieve the best experience. 29 | 30 | ### Using CLI 31 | 32 | Make sure you have [Appwrite CLI](https://appwrite.io/docs/command-line#installation) installed, and you have successfully logged into your Appwrite server. To make sure Appwrite CLI is ready, you can use the command `appwrite client --debug` and it should respond with green text `✓ Success`. 33 | 34 | Make sure you are in the same folder as your `appwrite.json` file and run `appwrite deploy function` to deploy your function. You will be prompted to select which functions you want to deploy. 35 | 36 | ### Manual using tar.gz 37 | 38 | Manual deployment has no requirements and uses Appwrite Console to deploy the tag. First, enter the folder of your function. Then, create a tarball of the whole folder and gzip it. After creating `.tar.gz` file, visit Appwrite Console, click on the `Deploy Tag` button and switch to the `Manual` tab. There, set the `entrypoint` to `src/index.js`, and upload the file we just generated. 39 | -------------------------------------------------------------------------------- /node/wipe_appwrite_bucket/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "wipe_appwrite_bucket", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "src/index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "node-appwrite": "^8.0.0" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /node/wipe_appwrite_collection/index.js: -------------------------------------------------------------------------------- 1 | const sdk = require('node-appwrite'); 2 | 3 | module.exports = async function (req, res) { 4 | const client = new sdk.Client(); 5 | const databases = new sdk.Databases(client); 6 | 7 | if(!req.variables["APPWRITE_FUNCTION_ENDPOINT"] || !req.variables["APPWRITE_FUNCTION_API_KEY"] || !req.variables["APPWRITE_FUNCTION_PROJECT_ID"]) { 8 | res.json({success: false, message: "Variables missing."}); 9 | return; 10 | } 11 | 12 | client 13 | .setEndpoint(req.variables["APPWRITE_FUNCTION_ENDPOINT"]) 14 | .setProject(req.variables["APPWRITE_FUNCTION_PROJECT_ID"]) 15 | .setKey(req.variables["APPWRITE_FUNCTION_API_KEY"]); 16 | 17 | try{ 18 | const payload = JSON.parse(req.payload ?? '{}'); 19 | if(!payload.databaseId || !payload.collectionId) { 20 | res.json({success: false, message: "Invalid payload."}); 21 | return; 22 | } 23 | 24 | let sum = 0; 25 | let done = false; 26 | 27 | while(!done) { 28 | const response = await databases.listDocuments(payload.databaseId, payload.collectionId); 29 | const documents = response.documents; 30 | 31 | for(const document of documents) { 32 | await databases.deleteDocument(payload.databaseId, payload.collectionId, document.$id); 33 | sum++; 34 | } 35 | 36 | if(documents.length === 0) { 37 | done = true; 38 | } 39 | } 40 | 41 | res.send({success: true, sum: sum}); 42 | } catch(e) { 43 | res.json({success: false, message: "Unexpected error: " + e}); 44 | } 45 | 46 | }; 47 | -------------------------------------------------------------------------------- /node/wipe_appwrite_collection/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "wipe_appwrite_collection", 3 | "version": "1.0.0", 4 | "description": "Delete all documents from a collection", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "Kritika Sharma", 10 | "license": "ISC", 11 | "dependencies": { 12 | "node-appwrite": "^8.1.0" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /php/convert-phone-number-to-country-name/composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "opr/convert_phone_number_to_country_name", 3 | "description": "", 4 | "type": "library", 5 | "license": "ISC", 6 | "authors": [], 7 | "require": { 8 | "php": ">=8.0.0", 9 | "appwrite/appwrite": "4.0.*" 10 | } 11 | } -------------------------------------------------------------------------------- /php/deepgram-audio-summary/README.md: -------------------------------------------------------------------------------- 1 | 2 | # ⚡ deepgramAudioSummary() 3 | 4 | A Php Cloud Function for audio summary using [Deepgram](https://deepgram.com/) 5 | 6 | _Example function payload:_ 7 | 8 | ```json 9 | { 10 | "fileUrl":"https://rawcdn.githack.com/deepgram-devs/summary-audio/62fc7769d6e2bf38e420ee5224060922af4546f7/deepgram.mp3" 11 | } 12 | ``` 13 | 14 | _Successful function response::_ 15 | 16 | ```json 17 | { "deepgramData": {}, "success": true } 18 | ``` 19 | 20 | _Error function response:_ 21 | 22 | ```json 23 | { "message": "error message", "success": false } 24 | ``` 25 | 26 | ## 📝 Environment Variables 27 | 28 | List of environment variables used by this cloud function: 29 | 30 | **DEEPGRAM_API_KEY** - Your Deepgram API key. 31 | 32 | ## 🚀 Deployment 33 | 34 | 1. Clone this repository, and enter this function folder: 35 | 36 | ``` 37 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 38 | $ cd php/deepgram-audio-summary 39 | ``` 40 | 41 | 2. Enter this function folder and build the code: 42 | 43 | ``` 44 | docker run --rm --interactive --tty --volume $PWD:/usr/code openruntimes/php:v2-8.1 sh /usr/local/src/build.sh 45 | ``` 46 | 47 | As a result, a `code.tar.gz` file will be generated. 48 | 49 | 3. Start the Open Runtime: 50 | 51 | ``` 52 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_KEY=secret-key -e INTERNAL_RUNTIME_ENTRYPOINT=index.php --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/php:v2-8.1 sh /usr/local/src/start.sh 53 | ``` 54 | 55 | > Make sure to replace `YOUR_API_KEY` without your key. 56 | 57 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit PHP runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/php-8.1). 58 | 59 | ## 📝 Notes 60 | 61 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 62 | - This example is compatible with PHP 2.8.1. Other versions may work but are not guaranteed to work as they haven't been tested. 63 | -------------------------------------------------------------------------------- /php/deepgram-audio-summary/index.php: -------------------------------------------------------------------------------- 1 | json([ 10 | 'success' => false, 11 | 'message' => 'Cannot read payload.' 12 | ]); 13 | return; 14 | } 15 | 16 | $secretKey = $req['variables']['DEEPGRAM_API_KEY']; 17 | $request = "https://api.deepgram.com/v1/listen?summarize=true&punctuate=true"; 18 | $ch = curl_init($request); 19 | 20 | $payload = json_encode( array( "url" => $fileUrl ) ); 21 | curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); 22 | curl_setopt($ch, CURLOPT_HTTPHEADER, array( 23 | "Content-Type: application/json", 24 | "Authorization: Token " . $secretKey 25 | )); 26 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 27 | 28 | $response = curl_exec($ch); 29 | 30 | if (curl_errno($ch)) { 31 | $res->json([ 32 | 'success' => false, 33 | 'message' => 'Unexpected request error.' 34 | ]); 35 | return; 36 | } else { 37 | $resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE); 38 | if ($resultStatus != 200) { 39 | $res->json([ 40 | 'success' => false, 41 | 'message' => 'HTTP ' . $resultStatus . ' error.' 42 | ]); 43 | return; 44 | } 45 | } 46 | 47 | curl_close($ch); 48 | 49 | $res->json([ 50 | 'success' => true, 51 | 'deepgramData' => \json_decode($response) 52 | ]); 53 | } 54 | 55 | ?> 56 | -------------------------------------------------------------------------------- /php/deepgram_language_detection/README.md: -------------------------------------------------------------------------------- 1 | # deepgramLanguageDetection() 2 | 3 | A PHP Cloud Function for detecting language from audio using [Deepgram](https://deepgram.com/) 4 | 5 | _Example function payload:_ 6 | 7 | ```json 8 | { 9 | "fileUrl": "https://static.deepgram.com/examples/interview_speech-analytics.wav" 10 | } 11 | ``` 12 | 13 | _Example successful function response:_ 14 | 15 | ```json 16 | { 17 | "success": true, 18 | "deepgramData": {} 19 | } 20 | ``` 21 | 22 | _Example error function response:_ 23 | 24 | ```json 25 | { 26 | "success": false, 27 | "message": "Please provide a valid file URL." 28 | } 29 | ``` 30 | 31 | ## 📝 Variables 32 | 33 | List of variables used by this cloud function: 34 | 35 | **DEEPGRAM_API_KEY** - Your Deepgram API key. 36 | 37 | ## 🚀 Deployment 38 | 39 | 1. Clone this repository, and enter this function folder: 40 | 41 | ``` 42 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 43 | $ cd php/deepgram_language_detection 44 | ``` 45 | 46 | 2. Enter this function folder and build the code: 47 | ``` 48 | docker run --rm --interactive --tty --volume $PWD:/usr/code openruntimes/php:v2-8.1 sh /usr/local/src/build.sh 49 | ``` 50 | As a result, a `code.tar.gz` file will be generated. 51 | 52 | 3. Start the Open Runtime: 53 | ``` 54 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_KEY=secret-key -e INTERNAL_RUNTIME_ENTRYPOINT=index.php --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/php:v2-8.1 sh /usr/local/src/start.sh 55 | ``` 56 | 57 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit PHP runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/php-8.1). 58 | 59 | ## 📝 Notes 60 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 61 | - This example is compatible with PHP 8.1. Other versions may work but are not guaranteed to work as they haven't been tested. -------------------------------------------------------------------------------- /php/deepgram_language_detection/composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "opr/deepgram_language_detection", 3 | "description": "", 4 | "type": "library", 5 | "license": "ISC", 6 | "authors": [], 7 | "require": { 8 | "php": ">=8.0.0" 9 | } 10 | } -------------------------------------------------------------------------------- /php/deepgram_language_detection/index.php: -------------------------------------------------------------------------------- 1 | json([ 10 | 'success' => false, 11 | 'message' => 'Please provide all required environment variables.', 12 | ]); 13 | } 14 | 15 | // Make sure the payload is populated 16 | try { 17 | $payload = \json_decode($req['payload'], true); 18 | $file_url = \trim($payload['fileUrl']); 19 | } catch(\Exception $err) { 20 | $res->json([ 21 | 'success' => false, 22 | 'message' => 'Payload is invalid with error ' . $err->getMessage(), 23 | ]); 24 | } 25 | 26 | if(empty($file_url)) { 27 | $res->json([ 28 | 'success' => false, 29 | 'message' => 'Invalid url. ' . $file_url, 30 | ]); 31 | } 32 | 33 | $ch = \curl_init("https://api.deepgram.com/v1/listen?detect_language=true&punctuate=true"); 34 | // Authorization: Token 35 | \curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Token " . $req['variables']['DEEPGRAM_API_KEY'], "Content-Type: application/json")); 36 | \curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 37 | \curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array("url" => $file_url))); 38 | 39 | $response = \curl_exec($ch); 40 | $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 41 | 42 | if ($response !== false && $httpcode === 200) { 43 | $return = [ 44 | 'success' => true, 45 | 'deepgramData' => \json_decode($response, true), 46 | ]; 47 | } else { 48 | $return = [ 49 | 'success' => false, 50 | 'message' => 'HTTP code: ' . $httpcode . ' Body: ' . $response, 51 | ]; 52 | } 53 | \curl_close($ch); 54 | 55 | $res->json($return); 56 | }; -------------------------------------------------------------------------------- /php/deepgram_transcribe_audio/composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "opr/deepgram_transcribe_audio", 3 | "description": "", 4 | "type": "library", 5 | "license": "ISC", 6 | "authors": [], 7 | "require": { 8 | "php": ">=8.0.0", 9 | "guzzlehttp/guzzle": "^7.0" 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /php/generate_giphy_gif/README.md: -------------------------------------------------------------------------------- 1 | # 🖼️ Get Giphy GIF 2 | 3 | A PHP Cloud Function for generating Giphy GIF from the [Giphy API](https://developers.giphy.com/docs/api#quick-start-guide). 4 | 5 | _Example input:_ 6 | 7 | ```json 8 | { 9 | "search": "good morning" 10 | } 11 | ``` 12 | 13 | _Example output:_ 14 | 15 | 16 | ```json 17 | { 18 | "search": "good morning", 19 | "gif": "https://giphy.com/gifs/text-gif-sticker-brittdoesdesign-MS9Yq6Y718CSiDTxR5" 20 | } 21 | ``` 22 | 23 | ## 📝 Environment Variables 24 | 25 | List of environment variables used by this cloud function: 26 | 27 | **GIPHY_API_KEY** - Your Giphy API key. 28 | 29 | ## 🚀 Deployment 30 | 31 | 1. Clone this repository, and enter this function folder: 32 | 33 | ``` 34 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 35 | $ cd php/generate_giphy_gif 36 | ``` 37 | 38 | 2. Enter this function folder and build the code: 39 | ``` 40 | docker run --rm --interactive --tty --volume $PWD:/usr/code openruntimes/php:v2-8.1 sh /usr/local/src/build.sh 41 | ``` 42 | As a result, a `code.tar.gz` file will be generated. 43 | 44 | 3. Start the Open Runtime: 45 | ``` 46 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_KEY=secret-key -e INTERNAL_RUNTIME_ENTRYPOINT=index.php --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/php:v2-8.1 sh /usr/local/src/start.sh 47 | ``` 48 | 49 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit PHP runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/php-8.1). 50 | 51 | ## 📝 Notes 52 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 53 | - This example is compatible with PHP 8.1. Other versions may work but are not guaranteed to work as they haven't been tested. -------------------------------------------------------------------------------- /php/generate_giphy_gif/composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "opr/generate_giphy_gif", 3 | "description": "", 4 | "type": "library", 5 | "license": "ISC", 6 | "authors": [], 7 | "require": { 8 | "php": ">=8.0.0" 9 | } 10 | } -------------------------------------------------------------------------------- /php/generate_giphy_gif/index.php: -------------------------------------------------------------------------------- 1 | json([ 34 | 'search' => $search, 35 | 'gif' => $response["data"][0]['url'], 36 | ]); 37 | }; 38 | -------------------------------------------------------------------------------- /php/object_detection/README.md: -------------------------------------------------------------------------------- 1 | # 📷 Object Detection using Cloudmersive Vision API 2 | 3 | A PHP Cloud Function for object detection from an image URL. 4 | 5 | _Example input:_ 6 | 7 | ```json 8 | { 9 | "url": "https://picsum.photos/seed/open___runtimes/1000/1000" 10 | } 11 | ``` 12 | 13 | _Example output:_ 14 | 15 | 16 | ```json 17 | { 18 | "ObjectClassName": "cake", 19 | "Score": 0.7977721691131592, 20 | "X": 21, 21 | "Y": 5, 22 | "Width": 494, 23 | "Height": 333 24 | } 25 | ``` 26 | 27 | ## 📝 Environment Variables 28 | 29 | List of environment variables used by this cloud function: 30 | 31 | **CLOUDMERSIVE_API_KEY** - Your Cloudmersive API key. 32 | 33 | ## 🚀 Deployment 34 | 35 | 1. Clone this repository, and enter this function folder: 36 | 37 | ``` 38 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 39 | $ cd php/object_detection 40 | ``` 41 | 42 | 2. Enter this function folder and build the code: 43 | 44 | ``` 45 | docker run --rm --interactive --tty --volume $PWD:/usr/code openruntimes/php:v2-8.1 sh /usr/local/src/build.sh 46 | ``` 47 | As a result, a `code.tar.gz` file will be generated. 48 | 49 | 3. Start the Open Runtime: 50 | 51 | ``` 52 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_KEY=secret-key -e INTERNAL_RUNTIME_ENTRYPOINT=index.php --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/php:v2-8.1 sh /usr/local/src/start.sh 53 | ``` 54 | 55 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit PHP runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/php-8.1). 56 | 57 | ## 📝 Notes 58 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 59 | - This example is compatible with PHP 8.1. Other versions may work but are not guaranteed to work as they haven't been tested. 60 | -------------------------------------------------------------------------------- /php/object_detection/composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "opr/object_detection", 3 | "description": "", 4 | "type": "library", 5 | "license": "ISC", 6 | "authors": [], 7 | "require": { 8 | "php": ">=8.0.0" 9 | } 10 | } -------------------------------------------------------------------------------- /php/object_detection/index.php: -------------------------------------------------------------------------------- 1 | $image, 42 | ]); 43 | \curl_setopt($ch, CURLOPT_HTTPHEADER, [ 44 | 'Apikey: ' . $req['variables']['CLOUDMERSIVE_API_KEY'], 45 | ]); 46 | 47 | $response = \json_decode(\curl_exec($ch), true); 48 | \curl_close($ch); 49 | 50 | // Return phone number prefix 51 | $res->json($response['Objects']); 52 | }; 53 | -------------------------------------------------------------------------------- /php/send-http-request/README.md: -------------------------------------------------------------------------------- 1 | # Function to send request and get response 2 | 3 | A PHP Cloud Function for getting the response from request. 4 | 5 | _Example input:_ 6 | 7 | ```json 8 | { 9 | "url": "https://demo.appwrite.io/v1/locale/countries/eu", 10 | "method": "GET", 11 | "headers": { 12 | "x-client-version": "1.0.0" 13 | }, 14 | "body": "" 15 | } 16 | ``` 17 | 18 | _Example output:_ 19 | 20 | 21 | ```json 22 | { 23 | "success": true, 24 | "response": { 25 | "headers": "{headers_content}", 26 | "code": 200, 27 | "body": "{body_content}" 28 | } 29 | } 30 | ``` 31 | 32 | ## 🚀 Deployment 33 | 34 | 1. Clone this repository, and enter this function folder: 35 | 36 | ``` 37 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 38 | $ cd php/send-http-request 39 | ``` 40 | 41 | 2. Enter this function folder and build the code: 42 | ``` 43 | docker run --rm --interactive --tty --volume $PWD:/usr/code openruntimes/php:v2-8.1 sh /usr/local/src/build.sh 44 | ``` 45 | 46 | 3. Start the Open Runtime: 47 | ``` 48 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_KEY=secret-key -e INTERNAL_RUNTIME_ENTRYPOINT=index.php --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/php:v2-8.1 sh /usr/local/src/start.sh 49 | ``` 50 | 51 | Your function is now listening on port `3000`, and you can execute it by sending `GET` request with appropriate authorization headers. To learn more about runtime, you can visit PHP runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/php-8.1). 52 | 53 | ## 📝 Notes 54 | - This example is compatible with PHP 8.1. Other versions may work but are not guaranteed to work as they haven't been tested. -------------------------------------------------------------------------------- /php/send-http-request/composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "opr/send-http-request", 3 | "description": "", 4 | "type": "library", 5 | "license": "ISC", 6 | "authors": [], 7 | "require": { 8 | "php": ">=8.0.0", 9 | "guzzlehttp/guzzle": "^7.0" 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /php/send-http-request/index.php: -------------------------------------------------------------------------------- 1 | json([ 22 | 'success' => false, 23 | 'message' => 'Payload is invalid: ' . $err->getMessage() 24 | ]); 25 | return; 26 | } 27 | 28 | $client = new Client(); 29 | $response = $client->request($method, $url, [ 30 | 'body' => $body, 31 | 'headers' => $headers 32 | ]); 33 | 34 | if ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300) { 35 | $res->json([ 36 | 'success' => true, 37 | 'response' => [ 38 | 'headers' => $response->getHeaders(), 39 | 'code' => $response->getStatusCode(), 40 | 'body' => $response->getBody()->getContents() 41 | ] 42 | ]); 43 | return; 44 | } 45 | 46 | $res->json([ 47 | 'success' => false, 48 | 'message' => $response->getBody()->getContents() 49 | ]); 50 | } 51 | ?> -------------------------------------------------------------------------------- /php/send_message/composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "opr/send-message", 3 | "description": "An example PHP Cloud Function sending a message using a specific channel to a receiver", 4 | "type": "project", 5 | "require": { 6 | "guzzlehttp/guzzle": "^7.5", 7 | "guzzlehttp/oauth-subscriber": "^0.6.0" 8 | }, 9 | "license": "ISC", 10 | "minimum-stability": "stable" 11 | } 12 | -------------------------------------------------------------------------------- /php/send_message/index.php: -------------------------------------------------------------------------------- 1 | json([ 16 | 'status' => false, 17 | 'message' => $e->getMessage(), 18 | ]); 19 | }; 20 | 21 | if (!array_key_exists('type', $payload)) { 22 | return $res->json([ 23 | 'status' => false, 24 | 'message' => "Invalid payload, object 'type' is required." 25 | ]); 26 | } 27 | 28 | $notificator = match (strtolower($payload['type'])) { 29 | 'sms' => new SMSChannel($req['variables']), 30 | 'email' => new EmailChannel($req['variables']), 31 | 'twitter' => new TwitterChannel($req['variables']), 32 | 'discord' => new DiscordChannel($req['variables']), 33 | default => new NullChannel, 34 | }; 35 | 36 | $res->json( 37 | json: $notificator->send( 38 | payload: $payload, 39 | ), 40 | ); 41 | }; 42 | -------------------------------------------------------------------------------- /php/send_message/src/Contracts/Channel.php: -------------------------------------------------------------------------------- 1 | client = new Client( 17 | config: [ 18 | 'headers' => [ 19 | 'content-type' => 'application/json', 20 | ] 21 | ] 22 | ); 23 | } 24 | 25 | public function hasEnvironmentVariables(): string 26 | { 27 | return array_key_exists('DISCORD_WEBHOOK_URL', $this->environment); 28 | } 29 | 30 | public function getEndpoint(): string 31 | { 32 | return $this->environment['DISCORD_WEBHOOK_URL']; 33 | } 34 | 35 | public function send(array $payload): array 36 | { 37 | if (! $this->hasEnvironmentVariables()) { 38 | return [ 39 | 'success' => false, 40 | 'message' => 'Environment variables are not set.', 41 | ]; 42 | } 43 | 44 | try { 45 | $response = $this->client->send( 46 | request: new Request( 47 | method: 'POST', 48 | uri: $this->getEndpoint(), 49 | ), 50 | options: [ 51 | RequestOptions::JSON => [ 52 | 'content' => $payload['message'], 53 | ], 54 | ], 55 | ); 56 | } catch (\Exception $e) { 57 | return [ 58 | 'success' => false, 59 | 'message' => $e->getMessage(), 60 | ]; 61 | } 62 | 63 | return [ 64 | 'success' => (200 <= $response->getStatusCode() && $response->getStatusCode() < 300), 65 | ]; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /php/send_message/src/NullChannel.php: -------------------------------------------------------------------------------- 1 | false, 11 | 'message' => 'No channel type found.', 12 | ]; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /php/send_message/src/Traits/HasReceiver.php: -------------------------------------------------------------------------------- 1 | validate($receiver); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /php/send_message/src/Validators/EmailValidator.php: -------------------------------------------------------------------------------- 1 | client->send( 22 | request: new Request( 23 | method: 'GET', 24 | uri: sprintf('https://lookups.twilio.com/v1/PhoneNumbers/%s', rawurlencode($receiver)), 25 | ), 26 | options: [ 27 | RequestOptions::AUTH => [ 28 | $this->SID, $this->token, 29 | ], 30 | RequestOptions::ALLOW_REDIRECTS => false, 31 | ], 32 | ); 33 | } catch (\Exception) { 34 | return false; 35 | } 36 | 37 | return $response->getStatusCode() === 200; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /php/wipe_appwrite_bucket/composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "user/function", 3 | "description": "", 4 | "type": "library", 5 | "license": "ISC", 6 | "authors": [], 7 | "require": { 8 | "php": ">=8.0.0", 9 | "appwrite/appwrite": "7.0.*" 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /python/convert-phone-number-to-country-name/requirements.txt: -------------------------------------------------------------------------------- 1 | appwrite==0.7.0 -------------------------------------------------------------------------------- /python/deepgram-audio-summary/main.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | 4 | 5 | def errorMessage(res, message): 6 | return res.json({ 7 | "success": False, 8 | "message": message, 9 | }) 10 | 11 | 12 | def main(req,res): 13 | try: 14 | #fileUrl and DEEPGRAM_API_KEY is required 15 | file_url = req.payload['fileUrl'] 16 | api_key = req.variables.get('DEEPGRAM_API_KEY') 17 | 18 | except Exception: 19 | return errorMessage(res, 'Payload must contain fileUrl and DEEPGRAM_API_KEY.') 20 | 21 | # Setting up headers and body data for the requst 22 | headers = { 23 | 'content-type': "application/json", 24 | 'Authorization': f"Token {api_key}" 25 | } 26 | data = {"url": file_url } 27 | try: 28 | r = requests.post("https://api.deepgram.com/v1/listen?summarize=true&punctuate=true", headers=headers, json=data) 29 | except Exception as ex: 30 | return errorMessage(res, str(ex)) 31 | 32 | status = r.status_code 33 | if status == requests.codes.ok: 34 | return res.json({ 35 | "success": True, 36 | "deepgramData": r.json()["results"] 37 | }) 38 | else: 39 | return errorMessage(res, f"{status} status error.") 40 | -------------------------------------------------------------------------------- /python/deepgram-audio-summary/requirements.txt: -------------------------------------------------------------------------------- 1 | requests==2.27.1 -------------------------------------------------------------------------------- /python/deepgram-language-detection/main.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | 4 | 5 | def errorMessage(res, message): 6 | return res.json({ 7 | "success": False, 8 | "message": message, 9 | }) 10 | 11 | 12 | def main(req,res): 13 | try: 14 | #fileUrl and DEEPGRAM_API_KEY is required 15 | file_url = req.payload['fileUrl'] 16 | api_key = req.variables.get('DEEPGRAM_API_KEY') 17 | 18 | except Exception: 19 | return errorMessage(res, 'Request must contain the File URL in the payload and the Deepgram API Key as a variable.') 20 | 21 | # Setting up headers and body data for the requst 22 | headers = { 23 | 'content-type': "application/json", 24 | 'Authorization': f"Token {api_key}" 25 | } 26 | data = {"url": file_url } 27 | try: 28 | r = requests.post("https://api.deepgram.com/v1/listen?detect_language=true&punctuate=true", headers=headers, json=data) 29 | except Exception as ex: 30 | return errorMessage(res, str(ex)) 31 | 32 | status = r.status_code 33 | if status == requests.codes.ok: 34 | return res.json({ 35 | "success": True, 36 | "deepgramData": r.json()["results"] 37 | }) 38 | else: 39 | return errorMessage(res, f"{status} status error.") -------------------------------------------------------------------------------- /python/deepgram-language-detection/requirements.txt: -------------------------------------------------------------------------------- 1 | requests==2.27.1 2 | -------------------------------------------------------------------------------- /python/deepgram-topic-detection/README.md: -------------------------------------------------------------------------------- 1 | # 🧹Deepgram Topic Detection 2 | 3 | A Cloud Function for topic detection using [Deepgram](https://deepgram.com/) 4 | 5 | _Example input:_ 6 | 7 | ```json 8 | { 9 | "fileUrl": "https://static.deepgram.com/examples/interview_speech-analytics.wav" 10 | } 11 | ``` 12 | 13 | _Example output:_ 14 | 15 | ```json 16 | { 17 | "deepgramData": {}, 18 | "success": true 19 | } 20 | ``` 21 | 22 | _Example error output:_ 23 | 24 | ```json 25 | { 26 | "success": false, 27 | "message": "Error" 28 | } 29 | ``` 30 | 31 | ## 📝 Environment Variables 32 | 33 | **DEEPGRAM_API_KEY** - Your Deepgram secret API key. 34 | Details are under link: [Deepgram_getting_started](https://developers.deepgram.com/documentation/getting-started/) 35 | 36 | ## 🚀 Deployment 37 | 38 | 1. Clone this repository, and enter this function folder: 39 | 40 | ```bash 41 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 42 | $ cd python/deepgram-topic-detection 43 | ``` 44 | 45 | 2. Build the code: 46 | 47 | ```bash 48 | docker run -e INTERNAL_RUNTIME_ENTRYPOINT=main.py --rm --interactive --tty --volume $PWD:/usr/code openruntimes/python:v2-3.10 sh /usr/local/src/build.sh 49 | ``` 50 | 51 | 3. Spin-up open-runtime: 52 | 53 | ```bash 54 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_KEY=secret-key --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/python:v2-3.10 sh /usr/local/src/start.sh 55 | ``` 56 | 57 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit Python runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/python-3.10). 58 | 59 | ## 📝 Notes 60 | 61 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). -------------------------------------------------------------------------------- /python/deepgram-topic-detection/main.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import validators 3 | 4 | 5 | def main(req, res): 6 | # validate the request url/payload is not empty 7 | file_url = None 8 | try: 9 | file_url = req.payload['fileUrl'] 10 | api_key = req.variables.get('DEEPGRAM_API_KEY') 11 | except Exception: 12 | return res.json({'success': "false", 'message': "Invalid/Empty Payload"}) 13 | 14 | if not file_url: 15 | return res.json({'success': "false", 'message': "Empty URL"}) 16 | 17 | # validate if the file url is in correct format 18 | if not validators.url(file_url): 19 | return res.json({'success': "false", 'message': "Invalid URL please provide URL in correct format"}) 20 | 21 | # Make sure we have environment variables required to execute 22 | if not api_key: 23 | return res.json({'success': "false", 'message': "You need to pass an API key for the provider"}) 24 | 25 | # Fetch the DEEPGRAM Data 26 | base_url = "https://api.deepgram.com/v1/listen?detect_topics=true&punctuate=true" 27 | response = requests.post(base_url, json={"url": file_url}, 28 | headers={"Content-Type": "application/json", "Authorization": "Token " + api_key}) 29 | 30 | # Make sure we get the deepgram data 31 | if response.status_code != 200: 32 | return res.json({"success": "false", 'message': "Can't fetch the data/API key is not valid"}) 33 | 34 | print(response.json()) 35 | 36 | # Return DEEPGRAM DATA 37 | return res.json({"success": "true", "deepgramData": response.json()["results"]}) 38 | -------------------------------------------------------------------------------- /python/deepgram-topic-detection/requirements.txt: -------------------------------------------------------------------------------- 1 | requests==2.28.1 2 | validators==0.20.0 -------------------------------------------------------------------------------- /python/deepgram-transcribe-audio/requirements.txt: -------------------------------------------------------------------------------- 1 | requests==2.27.1 2 | -------------------------------------------------------------------------------- /python/deepgram-transcribe-video/main.py: -------------------------------------------------------------------------------- 1 | from deepgram import Deepgram 2 | import asyncio 3 | import json 4 | 5 | 6 | async def transribeVideo(api_key, payload): 7 | 8 | dg_client = Deepgram(api_key) 9 | source = {'url': payload['fileUrl']} 10 | 11 | try: 12 | response = await dg_client.transcription.prerecorded(source, {'punctuate': True, "model": 'video'}) 13 | except Exception as e: 14 | return {'success': False, 'message': str(e)} 15 | return {'success': True, 'deepgramData': response} 16 | 17 | 18 | def main(req, res): 19 | try: 20 | payload = json.loads(req.payload) 21 | api_key = req.variables['DEEPGRAM_API_KEY'] 22 | rs = asyncio.run(transribeVideo(api_key, payload)) 23 | return res.json(rs) 24 | except Exception as e: 25 | return res.json({'success': False, 'message': str(e)}) 26 | -------------------------------------------------------------------------------- /python/deepgram-transcribe-video/requirements.txt: -------------------------------------------------------------------------------- 1 | aiohttp==3.8.3 2 | aiosignal==1.2.0 3 | async-timeout==4.0.2 4 | attrs==22.1.0 5 | charset-normalizer==2.1.1 6 | deepgram-sdk==1.0.0 7 | frozenlist==1.3.1 8 | idna==3.4 9 | multidict==6.0.2 10 | websockets==10.3 11 | yarl==1.8.1 12 | -------------------------------------------------------------------------------- /python/generate-giphy-gif/README.md: -------------------------------------------------------------------------------- 1 | # 🖼️ Get Giphy GIF 2 | 3 | A Python Cloud Function for generating Giphy GIF from the [Giphy API](https://developers.giphy.com/docs/api#quick-start-guide). 4 | 5 | _Example input:_ 6 | 7 | ```json 8 | { 9 | "search": "good morning" 10 | } 11 | ``` 12 | 13 | _Example output:_ 14 | 15 | 16 | ```json 17 | { 18 | "search": "good morning", 19 | "gif": "https://giphy.com/gifs/text-gif-sticker-brittdoesdesign-MS9Yq6Y718CSiDTxR5" 20 | } 21 | ``` 22 | 23 | ## 📝 Environment Variables 24 | 25 | List of environment variables used by this cloud function: 26 | 27 | **GIPHY_API_KEY** - Your Giphy API key. 28 | 29 | ## 🚀 Deployment 30 | 31 | 1. Clone this repository, and enter this function folder: 32 | 33 | ``` 34 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 35 | $ cd python/generate-giphy-gif 36 | ``` 37 | 38 | 2. Enter this function folder and build the code: 39 | ``` 40 | docker run --rm --interactive --tty --volume $PWD:/usr/code openruntimes/python:v2-3.10 sh /usr/local/src/build.sh 41 | ``` 42 | As a result, a `code.tar.gz` file will be generated. 43 | 44 | 3. Start the Open Runtime: 45 | ``` 46 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_KEY=secret-key -e INTERNAL_RUNTIME_ENTRYPOINT=main.py --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/python:v2-3.10 sh /usr/local/src/start.sh 47 | ``` 48 | 49 | > Make sure to replace `YOUR_API_KEY` without your key. 50 | 51 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit Python runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/python-3.10). 52 | 53 | ## 📝 Notes 54 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 55 | - This example is compatible with Python 3.10. Other versions may work but are not guaranteed to work as they haven't been tested. -------------------------------------------------------------------------------- /python/generate-giphy-gif/main.py: -------------------------------------------------------------------------------- 1 | import json 2 | import requests 3 | 4 | def main(req, res): 5 | # Input validation 6 | search = None 7 | try: 8 | payload = json.loads(req.payload) 9 | search = payload['search'] 10 | except Exception as err: 11 | print(err) 12 | raise Exception('Payload is invalid.') 13 | 14 | if not search: 15 | raise Exception('Invalid search.') 16 | 17 | # Make sure we have envirnment variables required to execute 18 | if not req.variables.get('GIPHY_API_KEY', None): 19 | raise Exception('Please provide all required environment variables.') 20 | 21 | api_key = req.variables.get('GIPHY_API_KEY', None) 22 | 23 | # Fetch the Giphy URL 24 | response = requests.get(f"https://api.giphy.com/v1/gifs/search?api_key={api_key}&q={search}&limit=1") 25 | response.raise_for_status() 26 | url = response.json()["data"][0]['url'] 27 | 28 | # Return Giphy URL 29 | return res.json({'search': search, 'gif': url}) -------------------------------------------------------------------------------- /python/generate-giphy-gif/requirements.txt: -------------------------------------------------------------------------------- 1 | requests==2.27.1 2 | -------------------------------------------------------------------------------- /python/generate-map/README.md: -------------------------------------------------------------------------------- 1 | # 🗺️ Generate Map Image 2 | A Python Cloud Function that generate static map image from longitude and latitude. 3 | _Example input:_ 4 | ```json 5 | { 6 | "lng": 12.561767, 7 | "lat": 41.857177 8 | } 9 | ``` 10 | _Example output:_ 11 | 12 | ```json 13 | { 14 | "success":true, 15 | "image":"iVBORw0KGgoAAAANSUhEUgAAAaQAAALiCAY...QoH9hbkTPQAAAABJRU5ErkJggg==" 16 | } 17 | ``` 18 | ## 📝 Environment Variables 19 | 20 | List of environment variables used by this cloud function: 21 | 22 | **MAPBOX_ACCESS_TOKEN** - Your Mapbox API key. 23 | 24 | ## 🚀 Deployment 25 | 26 | 1. Clone this repository, and enter this function folder: 27 | ``` 28 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 29 | $ cd python/generate-map 30 | ``` 31 | 32 | 2. Enter this function folder and build the code: 33 | ``` 34 | docker run --rm --interactive --tty --volume $PWD:/usr/code openruntimes/python:v2-3.10 sh /usr/local/src/build.sh 35 | ``` 36 | As a result, a `code.tar.gz` file will be generated. 37 | 38 | 3. Start the Open Runtime: 39 | ``` 40 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_KEY=secret-key -e INTERNAL_RUNTIME_ENTRYPOINT=main.py --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/python:v2-3.10 sh /usr/local/src/start.sh 41 | ``` 42 | 43 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit Python runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/python-3.10). 44 | 45 | 4. Execute function: 46 | 47 | ``` 48 | curl http://localhost:3000/ -d '{"variables":{"MAPBOX_ACCESS_TOKEN":"YOUR_API_KEY"},"payload": "{\"lng\":50,\"lat\":60}"}' -H "X-Internal-Challenge: secret-key" -H "Content-Type: application/json" 49 | 50 | ``` 51 | 52 | ## 📝 Notes 53 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 54 | - This example is compatible with Python 3.10. Other versions may work but are not guaranteed to work as they haven't been tested. 55 | -------------------------------------------------------------------------------- /python/generate-map/main.py: -------------------------------------------------------------------------------- 1 | import json 2 | import requests 3 | import base64 4 | 5 | def error(res,message): 6 | return res.json({"success":False,"message":message}) 7 | 8 | def main(req,res): 9 | try: 10 | payload = json.loads('{}' if not req.payload else req.payload) 11 | lng = payload.get('lng', None) 12 | lat = payload.get('lat', None) 13 | access_token = req.variables["MAPBOX_ACCESS_TOKEN"] 14 | except Exception: 15 | return error(res,"The payload must contain lng and lat or access token is not present") 16 | if lng == None or lat == None: 17 | return error(res,"The payload must contain lng and lat") 18 | elif((type(lng)!=float or type(lat)!=float) and (type(lng)!=int or type(lat)!=int)): 19 | return error(res,"The longitude and latitude must be a number") 20 | elif lng >180 or lng < -180: 21 | return error(res,"The longitude must be between -180 and 180") 22 | elif lat >90 or lat < -90: 23 | return error(res,"The latitude must be between -90 and 90") 24 | 25 | url ="https://api.mapbox.com/styles/v1/mapbox/streets-v11/static/{0},{1},15,0,0/1000x1000?access_token={2}".format(lng,lat,access_token) 26 | response = requests.get(url,timeout=30) 27 | 28 | if response.status_code ==requests.codes.ok: 29 | image = base64.b64encode(response.content) 30 | return res.json({"success":True,"image":image.decode("utf-8")}) 31 | else: 32 | return error(res,"Error " + str(response.status_code) + ": " + str(response.content)) 33 | -------------------------------------------------------------------------------- /python/generate-map/requirements.txt: -------------------------------------------------------------------------------- 1 | requests==2.27.1 -------------------------------------------------------------------------------- /python/generate-short-url/requirements.txt: -------------------------------------------------------------------------------- 1 | requests==2.27.1 2 | -------------------------------------------------------------------------------- /python/object-detection/README.md: -------------------------------------------------------------------------------- 1 | # 📷 Object Detection using Cloudmersive Vision API 2 | 3 | A Python Cloud Function for object detection from an image URL. 4 | 5 | _Example input:_ 6 | 7 | ```json 8 | { 9 | "url": "https://picsum.photos/seed/open___runtimes/1000/1000" 10 | } 11 | ``` 12 | 13 | _Example output:_ 14 | 15 | 16 | ```json 17 | { 18 | "url": "https://picsum.photos/seed/open___runtimes/1000/1000", 19 | "name": "cake", 20 | "confidence": 0.7977721691131592, 21 | "x": 21, 22 | "y": 5, 23 | "width": 494, 24 | "height": 333 25 | } 26 | ``` 27 | 28 | ## 📝 Environment Variables 29 | 30 | List of environment variables used by this cloud function: 31 | 32 | **CLOUDMERSIVE_API_KEY** - Your Cloudmersive API key. 33 | 34 | ## 🚀 Deployment 35 | 36 | 1. Clone this repository, and enter this function folder: 37 | 38 | ``` 39 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 40 | $ cd python/object-detection 41 | ``` 42 | 43 | 2. Enter this function folder and build the code: 44 | ``` 45 | docker run --rm --interactive --tty --volume $PWD:/usr/code openruntimes/python:v2-3.10 sh /usr/local/src/build.sh 46 | ``` 47 | As a result, a `code.tar.gz` file will be generated. 48 | 49 | 3. Start the Open Runtime: 50 | ``` 51 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_KEY=secret-key -e INTERNAL_RUNTIME_ENTRYPOINT=main.py --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/python:v2-3.10 sh /usr/local/src/start.sh 52 | ``` 53 | 54 | > Make sure to replace `YOUR_API_KEY` without your key. 55 | 56 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit Python runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/python-3.10). 57 | 58 | ## 📝 Notes 59 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 60 | - This example is compatible with Python 3.10. Other versions may work but are not guaranteed to work as they haven't been tested. -------------------------------------------------------------------------------- /python/object-detection/main.py: -------------------------------------------------------------------------------- 1 | import json 2 | import requests 3 | 4 | from cloudmersive_image_api_client import Configuration, RecognizeApi, ApiClient 5 | from cloudmersive_image_api_client.rest import ApiException 6 | 7 | def main(req, res): 8 | # Input validation 9 | file_url = None 10 | try: 11 | payload = json.loads(req.payload) 12 | file_url = payload['url'] 13 | except Exception as err: 14 | print(err) 15 | raise Exception('Payload is invalid.') 16 | 17 | if not file_url: 18 | raise Exception('Invalid search.') 19 | 20 | # Make sure we have envirnment variables required to execute 21 | if not req.variables.get('CLOUDMERSIVE_API_KEY', None): 22 | raise Exception('Please provide all required environment variables.') 23 | 24 | api_key = req.variables.get('CLOUDMERSIVE_API_KEY', None) 25 | 26 | # Download the file 27 | response = requests.get(file_url, stream=True) 28 | with open("temp.jpg", 'wb') as newFile: 29 | for chunk in response.iter_content(chunk_size=1024): 30 | if chunk: 31 | newFile.write(chunk) 32 | newFile.flush() 33 | 34 | # Configure the detection client 35 | configuration = Configuration() 36 | configuration.api_key['Apikey'] = api_key 37 | 38 | # Create an instance of the API class 39 | api_client = RecognizeApi(ApiClient(configuration)) 40 | 41 | # Detect objects including types and locations in an image 42 | api_response = api_client.recognize_detect_objects("temp.jpg") 43 | 44 | # Return object detection results 45 | results = list(map(lambda x: { 46 | "name": x.object_class_name, 47 | "confidence": x.score, 48 | "x": x.x, 49 | "y": x.y, 50 | "width": x.width, 51 | "height": x.height 52 | }, api_response.objects)) 53 | 54 | if len(results) < 1: 55 | raise Exception('No objects found in the image.') 56 | 57 | return res.json(results[0]) 58 | -------------------------------------------------------------------------------- /python/object-detection/requirements.txt: -------------------------------------------------------------------------------- 1 | requests==2.27.1 2 | cloudmersive-image-api-client==3.0.1 -------------------------------------------------------------------------------- /python/send-http-request/main.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | 4 | 5 | def errorMessage(res, message): 6 | return res.json({ 7 | "success": False, 8 | "message": message, 9 | }) 10 | 11 | 12 | def main(req,res): 13 | 14 | headers = None 15 | body = None 16 | try: 17 | payload = json.loads(req.payload) 18 | 19 | #url and method are required 20 | url = payload['url'] 21 | method = payload['method'] 22 | 23 | # headers and body are optional 24 | if 'headers' in payload.keys(): 25 | headers = payload['headers'] 26 | if 'body' in payload.keys(): 27 | body = payload['body'] 28 | 29 | except Exception: 30 | return errorMessage(res, 'Payload must contain url and method.') 31 | if url.strip() == "": 32 | return errorMessage(res, 'Payload url cannot be empty.') 33 | if method.strip() == "": 34 | return errorMessage(res, 'Payload method cannot be empty.') 35 | 36 | r = None 37 | try: 38 | r = requests.request(method, url, headers=headers, json=body, timeout=30) 39 | except Exception: 40 | return errorMessage(res, 'URL could not be reached.') 41 | 42 | status = r.status_code 43 | if status == requests.codes.ok: 44 | return res.json({ 45 | "success": True, 46 | "response": 47 | { 48 | "headers": json.dumps(dict(r.headers)), 49 | "code": status, 50 | "body": r.json() 51 | } 52 | }) 53 | else: 54 | return errorMessage(res, f"{status} status error. Nothing to retrieve. Check that URL path is correct.") -------------------------------------------------------------------------------- /python/send-http-request/requirements.txt: -------------------------------------------------------------------------------- 1 | requests==2.27.1 -------------------------------------------------------------------------------- /python/send_message/functions/send_email_mailgun.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import os 3 | 4 | 5 | def send_email_mailgun(variables, email, message, subject): 6 | """Send email using Mailgun""" 7 | 8 | if not email or not message or not subject: 9 | raise Exception("Missing email, message or subject") 10 | 11 | domain = variables.get("MAILGUN_DOMAIN", None) 12 | api_key = variables.get("MAILGUN_API_KEY", None) 13 | 14 | if not domain: 15 | raise Exception("Missing Mailgun domain") 16 | if not api_key: 17 | raise Exception("Missing Mailgun API key") 18 | 19 | try: 20 | response = requests.post( 21 | f"https://api.mailgun.net/v3/{domain}/messages", 22 | auth=("api", api_key), 23 | data={ 24 | "from": "", 25 | "to": email, 26 | "subject": subject, 27 | "text": message, 28 | }, 29 | ) 30 | response.raise_for_status() 31 | 32 | except Exception as e: 33 | print(e) 34 | return {"success": False, "message": str(e)} 35 | 36 | return { 37 | "success": True, 38 | } 39 | -------------------------------------------------------------------------------- /python/send_message/functions/send_message_discord_webhook.py: -------------------------------------------------------------------------------- 1 | import json 2 | import requests 3 | 4 | 5 | def send_message_discord_webhook(variables, message): 6 | """Send message to Discord webhook""" 7 | 8 | if not message: 9 | raise Exception("No message provided") 10 | 11 | webhook = variables.get("DISCORD_WEBHOOK_URL", None) 12 | 13 | if not webhook: 14 | raise Exception("No Discord webhook URL provided") 15 | 16 | try: 17 | response = requests.post( 18 | webhook, 19 | data=json.dumps({"content": message}), 20 | headers={"Content-Type": "application/json"}, 21 | ) 22 | response.raise_for_status() 23 | except Exception as e: 24 | print(e) 25 | return {"success": False, "message": str(e)} 26 | 27 | return {"success": True} 28 | -------------------------------------------------------------------------------- /python/send_message/functions/send_sms_twilio.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | 4 | def send_sms_twilio(variables, phoneNumber, message): 5 | """Send SMS using Twilio""" 6 | 7 | if not phoneNumber: 8 | raise Exception("No phone number provided") 9 | 10 | if not message: 11 | raise Exception("No message provided") 12 | 13 | accountSID = variables.get("TWILIO_ACCOUNT_SID", None) 14 | authToken = variables.get("TWILIO_AUTH_TOKEN", None) 15 | sender = variables.get("TWILIO_SENDER", None) 16 | 17 | if not accountSID: 18 | raise Exception("Missing Twilio account SID") 19 | if not authToken: 20 | raise Exception("Missing Twilio auth token") 21 | if not sender: 22 | raise Exception("Missing Twilio sender") 23 | 24 | try: 25 | response = requests.post( 26 | f"https://api.twilio.com/2010-04-01/Accounts/{accountSID}/Messages.json", 27 | auth=(accountSID, authToken), 28 | data={ 29 | "From": sender, 30 | "To": phoneNumber, 31 | "Body": message, 32 | }, 33 | ) 34 | response.raise_for_status() 35 | except Exception as e: 36 | print(e) 37 | return {"success": False, "message": str(e)} 38 | 39 | return {"success": True} 40 | -------------------------------------------------------------------------------- /python/send_message/functions/send_tweet.py: -------------------------------------------------------------------------------- 1 | import tweepy 2 | 3 | 4 | def send_tweet(variables, message): 5 | """Send tweet to Twitter""" 6 | 7 | if not message: 8 | raise Exception("Missing message") 9 | 10 | consumer_key = variables.get("TWITTER_API_KEY", None) 11 | consumer_secret = variables.get("TWITTER_API_KEY_SECRET", None) 12 | access_token = variables.get("TWITTER_ACCESS_TOKEN", None) 13 | access_token_secret = variables.get("TWITTER_ACCESS_TOKEN_SECRET", None) 14 | 15 | if not consumer_key: 16 | raise Exception("Missing Twitter consumer key") 17 | if not consumer_secret: 18 | raise Exception("Missing Twitter consumer secret") 19 | if not access_token: 20 | raise Exception("Missing Twitter access token") 21 | if not access_token_secret: 22 | raise Exception("Missing Twitter access token secret") 23 | 24 | try: 25 | auth = tweepy.OAuthHandler(consumer_key, consumer_secret) 26 | auth.set_access_token( 27 | access_token, 28 | access_token_secret, 29 | ) 30 | 31 | api = tweepy.API(auth) 32 | 33 | api.update_status(message) 34 | 35 | except Exception as e: 36 | print(e) 37 | return {"success": False, "message": str(e)} 38 | 39 | return { 40 | "success": True, 41 | } 42 | -------------------------------------------------------------------------------- /python/send_message/main.py: -------------------------------------------------------------------------------- 1 | from .functions.send_sms_twilio import send_sms_twilio 2 | from .functions.send_email_mailgun import send_email_mailgun 3 | from .functions.send_tweet import send_tweet 4 | from .functions.send_message_discord_webhook import send_message_discord_webhook 5 | import json 6 | 7 | 8 | def main(req, res): 9 | """Main Function""" 10 | 11 | result = {} 12 | 13 | try: 14 | payload = json.loads(req.payload) 15 | 16 | payload_type = payload["type"] 17 | message = payload["message"] 18 | 19 | if payload_type == "SMS": 20 | reciever = payload["receiver"] 21 | result = send_sms_twilio(req.variables, reciever, message) 22 | elif payload_type == "Email": 23 | reciever = payload["receiver"] 24 | subject = payload["subject"] 25 | result = send_email_mailgun( 26 | req.variables, reciever, message, subject) 27 | elif payload_type == "Twitter": 28 | result = send_tweet(req.variables, message) 29 | elif payload_type == "Discord": 30 | result = send_message_discord_webhook(req.variables, message) 31 | else: 32 | result = {"success": False, "message": "Invalid Type"} 33 | 34 | except Exception as e: 35 | 36 | return res.json({"success": False, "message": str(e)}) 37 | 38 | return res.json(result) 39 | -------------------------------------------------------------------------------- /python/send_message/requirements.txt: -------------------------------------------------------------------------------- 1 | certifi==2022.9.24 2 | charset-normalizer==2.0.12 3 | idna==3.4 4 | oauthlib==3.2.1 5 | python-dotenv==0.21.0 6 | requests==2.27.1 7 | requests-oauthlib==1.3.1 8 | tweepy==4.10.1 9 | urllib3==1.26.12 10 | -------------------------------------------------------------------------------- /ruby/.gitignore: -------------------------------------------------------------------------------- 1 | # Ruby gitignore from: https://github.com/github/gitignore/blob/main/Ruby.gitignore 2 | 3 | *.gem 4 | *.rbc 5 | /.config 6 | /coverage/ 7 | /InstalledFiles 8 | /pkg/ 9 | /spec/reports/ 10 | /spec/examples.txt 11 | /test/tmp/ 12 | /test/version_tmp/ 13 | /tmp/ 14 | 15 | # Used by dotenv library to load environment variables. 16 | # .env 17 | 18 | # Ignore Byebug command history file. 19 | .byebug_history 20 | 21 | ## Specific to RubyMotion: 22 | .dat* 23 | .repl_history 24 | build/ 25 | *.bridgesupport 26 | build-iPhoneOS/ 27 | build-iPhoneSimulator/ 28 | 29 | ## Specific to RubyMotion (use of CocoaPods): 30 | # 31 | # We recommend against adding the Pods directory to your .gitignore. However 32 | # you should judge for yourself, the pros and cons are mentioned at: 33 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 34 | # 35 | # vendor/Pods/ 36 | 37 | ## Documentation cache and generated files: 38 | /.yardoc/ 39 | /_yardoc/ 40 | /doc/ 41 | /rdoc/ 42 | 43 | ## Environment normalization: 44 | /.bundle/ 45 | /vendor/bundle 46 | /lib/bundler/man/ 47 | 48 | # for a library or gem, you might want to ignore these files since the code is 49 | # intended to run in multiple environments; otherwise, check them in: 50 | # Gemfile.lock 51 | # .ruby-version 52 | # .ruby-gemset 53 | 54 | # unless supporting rvm < 1.11.0 or doing something fancy, ignore this: 55 | .rvmrc 56 | 57 | # Used by RuboCop. Remote config files pulled in from inherit_from directive. 58 | # .rubocop-https?--* 59 | -------------------------------------------------------------------------------- /ruby/compress-image/Gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | gem "base64" 3 | gem "tinify" 4 | gem "kraken-io" -------------------------------------------------------------------------------- /ruby/convert-phone-number-to-country-name/Gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | gem "appwrite" -------------------------------------------------------------------------------- /ruby/deepgram-audio-summary/Gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | 3 | gem "uri" 4 | -------------------------------------------------------------------------------- /ruby/deepgram-audio-summary/index.rb: -------------------------------------------------------------------------------- 1 | require "uri" 2 | require "net/http" 3 | require "openssl" 4 | require "json" 5 | 6 | 7 | def main(req, res) 8 | fileUrl = req.payload["fileUrl"] 9 | deepgramApiKey = req.variables["DEEPGRAM_API_KEY"] 10 | 11 | url = URI("https://api.deepgram.com/v1/listen?summarize=true&punctuate=true") 12 | http = Net::HTTP.new(url.host, url.port) 13 | http.use_ssl = true 14 | 15 | request = Net::HTTP::Post.new(url) 16 | request["content-type"] = "application/json" 17 | request["Authorization"] = "Token #{deepgramApiKey}" 18 | request.body = JSON.generate({url: fileUrl}) 19 | 20 | begin 21 | response = http.request(request) 22 | rescue Exception => err 23 | return res.json({ 24 | success: false, 25 | message: err 26 | }) 27 | end 28 | 29 | response_body = response.read_body 30 | if response.code=="200" 31 | parsed_response = JSON.parse(response_body) 32 | res.json({ 33 | success: true, 34 | deepgramData: parsed_response["results"] 35 | }) 36 | elsif valid_json?(response_body) 37 | res.json({ 38 | success: false, 39 | message: JSON.parse(response_body) 40 | }) 41 | else 42 | res.json({ 43 | success: false, 44 | message: response_body 45 | }) 46 | end 47 | end 48 | 49 | def valid_json?(json) 50 | JSON.parse(json) 51 | true 52 | rescue JSON::ParserError, TypeError => e 53 | false 54 | end 55 | -------------------------------------------------------------------------------- /ruby/deepgram-transcribe-video/Gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | 3 | gem "uri" -------------------------------------------------------------------------------- /ruby/deepgram-transcribe-video/index.rb: -------------------------------------------------------------------------------- 1 | require "uri" 2 | require "net/http" 3 | require "openssl" 4 | require "json" 5 | 6 | 7 | def main(req, res) 8 | fileUrl = req.payload["fileUrl"] 9 | deepgramApiKey = req.variables["DEEPGRAM_API_KEY"] 10 | 11 | url = URI("https://api.deepgram.com/v1/listen?model=video") 12 | http = Net::HTTP.new(url.host, url.port) 13 | http.use_ssl = true 14 | 15 | request = Net::HTTP::Post.new(url) 16 | request["content-type"] = "application/json" 17 | request["Authorization"] = "Token #{deepgramApiKey}" 18 | request.body = JSON.generate({url: fileUrl}) 19 | 20 | begin 21 | response = http.request(request) 22 | rescue Exception => err 23 | return res.json({ 24 | success: false, 25 | message: err 26 | }) 27 | end 28 | 29 | response_body = response.read_body 30 | if response.code=="200" 31 | parsed_response = JSON.parse(response_body) 32 | res.json({ 33 | success: true, 34 | deepgramData: parsed_response["results"] 35 | }) 36 | elsif valid_json?(response_body) 37 | res.json({ 38 | success: false, 39 | message: JSON.parse(response_body) 40 | }) 41 | else 42 | res.json({ 43 | success: false, 44 | message: response_body 45 | }) 46 | end 47 | end 48 | 49 | def valid_json?(json) 50 | JSON.parse(json) 51 | true 52 | rescue JSON::ParserError, TypeError => e 53 | false 54 | end -------------------------------------------------------------------------------- /ruby/send-http-request/Gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | gem "httparty" 3 | -------------------------------------------------------------------------------- /ruby/send-http-request/index.rb: -------------------------------------------------------------------------------- 1 | require "httparty" 2 | require "json" 3 | 4 | def main(req, res) 5 | begin 6 | payload = JSON.parse(req.payload) 7 | url = payload["url"] 8 | method = payload["method"] 9 | headers = payload["headers"] 10 | body = payload["body"] 11 | rescue Exception => err 12 | puts err 13 | raise 'Payload is invalid.' 14 | end 15 | 16 | if url.nil? or url.empty? or method.nil? or method.empty? 17 | raise 'Payload is invalid.' 18 | end 19 | 20 | begin 21 | response = HTTParty.send(method.downcase, url, headers: headers, body: body) 22 | 23 | if response.success? 24 | res.json({ 25 | "success": response.success?, 26 | "response": { 27 | "headers": response.headers, 28 | "code": response.code, 29 | "body": response.body 30 | } 31 | }) 32 | else 33 | res.json({ 34 | "success": false, 35 | "message": { 36 | "code": response.code, 37 | "body": response.message 38 | } 39 | }) 40 | end 41 | rescue Exception => err 42 | puts err 43 | raise 'Request could not be made.' 44 | end 45 | end 46 | -------------------------------------------------------------------------------- /ruby/send-sms-with-twilio/Gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | gem "twilio-ruby" -------------------------------------------------------------------------------- /ruby/send-sms-with-twilio/index.rb: -------------------------------------------------------------------------------- 1 | require "twilio-ruby" 2 | require "json" 3 | 4 | def main(req, res) 5 | # Input validation 6 | message = nil 7 | receiver = nil 8 | begin 9 | payload = JSON.parse(req.payload) 10 | message = payload["message"] 11 | receiver = payload["receiver"] 12 | rescue Exception => err 13 | puts err 14 | raise 'Payload is invalid.' 15 | end 16 | 17 | if message.nil? or message.empty? or receiver.nil? or receiver.empty? 18 | raise 'Payload is invalid.' 19 | end 20 | 21 | # Make sure we have envirnment variables required to execute 22 | if !req.variables['TWILIO_ACCOUNT_SID'] or !req.variables['TWILIO_AUTH_TOKEN'] or !req.variables['TWILIO_SENDER'] 23 | raise 'Please provide all required environment variables.' 24 | end 25 | 26 | # Parse the environment variables to get account keys and the sender's mobile number. 27 | account_sid = req.variables["TWILIO_ACCOUNT_SID"] 28 | auth_token = req.variables["TWILIO_AUTH_TOKEN"] 29 | sender = req.variables["TWILIO_SENDER"] 30 | 31 | # Create the Twilio client. 32 | client = Twilio::REST::Client.new(account_sid, auth_token) 33 | 34 | # Send the message. 35 | message = client.messages.create( 36 | body: message, 37 | from: sender, 38 | to: receiver 39 | ) 40 | 41 | # Return a response 42 | res.json({ 43 | messageId: message.sid, 44 | }) 45 | end -------------------------------------------------------------------------------- /ruby/translate-text-with-google/Gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | gem "free_google_translate" -------------------------------------------------------------------------------- /ruby/translate-text-with-google/README.md: -------------------------------------------------------------------------------- 1 | # 🌐 Translate text from one language to another 2 | 3 | A Ruby Cloud Function for translating text from one language to another using [Google Translate](https://translate.google.com/). 4 | 5 | _Example input:_ 6 | 7 | ```json 8 | { 9 | "text": "Hello from Open Runtimes 👋", 10 | "source": "en", 11 | "target": "es" 12 | } 13 | ``` 14 | 15 | _Example output:_ 16 | 17 | ```json 18 | { 19 | "text": "Hello from Open Runtimes 👋", 20 | "translation": "Saludos desde Open Runtime 👋" 21 | } 22 | ``` 23 | 24 | ## 📝 Environment Variables 25 | 26 | No environment variables needed. 27 | 28 | ## 🚀 Deployment 29 | 30 | 1. Clone this repository, and enter this function folder: 31 | 32 | ``` 33 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 34 | $ cd ruby/translate-text-with-google 35 | ``` 36 | 37 | 2. Enter this function folder and build the code: 38 | ``` 39 | docker run --rm --interactive --tty --volume $PWD:/usr/code openruntimes/ruby:v2-3.1 sh /usr/local/src/build.sh 40 | ``` 41 | As a result, a `code.tar.gz` file will be generated. 42 | 43 | 3. Start the Open Runtime: 44 | ``` 45 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_KEY=secret-key -e INTERNAL_RUNTIME_ENTRYPOINT=index.rb --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/ruby:v2-3.1 sh /usr/local/src/start.sh 46 | ``` 47 | 48 | > Make sure to replace `secret-key` with your key. 49 | 50 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit Ruby runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/ruby-3.1). 51 | 52 | ## 📝 Notes 53 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 54 | - This example is compatible with Ruby 3.1. Other versions may work but are not guaranteed to work as they haven't been tested. 55 | -------------------------------------------------------------------------------- /ruby/translate-text-with-google/index.rb: -------------------------------------------------------------------------------- 1 | require "free_google_translate" 2 | require "json" 3 | 4 | def main(req, res) 5 | # Input validation 6 | text = nil 7 | source = nil 8 | target = nil 9 | begin 10 | payload = JSON.parse(req.payload) 11 | text = payload["text"] 12 | source = payload["source"] 13 | target = payload["target"] 14 | rescue Exception => err 15 | puts err 16 | raise 'Payload is invalid.' 17 | end 18 | 19 | if text.nil? or text.empty? or source.nil? or source.empty? or target.nil? or target.empty? 20 | raise 'Payload is invalid.' 21 | end 22 | 23 | # Translate your text 24 | translation = GoogleTranslate.translate( 25 | from: source, 26 | to: target, 27 | text: text 28 | ) 29 | 30 | # Return the translation 31 | res.json({ 32 | "text": text, 33 | "translation": translation 34 | }) 35 | end 36 | -------------------------------------------------------------------------------- /ruby/wipe-appwrite-bucket/Gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | 3 | gem 'appwrite' -------------------------------------------------------------------------------- /ruby/wipe-appwrite-bucket/README.md: -------------------------------------------------------------------------------- 1 | # 🗑 Wipe Appwrite Bucket 2 | 3 | A Ruby cloud function to wipe a complete bucket in Appwrite by passing the bucket id as a payload. 4 | 5 | _Example input:_ 6 | 7 | ```json 8 | { 9 | "bucketId":"profilePictures" 10 | } 11 | ``` 12 | 13 | _Example output:_ 14 | 15 | ```json 16 | { 17 | "success":true 18 | } 19 | ``` 20 | 21 | _Example error output:_ 22 | 23 | ```json 24 | { 25 | "success":false, 26 | "message":"bucketId was not provided." 27 | } 28 | ``` 29 | 30 | ## 📝 Variables 31 | 32 | List of variables used by this cloud function: 33 | 34 | - **APPWRITE_FUNCTION_ENDPOINT** - Endpoint of Appwrite project 35 | - **APPWRITE_FUNCTION_API_KEY** - Appwrite API Key 36 | - **APPWRITE_FUNCTION_PROJECT_ID** - Appwrite project ID. If running on Appwrite, this variable is provided automatically. 37 | 38 | ## 🚀 Deployment 39 | 40 | There are two ways of deploying the Appwrite function, both having the same results, but each using a different process. We highly recommend using CLI deployment to achieve the best experience. 41 | 42 | ### Using CLI 43 | 44 | Make sure you have [Appwrite CLI](https://appwrite.io/docs/command-line#installation) installed, and you have successfully logged into your Appwrite server. To make sure Appwrite CLI is ready, you can use the command `appwrite client --debug` and it should respond with green text `✓ Success`. 45 | 46 | Make sure you are in the same folder as your `appwrite.json` file and run `appwrite deploy function` to deploy your function. You will be prompted to select which functions you want to deploy. 47 | 48 | ### Manual using tar.gz 49 | 50 | Manual deployment has no requirements and uses Appwrite Console to deploy the tag. First, enter the folder of your function. Then, create a tarball of the whole folder and gzip it. After creating `.tar.gz` file, visit Appwrite Console, click on the `Deploy Tag` button and switch to the `Manual` tab. There, set the `entrypoint` to `index.rb`, and upload the file we just generated. 51 | -------------------------------------------------------------------------------- /ruby/wipe-appwrite-bucket/index.rb: -------------------------------------------------------------------------------- 1 | require 'appwrite' 2 | 3 | def main(req, res) 4 | client = Appwrite::Client.new 5 | storage = Appwrite::Storage.new(client) 6 | 7 | if !req.variables['APPWRITE_FUNCTION_ENDPOINT'] or !req.variables['APPWRITE_FUNCTION_API_KEY'] or !req.variables['APPWRITE_FUNCTION_PROJECT_ID'] 8 | return res.json({ 9 | :success => false, 10 | :message => 'Environment variables are not set. Function cannot use Appwrite SDK.', 11 | }) 12 | end 13 | 14 | bucket_id = nil 15 | begin 16 | payload = JSON.parse(req.payload) 17 | bucket_id = (payload['bucketId'] || '').delete(' ') 18 | rescue Exception => err 19 | return res.json({ 20 | :success => false, 21 | :message => 'Payload is invalid.', 22 | }) 23 | end 24 | 25 | if !bucket_id || bucket_id == '' 26 | return res.json({ 27 | :success => false, 28 | :message => 'bucketId was not provided.', 29 | }) 30 | end 31 | 32 | client 33 | .set_endpoint(req.variables['APPWRITE_FUNCTION_ENDPOINT']) 34 | .set_project(req.variables['APPWRITE_FUNCTION_PROJECT_ID']) 35 | .set_key(req.variables['APPWRITE_FUNCTION_API_KEY']) 36 | .set_self_signed(true) 37 | 38 | done = false 39 | while !done do 40 | file_list = nil 41 | begin 42 | file_list = storage.list_files(bucket_id: bucket_id) 43 | rescue Exception => err 44 | return res.json({ 45 | :success => false, 46 | :message => 'Failed to get file list.', 47 | }) 48 | end 49 | 50 | file_list.files.each do |file| 51 | storage.delete_file(bucket_id: bucket_id, file_id: file.id) 52 | end 53 | 54 | if file_list.files.count <= 0 55 | done = true 56 | end 57 | end 58 | 59 | return res.json({ 60 | :success => true, 61 | }) 62 | end 63 | -------------------------------------------------------------------------------- /ruby/wipe-appwrite-collection/Gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | 3 | gem 'appwrite' -------------------------------------------------------------------------------- /ruby/wipe-appwrite-collection/README.md: -------------------------------------------------------------------------------- 1 | # 🧹 Wipe Appwrite Collection 2 | 3 | A Ruby Cloud Function that wipes all documents from an Appwrite collection. 4 | 5 | _Example input:_ 6 | 7 | ```json 8 | { 9 | "databaseId":"stage", 10 | "collectionId":"profiles" 11 | } 12 | ``` 13 | 14 | _Example output:_ 15 | 16 | 17 | ```json 18 | { 19 | "success":true 20 | } 21 | ``` 22 | 23 | _Example error output:_ 24 | 25 | 26 | ```json 27 | { 28 | "success":false, 29 | "message":"databaseId was not provided." 30 | } 31 | ``` 32 | 33 | ## 📝 Environment Variables 34 | 35 | List of environment variables used by this cloud function: 36 | 37 | - **APPWRITE_FUNCTION_ENDPOINT** - Endpoint of Appwrite project 38 | - **APPWRITE_FUNCTION_API_KEY** - Appwrite API Key 39 | - **APPWRITE_FUNCTION_PROJECT_ID** - Appwrite project ID. If running on Appwrite, this variable is provided automatically. 40 | 41 | ## 🚀 Deployment 42 | 43 | There are two ways of deploying the Appwrite function, both having the same results, but each using a different process. We highly recommend using CLI deployment to achieve the best experience. 44 | 45 | ### Using CLI 46 | 47 | Make sure you have [Appwrite CLI](https://appwrite.io/docs/command-line#installation) installed, and you have successfully logged into your Appwrite server. To make sure Appwrite CLI is ready, you can use the command `appwrite client --debug` and it should respond with green text `✓ Success`. 48 | 49 | Make sure you are in the same folder as your `appwrite.json` file and run `appwrite deploy function` to deploy your function. You will be prompted to select which functions you want to deploy. 50 | 51 | ### Manual using tar.gz 52 | 53 | Manual deployment has no requirements and uses Appwrite Console to deploy the tag. First, enter the folder of your function. Then, create a tarball of the whole folder and gzip it. After creating `.tar.gz` file, visit Appwrite Console, click on the `Deploy Tag` button and switch to the `Manual` tab. There, set the `entrypoint` to `index.rb`, and upload the file we just generated. 54 | -------------------------------------------------------------------------------- /ruby/wipe-appwrite-collection/index.rb: -------------------------------------------------------------------------------- 1 | require 'appwrite' 2 | 3 | def main(req, res) 4 | client = Appwrite::Client.new 5 | database = Appwrite::Databases.new(client) 6 | 7 | if !req.variables['APPWRITE_FUNCTION_ENDPOINT'] or !req.variables['APPWRITE_FUNCTION_API_KEY'] 8 | return res.json({ 9 | :success => false, 10 | :message => 'Environment variables are not set. Function cannot use Appwrite SDK.', 11 | }) 12 | end 13 | 14 | database_id = nil 15 | collection_id = nil 16 | begin 17 | payload = JSON.parse(req.payload) 18 | database_id = (payload['databaseId'] || '').delete(' ') 19 | collection_id = (payload['collectionId'] || '').delete(' ') 20 | rescue Exception => err 21 | return res.json({ 22 | :success => false, 23 | :message => 'Payload is invalid.', 24 | }) 25 | end 26 | 27 | if !database_id || database_id == '' 28 | return res.json({ 29 | :success => false, 30 | :message => 'databaseId was not provided.', 31 | }) 32 | end 33 | 34 | if !collection_id || collection_id == '' 35 | return res.json({ 36 | :success => false, 37 | :message => 'collectionId was not provided.', 38 | }) 39 | end 40 | 41 | client 42 | .set_endpoint(req.variables['APPWRITE_FUNCTION_ENDPOINT']) 43 | .set_project(req.variables['APPWRITE_FUNCTION_PROJECTID']) 44 | .set_key(req.variables['APPWRITE_FUNCTION_API_KEY']) 45 | .set_self_signed(true) 46 | 47 | done = false 48 | while !done do 49 | document_list = nil 50 | begin 51 | document_list = database.list_documents(database_id: database_id, collection_id: collection_id) 52 | rescue Exception => err 53 | return res.json({ 54 | :success => false, 55 | :message => 'Failed to get documents list.', 56 | }) 57 | end 58 | 59 | document_list.documents.each do |document| 60 | database.delete_document(database_id: database_id, collection_id: collection_id, document_id: document.id) 61 | end 62 | 63 | if document_list.documents.count <= 0 64 | done = true 65 | end 66 | end 67 | 68 | return res.json({ 69 | :success => true, 70 | }) 71 | end 72 | -------------------------------------------------------------------------------- /swift/convert-phone-number-to-country-name/Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version:5.5 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "swift-5.5", 8 | dependencies: [ 9 | // Dependencies declare other packages that this package depends on. 10 | // .package(url: /* package url */, from: "1.0.0"), 11 | .package(url: "https://github.com/appwrite/sdk-for-swift", .upToNextMajor(from: "0.3.0")), 12 | ], 13 | targets: [ 14 | // Targets are the basic building blocks of a package. A target can define a module or a test suite. 15 | // Targets can depend on other targets in this package, and on products in packages this package depends on. 16 | .executableTarget( 17 | name: "swift-5.5", 18 | dependencies: [ 19 | .product(name: "Appwrite", package: "sdk-for-swift") 20 | ]), 21 | ] 22 | ) -------------------------------------------------------------------------------- /swift/get-covid-stats/CovidData.swift: -------------------------------------------------------------------------------- 1 | struct CovidData : Codable { 2 | let global: Global 3 | let countries: [Country] 4 | 5 | enum CodingKeys : String, CodingKey { 6 | case global = "Global" 7 | case countries = "Countries" 8 | } 9 | } 10 | 11 | struct Global : Codable { 12 | let newConfirmed: Int 13 | let newDeaths: Int 14 | let newRecovered: Int 15 | 16 | enum CodingKeys: String, CodingKey { 17 | case newConfirmed = "NewConfirmed" 18 | case newDeaths = "NewDeaths" 19 | case newRecovered = "NewRecovered" 20 | } 21 | } 22 | 23 | struct Country : Codable { 24 | let country: String 25 | let countryCode: String 26 | let slug: String 27 | let newConfirmed: Int 28 | let newDeaths: Int 29 | let newRecovered: Int 30 | 31 | enum CodingKeys: String, CodingKey { 32 | case country = "Country" 33 | case countryCode = "CountryCode" 34 | case slug = "Slug" 35 | case newConfirmed = "NewConfirmed" 36 | case newDeaths = "NewDeaths" 37 | case newRecovered = "NewRecovered" 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /swift/get-covid-stats/Index.swift: -------------------------------------------------------------------------------- 1 | import AsyncHTTPClient 2 | import Foundation 3 | import NIOCore 4 | import NIOFoundationCompat 5 | 6 | func main(req: RequestValue, res: RequestResponse) async throws -> RequestResponse { 7 | let httpClient = HTTPClient(eventLoopGroupProvider: .createNew) 8 | 9 | guard !req.payload.isEmpty, 10 | let data = req.payload.data(using: .utf8), 11 | let payload: [String: Any?] = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any], 12 | let countryId = payload["country"] as? String else { 13 | return res.json(data: ["error": "Invalid payload."]) 14 | } 15 | 16 | let request = HTTPClientRequest(url: "https://api.covid19api.com/summary") 17 | let response = try await httpClient.execute(request, timeout: .seconds(30)) 18 | let body = try await response.body.collect(upTo: 1024*1024) // 1MB 19 | 20 | if (response.status != .ok) { 21 | return res.json(data: ["error": "Failed to fetch data: \(body)"]) 22 | } 23 | 24 | let covidData = try! JSONDecoder().decode(CovidData.self, from: body) 25 | 26 | let resultCountry = covidData.countries.filter { 27 | [ 28 | $0.countryCode.lowercased(), 29 | $0.country.lowercased(), 30 | $0.slug.lowercased() 31 | ].contains(countryId.lowercased()) 32 | }.first 33 | 34 | // Variables that will be shown in output 35 | let country = resultCountry?.country ?? "The World" 36 | let confirmedCasesToday = resultCountry?.newConfirmed ?? covidData.global.newConfirmed 37 | let deathsToday = resultCountry?.newDeaths ?? covidData.global.newDeaths 38 | let recoveredToday = resultCountry?.newRecovered ?? covidData.global.newRecovered 39 | 40 | return res.json(data: [ 41 | "country": country, 42 | "confirmedCasesToday": confirmedCasesToday, 43 | "deathsToday": deathsToday, 44 | "recoveredToday": recoveredToday 45 | ]) 46 | } -------------------------------------------------------------------------------- /swift/get-covid-stats/Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version:5.5 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "GetCovidStats", 8 | dependencies: [ 9 | // Dependencies declare other packages that this package depends on. 10 | .package(url: "https://github.com/swift-server/async-http-client.git", from: "1.9.0") 11 | ], 12 | targets: [ 13 | // Targets are the basic building blocks of a package. A target can define a module or a test suite. 14 | // Targets can depend on other targets in this package, and on products in packages this package depends on. 15 | .executableTarget( 16 | name: "GetCovidStats", 17 | dependencies: [ 18 | .product(name: "AsyncHTTPClient", package: "async-http-client") 19 | ] 20 | ), 21 | ] 22 | ) 23 | -------------------------------------------------------------------------------- /swift/get-covid-stats/README.md: -------------------------------------------------------------------------------- 1 | # 🦠 Get COVID-19 stats from an API 2 | 3 | A Swift Cloud Function for fetching COVID information using [Covid19Api](https://covid19api.com/). 4 | 5 | _Example input:_ 6 | 7 | ```json 8 | { 9 | "country": "NZ" 10 | } 11 | ``` 12 | 13 | _Example output:_ 14 | 15 | 16 | ```json 17 | { 18 | "country": "New Zealand", 19 | "confirmedCasesToday": 2, 20 | "recoveredToday": 4, 21 | "deathsToday": 0 22 | } 23 | ``` 24 | 25 | ## 📝 Environment Variables 26 | 27 | No environment variables needed. 28 | 29 | ## 🚀 Deployment 30 | 31 | 1. Clone this repository, and enter this function folder: 32 | 33 | ``` 34 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 35 | $ cd swift/convert_phone_number_to_country_name 36 | ``` 37 | 38 | 2. Enter this function folder and build the code: 39 | ``` 40 | docker run --rm --interactive --tty --volume $PWD:/usr/code openruntimes/swift:v2-5.5 sh /usr/local/src/build.sh 41 | ``` 42 | As a result, a `code.tar.gz` file will be generated. 43 | 44 | 3. Start the Open Runtime: 45 | ``` 46 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_KEY=secret-key --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/swift:v2-5.5 sh /usr/local/src/start.sh 47 | ``` 48 | 49 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit Swift runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/swift-5.5). 50 | 51 | ## 📝 Notes 52 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 53 | - This example is compatible with Swift 5.5. Other versions may work but are not guarenteed to work as they haven't been tested. -------------------------------------------------------------------------------- /swift/send-email-with-mailgun/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | /.build 3 | /Packages 4 | /.Package.resolved 5 | /*.xcodeproj 6 | xcuserdata/ 7 | DerivedData/ 8 | .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata 9 | -------------------------------------------------------------------------------- /swift/send-email-with-mailgun/Index.swift: -------------------------------------------------------------------------------- 1 | import AsyncHTTPClient 2 | import Foundation 3 | 4 | func main(req: RequestValue, res: RequestResponse) async throws -> RequestResponse { 5 | 6 | guard !req.payload.isEmpty, 7 | let data = req.payload.data(using: .utf8), 8 | let payload: [String: Any?] = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any], 9 | let name = payload["name"] as? String, 10 | let email = payload["email"] as? String else { 11 | return res.json(data: ["error": "Invalid payload."]) 12 | } 13 | 14 | guard let mailgunDomain = req.variables["MAILGUN_DOMAIN"], 15 | let mailgunAPIKey = req.variables["MAILGUN_API_KEY"] else { 16 | return res.json(data: ["error": "Missing environment variables."]) 17 | } 18 | 19 | let message = "Welcome \(name)!" 20 | let targetURL = "https://api.mailgun.net/v3/\(mailgunDomain)/messages" 21 | let auth = "api:\(mailgunAPIKey)".data(using: .utf8)!.base64EncodedString() 22 | let params = [ 23 | "from" : "Excited User ", 24 | "to" : email, 25 | "subject" : "Hello", 26 | "text" : message 27 | ] 28 | 29 | let httpClient = HTTPClient(eventLoopGroupProvider: .createNew) 30 | var request = HTTPClientRequest(url: targetURL) 31 | request.method = .POST 32 | request.headers.add(name: "Content-Type", value: "multipart/form-data") 33 | request.headers.add(name: "Authorization", value: "Basic \(auth)") 34 | 35 | buildMultipart(&request, with: params) 36 | 37 | let response = try await httpClient.execute(request, timeout: .seconds(30)) 38 | var body = try await response.body.collect(upTo: 1024*1024) //1MB 39 | let string = body.readString(length: body.readableBytes) 40 | 41 | if response.status == .ok { 42 | return res.send(data: string ?? "OK") 43 | } else { 44 | return res.json(data: [ 45 | "code": 500, 46 | "message": string ?? "Unknown error" 47 | ]) 48 | } 49 | } -------------------------------------------------------------------------------- /swift/send-email-with-mailgun/Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version:5.3 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "WelcomeEmail", 8 | dependencies: [ 9 | .package(url: "https://github.com/swift-server/async-http-client.git", from: "1.9.0"), 10 | ], 11 | targets: [ 12 | .target( 13 | name: "WelcomeEmail", 14 | dependencies: [ 15 | .product(name: "AsyncHTTPClient", package: "async-http-client"), 16 | ]) 17 | ] 18 | ) 19 | -------------------------------------------------------------------------------- /swift/send-email-with-mailgun/README.md: -------------------------------------------------------------------------------- 1 | # 📧 Sending Welcome Emails using Mailgun's Email API 2 | 3 | A sample Swift Cloud Function for sending emails using the Mailgun API. 4 | 5 | 6 | _Example input:_ 7 | 8 | ```json 9 | { 10 | "name": "John Doe", 11 | "email": "johndoe@gmail.com" 12 | } 13 | ``` 14 | 15 | 16 | _Example output:_ 17 | 18 | 19 | ```json 20 | { 21 | "id":"", 22 | "message":"Queued. Thank you." 23 | } 24 | ``` 25 | 26 | ## 📝 Environment Variables 27 | 28 | List of environment variables used by this cloud function: 29 | 30 | * **MAILGUN_API_KEY** - API Key for Mailgun 31 | * **MAILGUN_DOMAIN** - Domain Name from Mailgun 32 | 33 | ## 🚀 Deployment 34 | 35 | 1. Clone this repository, and enter this function folder: 36 | 37 | ``` 38 | $ git clone https://github.com/open-runtimes/examples.git && cd examples 39 | $ cd swift/send-email-with-mailgun 40 | ``` 41 | 42 | 2. Build the code: 43 | ``` 44 | docker run --rm --interactive --tty --volume $PWD:/usr/code openruntimes/swift:v2-5.5 sh /usr/local/src/build.sh 45 | ``` 46 | As a result, a `code.tar.gz` file will be generated. 47 | 48 | 3. Start the Open Runtime: 49 | ``` 50 | docker run -p 3000:3000 -e INTERNAL_RUNTIME_KEY=secret-key --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/swift:v2-5.5 sh /usr/local/src/start.sh 51 | ``` 52 | 53 | Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit Swift runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/swift-5.5). 54 | 55 | ## 📝 Notes 56 | - This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). 57 | - This example is compatible with NodeJS 5.5. --------------------------------------------------------------------------------