|
| 1 | +// |
| 2 | +// AddCommand.swift |
| 3 | +// |
| 4 | +// |
| 5 | +// Created by Jonas Frey on 01.05.21. |
| 6 | +// |
| 7 | + |
| 8 | +import Foundation |
| 9 | +import Telegrammer |
| 10 | + |
| 11 | +struct AddCommand: Command { |
| 12 | + |
| 13 | + let name = "Add" |
| 14 | + let commands = ["/add"] |
| 15 | + let syntax = "/add <name> <URL> \\[x y width height]" |
| 16 | + let description = "Adds a new website with an optional screenshot area to the list" |
| 17 | + let permission = BotPermission.mod |
| 18 | + |
| 19 | + func run(update: Update, context: BotContext?) throws { |
| 20 | + let chatID = try update.chatID() |
| 21 | + let args = try update.args() |
| 22 | + guard args.count > 0 else { |
| 23 | + try showUsage(chatID) |
| 24 | + return |
| 25 | + } |
| 26 | + |
| 27 | + // Check if there is a valid URL |
| 28 | + guard let urlIndex = args.lastIndex(where: { $0.starts(with: "http") }) else { |
| 29 | + // No valid URL found |
| 30 | + try bot.sendMessage("Please enter a valid URL, starting with 'http://' or 'https://'", to: chatID) |
| 31 | + return |
| 32 | + } |
| 33 | + // The first argument should be the name, not the URL |
| 34 | + if urlIndex == 0 { |
| 35 | + try showUsage(chatID) |
| 36 | + return |
| 37 | + } |
| 38 | + // Parse the arguments |
| 39 | + let name = args[0..<urlIndex].joined(separator: " ") |
| 40 | + let url = args[urlIndex] |
| 41 | + |
| 42 | + let area: Rectangle! |
| 43 | + if args.count == urlIndex + 5 { |
| 44 | + // If a cropping area was supplied |
| 45 | + let x = Int(args[urlIndex + 1]) |
| 46 | + let y = Int(args[urlIndex + 2]) |
| 47 | + let width = Int(args[urlIndex + 3]) |
| 48 | + let height = Int(args[urlIndex + 4]) |
| 49 | + guard x != nil && y != nil && width != nil && height != nil else { |
| 50 | + try bot.sendMessage("Please enter a valid Offset and Size", to: chatID) |
| 51 | + return |
| 52 | + } |
| 53 | + area = Rectangle(x: x!, y: y!, width: width!, height: height!) |
| 54 | + } else if args.count == urlIndex + 1 { |
| 55 | + // No cropping area |
| 56 | + area = .zero |
| 57 | + } else { |
| 58 | + try showUsage(chatID) |
| 59 | + return |
| 60 | + } |
| 61 | + |
| 62 | + // Create the new entry |
| 63 | + let entry = URLEntry(name: name, url: url, area: area, chatID: chatID) |
| 64 | + var config = try ConfigParser.getConfig() |
| 65 | + // Only check for matching names in the same chat |
| 66 | + guard !config.contains(where: { $0.name.lowercased() == name.lowercased() && $0.chatID == chatID }) else { |
| 67 | + try bot.sendMessage("There is an entry with that name already", to: chatID) |
| 68 | + return |
| 69 | + } |
| 70 | + config.append(entry) |
| 71 | + try ConfigParser.saveConfig(config) |
| 72 | + |
| 73 | + try bot.sendMessage("Added '\(name)'", to: chatID) |
| 74 | + } |
| 75 | + |
| 76 | +} |
0 commit comments