diff --git a/.github/workflows/oint_convert.yml b/.github/workflows/oint_convert.yml index 82ddbaeea0..8ae49eb8c3 100644 --- a/.github/workflows/oint_convert.yml +++ b/.github/workflows/oint_convert.yml @@ -47,6 +47,9 @@ jobs: - name: Обновить Workflow тестирования OInt (EN) run: oscript ./.github/workflows/os/oint_testmaker_en.os + - name: Скрипт форматирования модулей + run: oscript ./.github/workflows/os/format.os + - uses: stefanzweifel/git-auto-commit-action@v5 with: diff --git a/.github/workflows/os/format.os b/.github/workflows/os/format.os new file mode 100644 index 0000000000..4d00b93429 --- /dev/null +++ b/.github/workflows/os/format.os @@ -0,0 +1,206 @@ +Процедура ОтформатироватьМодуль(Знач ПутьКМодулю) Экспорт + + ТекстовыйДокумент = Новый ТекстовыйДокумент(); + ТекстовыйДокумент.Прочитать(ПутьКМодулю, "UTF-8"); + + БлокиКода = РазобратьМодульНаБлоки(ТекстовыйДокумент); + + Для Н = 0 По БлокиКода.ВГраница() Цикл + + МассивСтрокБлока = СтрРазделить(БлокиКода[Н], Символы.ПС); + + Если МассивСтрокБлока.Количество() < 2 Тогда + Продолжить; + ИначеЕсли СтрНачинаетсяС(СокрЛП(МассивСтрокБлока[1]), "//") Тогда + Продолжить; + Иначе + ВыровнятьЗнакиРавно(МассивСтрокБлока); + ВыровнятьЗапятые(МассивСтрокБлока); + КонецЕсли; + + БлокиКода[Н] = СтрСоединить(МассивСтрокБлока, Символы.ПС); + + КонецЦикла; + + ТекстФайла = СтрСоединить(БлокиКода, ""); + + ТекстовыйДокумент.УстановитьТекст(ТекстФайла); + ТекстовыйДокумент.Записать(ПутьКМодулю); + +КонецПроцедуры + +Функция РазобратьМодульНаБлоки(Знач ТекстовыйДокумент) + + Для Н = 1 По ТекстовыйДокумент.КоличествоСтрок() Цикл + + ТекущаяСтрока = ТекстовыйДокумент.ПолучитьСтроку(Н); + + Если Не ЗначениеЗаполнено(СокрЛП(ТекущаяСтрока)) Тогда + ТекстовыйДокумент.ЗаменитьСтроку(Н, "⣿"); + Иначе + ТекстовыйДокумент.ЗаменитьСтроку(Н, СокрП(ТекущаяСтрока)); + КонецЕсли; + + КонецЦикла; + + ТекстФайла = ТекстовыйДокумент.ПолучитьТекст(); + БлокиФайла = СтрРазделить(ТекстФайла, "⣿"); + + Возврат БлокиФайла; + +КонецФункции + +Процедура ВыровнятьЗнакиРавно(МассивСтрокБлока) + + СоответствиеРасположений = Новый Соответствие(); + МаксимальноеРасположение = 0; + ЧислоЗнаковРавно = 0; + + Для Н = 0 По МассивСтрокБлока.ВГраница() Цикл + + РасположениеРавно = СтрНайти(МассивСтрокБлока[Н], "="); + СоответствиеРасположений.Вставить(Н, РасположениеРавно); + МаксимальноеРасположение = ?(РасположениеРавно > МаксимальноеРасположение, РасположениеРавно, МаксимальноеРасположение); + + Если Не РасположениеРавно = 0 Тогда + ЧислоЗнаковРавно = ЧислоЗнаковРавно + 1; + КонецЕсли; + + КонецЦикла; + + Если МаксимальноеРасположение = 0 Или ЧислоЗнаковРавно < 2 Тогда + Возврат; + КонецЕсли; + + Для Каждого СтрокаБлока Из СоответствиеРасположений Цикл + + РасположениеРавно = СтрокаБлока.Значение; + Индекс = СтрокаБлока.Ключ; + + Если РасположениеРавно = 0 Или МаксимальноеРасположение - РасположениеРавно > 12 Тогда + Продолжить; + КонецЕсли; + + Для Н = РасположениеРавно По МаксимальноеРасположение - 1 Цикл + МассивСтрокБлока[Индекс] = СтрЗаменить(МассивСтрокБлока[Индекс], "=", " ="); + КонецЦикла; + + КонецЦикла; + +КонецПроцедуры + +Процедура ВыровнятьЗапятые(МассивСтрокБлока, СоответствиеМаксимумов = "") + + ПолноеСоответствиеРасположений = Новый Соответствие(); + СтрокаСЗапятыми = 0; + НачалоСтроки = ""; + + Для Н = 0 По МассивСтрокБлока.ВГраница() Цикл + + МассивУчастков = СтрРазделить(МассивСтрокБлока[Н], ","); + МассивУчастков_ = Новый Массив; + Соединение = Ложь; + СтрокаСоединения = ""; + + Для Каждого Участок Из МассивУчастков Цикл + + ЧислоКавычек = СтрЧислоВхождений(Участок, """"); + + Если (ЧислоКавычек = 0 Или ЧислоКавычек % 2 = 0 ) И Не Соединение Тогда + + МассивУчастков_.Добавить(Участок); + + ИначеЕсли Соединение И ЧислоКавычек % 2 <> 0 Тогда + МассивУчастков_.Добавить(СтрокаСоединения + "," + Участок); + СтрокаСоединения = ""; + Соединение = Ложь; + + Иначе + СтрокаСоединения = ?(ЗначениеЗаполнено(СтрокаСоединения), СтрокаСоединения + "," + Участок, Участок); + Соединение = Истина; + КонецЕсли; + + КонецЦикла; + + МассивУчастков = МассивУчастков_; + + Если МассивУчастков.Количество() < 2 Тогда + Продолжить; + Иначе + СтрокаСЗапятыми = СтрокаСЗапятыми + 1; + КонецЕсли; + + МассивНачалаСтроки = СтрРазделить(МассивУчастков[0], "("); + + Если МассивНачалаСтроки.Количество() < 2 Тогда + Продолжить; + КонецЕсли; + + НачалоСтроки = МассивНачалаСтроки[0]; + СоответствиеРасположений = ПолноеСоответствиеРасположений[НачалоСтроки]; + + Если Не ЗначениеЗаполнено(СоответствиеРасположений) Тогда + СоответствиеРасположений = Новый Соответствие; + КонецЕсли; + + Для Р = 0 По МассивУчастков.ВГраница() - 1 Цикл + + Если Не ЗначениеЗаполнено(СоответствиеМаксимумов) Тогда + + ДлинаУчастка = СтрДлина(МассивУчастков[Р]); + + ТекущийМаксимум = СоответствиеРасположений.Получить(Р); + ТекущийМаксимум = ?(ЗначениеЗаполнено(ТекущийМаксимум), ТекущийМаксимум, 0); + ТекущийМаксимум = ?(ДлинаУчастка > ТекущийМаксимум , ДлинаУчастка , ТекущийМаксимум); + + СоответствиеРасположений.Вставить(Р, ТекущийМаксимум); + + Иначе + + ТекущееСоответствиеМаксимумов = СоответствиеМаксимумов[НачалоСтроки]; + + Если Не ЗначениеЗаполнено(ТекущееСоответствиеМаксимумов) Тогда + Прервать; + КонецЕсли; + + НеобходимаяДлина = ТекущееСоответствиеМаксимумов[Р]; + + Если НеобходимаяДлина = Неопределено Тогда + Продолжить; + КонецЕсли; + + Пока СтрДлина(МассивУчастков[Р]) < НеобходимаяДлина Цикл + МассивУчастков[Р] = МассивУчастков[Р] + " "; + КонецЦикла; + + КонецЕсли; + + КонецЦикла; + + ПолноеСоответствиеРасположений.Вставить(НачалоСтроки, СоответствиеРасположений); + + МассивСтрокБлока[Н] = СтрСоединить(МассивУчастков, ","); + + КонецЦикла; + + Если Не ЗначениеЗаполнено(СоответствиеМаксимумов) + И ЗначениеЗаполнено(ПолноеСоответствиеРасположений) + И СтрокаСЗапятыми > 1 Тогда + ВыровнятьЗапятые(МассивСтрокБлока, ПолноеСоответствиеРасположений); + КонецЕсли; + +КонецПроцедуры + +Для Каждого Файл Из НайтиФайлы("./src", "*.os", Истина) Цикл + Если СтрНайти(Файл.ПолноеИмя, "\cli\") = 0 + И СтрНайти(Файл.ПолноеИмя, "/cli/") = 0 Тогда + ОтформатироватьМодуль(Файл.ПолноеИмя); + КонецЕсли; +КонецЦикла; + +Для Каждого Файл Из НайтиФайлы("./src", "*.bsl", Истина) Цикл + Если СтрНайти(Файл.ПолноеИмя, "\cli\") = 0 + И СтрНайти(Файл.ПолноеИмя, "/cli/") = 0 Тогда + ОтформатироватьМодуль(Файл.ПолноеИмя); + КонецЕсли; +КонецЦикла; diff --git a/src/en/OInt/core/Modules/OPI_Airtable.os b/src/en/OInt/core/Modules/OPI_Airtable.os index 3ff4784c3a..c236e573f0 100644 --- a/src/en/OInt/core/Modules/OPI_Airtable.os +++ b/src/en/OInt/core/Modules/OPI_Airtable.os @@ -42,91 +42,91 @@ // Get list of bases // Gets the list of available bases -// +// // Parameters: // Token - String - Token - token // Indent - String - Next page identifier of the base list from the previous request - offset -// +// // Returns: -// Map Of KeyAndValue - serialized JSON response from Airtable +// Map Of KeyAndValue - serialized JSON response from Airtable Function GetListOfBases(Val Token, Val Indent = "") Export - + OPI_TypeConversion.GetLine(Indent); - - URL = "https://api.airtable.com/v0/meta/bases"; - Headers = GetAuthorizationHeader(Token); + + URL = "https://api.airtable.com/v0/meta/bases"; + Headers = GetAuthorizationHeader(Token); Parameters = New Structure; - + OPI_Tools.AddField("offset", Indent, "String", Parameters); - + Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; - + EndFunction // Get base tables // Gets the schema of base tables -// +// // Parameters: // Token - String - Token - token // Base - String - Base identifier - base -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Airtable Function GetDatabaseTables(Val Token, Val Base) Export - + OPI_TypeConversion.GetLine(Base); - - URL = "https://api.airtable.com/v0/meta/bases/" + Base + "/tables"; + + URL = "https://api.airtable.com/v0/meta/bases/" + Base + "/tables"; Headers = GetAuthorizationHeader(Token); - + Response = OPI_Tools.Get(URL, , Headers); - + Return Response; - + EndFunction // Create base // Creates a new database -// +// // Parameters: // Token - String - Token - token // Workspace - String - Workspace identifier - ws // Name - String - New base name - title // TableCollection - Map Of KeyAndValue - Table description: Key > name, Value > array of fields - tablesdata -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Airtable Function CreateDatabase(Val Token, Val Workspace, Val Name, Val TableCollection) Export - + OPI_TypeConversion.GetCollection(TableCollection); - - If Not TypeOf(TableCollection) = Type("Structure") + + If Not TypeOf(TableCollection) = Type("Structure") And Not TypeOf(TableCollection) = Type("Map") Then - + Raise "Error in table collection data"; - + EndIf; - - URL = "https://api.airtable.com/v0/meta/bases"; - Headers = GetAuthorizationHeader(Token); + + URL = "https://api.airtable.com/v0/meta/bases"; + Headers = GetAuthorizationHeader(Token); TableArray = New Array; - + For Each Table In TableCollection Do - + Description = GenerateTableDescription(Table.Key, Table.Value); TableArray.Add(Description); - + EndDo; - + Parameters = New Structure; - OPI_Tools.AddField("name" , Name , "String", Parameters); - OPI_Tools.AddField("tables" , TableArray , "Array", Parameters); - OPI_Tools.AddField("workspaceId", Workspace, "String", Parameters); - + OPI_Tools.AddField("name" , Name , "String", Parameters); + OPI_Tools.AddField("tables" , TableArray , "Array" , Parameters); + OPI_Tools.AddField("workspaceId", Workspace , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction @@ -137,56 +137,56 @@ EndFunction // Create table // Creates a new table in the base -// +// // Parameters: // Token - String - Token - token // Base - String - Base identifier - base // Name - String - New table name - title // FieldArray - Array of Structure - Array of field descriptions - fieldsdata // Description - String - Table description - description -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Airtable Function CreateTable(Val Token, Val Base, Val Name, Val FieldArray, Val Description = "") Export - + OPI_TypeConversion.GetLine(Base); - - URL = "https://api.airtable.com/v0/meta/bases/" + Base + "/tables"; - Headers = GetAuthorizationHeader(Token); - Parameters = GenerateTableDescription(Name, FieldArray, Description); - + + URL = "https://api.airtable.com/v0/meta/bases/" + Base + "/tables"; + Headers = GetAuthorizationHeader(Token); + Parameters = GenerateTableDescription(Name, FieldArray, Description); + Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction // Modify table // Changes the name and/or description of the base -// +// // Parameters: // Token - String - Token - token // Base - String - Base identifier - base // Table - String - Table identifier - table // Name - String - New name - title // Description - String - New description - description -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Airtable Function ModifyTable(Val Token, Val Base, Val Table, Val Name = "", Val Description = "") Export - + OPI_TypeConversion.GetLine(Base); OPI_TypeConversion.GetLine(Table); - - URL = "https://api.airtable.com/v0/meta/bases/" + Base + "/tables/" + Table; - Headers = GetAuthorizationHeader(Token); - Parameters = New Structure; - - OPI_Tools.AddField("name" , Name, "String", Parameters); + + URL = "https://api.airtable.com/v0/meta/bases/" + Base + "/tables/" + Table; + Headers = GetAuthorizationHeader(Token); + Parameters = New Structure; + + OPI_Tools.AddField("name" , Name , "String", Parameters); OPI_Tools.AddField("description", Description , "String", Parameters); - + Response = OPI_Tools.Patch(URL, Parameters, Headers); - + Return Response; EndFunction @@ -197,40 +197,40 @@ EndFunction // Create field // Creates a new field in the table -// +// // Parameters: // Token - String - Token - token // Base - String - Base identifier - base // Table - String - Table identifier - table // FieldStructure - Structure of KeyAndValue - Description of the new field - fielddata -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Airtable Function CreateField(Val Token, Val Base, Val Table, Val FieldStructure) Export - + OPI_TypeConversion.GetLine(Base); OPI_TypeConversion.GetLine(Table); OPI_TypeConversion.GetCollection(FieldStructure); - - If Not TypeOf(FieldStructure) = Type("Structure") + + If Not TypeOf(FieldStructure) = Type("Structure") And Not TypeOf(FieldStructure) = Type("Map") Then - + Raise "Error in field description data"; - + EndIf; - - URL = "https://api.airtable.com/v0/meta/bases/" + Base + "/tables/" + Table + "/fields"; - Headers = GetAuthorizationHeader(Token); - + + URL = "https://api.airtable.com/v0/meta/bases/" + Base + "/tables/" + Table + "/fields"; + Headers = GetAuthorizationHeader(Token); + Response = OPI_Tools.Post(URL, FieldStructure, Headers); - + Return Response; EndFunction // Modify field // Changes the name and/or description of an existing table field -// +// // Parameters: // Token - String - Token - token // Base - String - Base identifier Base - base @@ -238,152 +238,152 @@ EndFunction // Field - String - Field identifier - field // Name - String - New name - title // Description - String - New description - description -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Airtable Function ModifyField(Val Token, Val Base, Val Table, Val Field, Val Name = "", Val Description = "") Export - + OPI_TypeConversion.GetLine(Base); OPI_TypeConversion.GetLine(Table); OPI_TypeConversion.GetLine(Field); - - URL = "https://api.airtable.com/v0/meta/bases/" - + Base - + "/tables/" - + Table - + "/fields/" + + URL = "https://api.airtable.com/v0/meta/bases/" + + Base + + "/tables/" + + Table + + "/fields/" + Field; - + Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure(); - OPI_Tools.AddField("name" , Name, "String", Parameters); + OPI_Tools.AddField("name" , Name , "String", Parameters); OPI_Tools.AddField("description", Description , "String", Parameters); - + Response = OPI_Tools.Patch(URL, Parameters, Headers); - + Return Response; EndFunction // Get field (string) // Gets the description of a string field -// +// // Parameters: // Name - String - New field name - title -// +// // Returns: // Structure - Field description Function GetStringField(Val Name) Export - + Return PrimitiveFieldDescription(Name, "richText"); - + EndFunction // Get field (numeric) // Gets the description of a numeric field -// +// // Parameters: // Name - String - New field name - title // Precision - Number, String - Number of decimal places - precision -// +// // Returns: // Structure - Field description Function GetNumberField(Val Name, Val Precision = 0) Export - + OPI_TypeConversion.GetNumber(Precision); - + OptionsStructure = New Structure("precision", Precision); Return PrimitiveFieldDescription(Name, "number", OptionsStructure); - + EndFunction // Get field (file) // Gets the description of a file field -// +// // Parameters: // Name - String - Field name - title -// +// // Returns: // Structure - Field description Function GetAttachmentField(Val Name) Export - + Return PrimitiveFieldDescription(Name, "multipleAttachments"); - + EndFunction // Get field (checkbox) // Gets the description of a boolean field -// +// // Parameters: // Name - String - Field name - title -// +// // Returns: // Structure - Field description Function GetCheckboxField(Val Name) Export - + OptionsStructure = New Structure("icon,color", "check", "yellowBright"); Return PrimitiveFieldDescription(Name, "checkbox", OptionsStructure); - + EndFunction // Get field (date) // Gets the description of a date field -// +// // Parameters: // Name - String - Field name - title -// +// // Returns: // Structure - Field description Function GetDateField(Val Name) Export - - FormatStructure = New Structure("format,name", "YYYY-MM-DD", "iso"); + + FormatStructure = New Structure("format,name", "YYYY-MM-DD", "iso"); OptionsStructure = New Structure("dateFormat", FormatStructure); - + Return PrimitiveFieldDescription(Name, "date", OptionsStructure); - + EndFunction // Get field (email) // Gets the description of an email field -// +// // Parameters: // Name - String - Field name - title -// +// // Returns: // Structure - Field description Function GetEmailField(Val Name) Export - + Return PrimitiveFieldDescription(Name, "email"); - + EndFunction // Get field (phone) // Gets the description of a phone number field -// +// // Parameters: // Name - String - Field name - title -// +// // Returns: // Structure - Field description Function GetPhoneField(Val Name) Export - + Return PrimitiveFieldDescription(Name, "phoneNumber"); - + EndFunction // Get field (url) // Gets the description of a URL field -// +// // Parameters: // Name - String - Field name - title -// +// // Returns: // Structure - Field description Function GetLinkField(Val Name) Export - + Return PrimitiveFieldDescription(Name, "url"); - + EndFunction #EndRegion @@ -392,67 +392,67 @@ EndFunction // Get list of records // Gets the list of records of the selected table -// +// // Parameters: // Token - String - Token - token // Base - String - Database identifier - base // Table - String - Table identifier - table // Indent - String - Next page identifier of data from the previous request - offset -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Airtable Function GetListOfRecords(Val Token, Val Base, Val Table, Val Indent = "") Export OPI_TypeConversion.GetLine(Base); OPI_TypeConversion.GetLine(Table); - - URL = "https://api.airtable.com/v0/" + Base + "/" + Table; + + URL = "https://api.airtable.com/v0/" + Base + "/" + Table; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure(); OPI_Tools.AddField("offset", Indent, "String", Parameters); - + Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; - + EndFunction // Get record // Gets row data of the table by identifier -// +// // Parameters: // Token - String - Token - token // Base - String - Database identifier - base // Table - String - Table identifier - table // Record - String - Record identifier in the table - record -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Airtable Function GetRecord(Val Token, Val Base, Val Table, Val Record) Export - + OPI_TypeConversion.GetLine(Base); OPI_TypeConversion.GetLine(Table); OPI_TypeConversion.GetLine(Record); - - URL = "https://api.airtable.com/v0/" + Base + "/" + Table + "/" + Record; + + URL = "https://api.airtable.com/v0/" + Base + "/" + Table + "/" + Record; Headers = GetAuthorizationHeader(Token); Response = OPI_Tools.Get(URL, , Headers); - + Return Response; - + EndFunction // Create records // Creates one or an array of records by description or an array of field value descriptions -// +// // Parameters: // Token - String - Token - token // Base - String - Database identifier - base // Table - String - Table identifier - table // Data - Structure, Array of Structure - Set or array of sets of pairs Key : Value > Field : FieldValue - data -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Airtable Function CreatePosts(Val Token, Val Base, Val Table, Val Data) Export @@ -460,52 +460,52 @@ Function CreatePosts(Val Token, Val Base, Val Table, Val Data) Export OPI_TypeConversion.GetLine(Base); OPI_TypeConversion.GetLine(Table); OPI_TypeConversion.GetCollection(Data); - - Parameters = New Structure(); - AddDataDescription(Data, Parameters); - URL = "https://api.airtable.com/v0/" + Base + "/" + Table; + Parameters = New Structure(); + AddDataDescription(Data, Parameters); + + URL = "https://api.airtable.com/v0/" + Base + "/" + Table; Headers = GetAuthorizationHeader(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - - Return Response; - + + Return Response; + EndFunction // Delete records // Deletes one or an array of records by identifiers -// +// // Parameters: // Token - String - Token - token // Base - String - Database identifier - base // Table - String - Table identifier - table // Records - String, Array of String - Identifier or array of record identifiers - records -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Airtable Function DeletePosts(Val Token, Val Base, Val Table, Val Records) Export - + OPI_TypeConversion.GetLine(Base); OPI_TypeConversion.GetLine(Table); OPI_TypeConversion.GetArray(Records); - + RecordString = ""; - + For Each Record In Records Do - RecordString = RecordString + RecordString = RecordString + ?(ValueIsFilled(RecordString), "&", "?") + "records[]=" - + OPI_Tools.NumberToString(Record); + + OPI_Tools.NumberToString(Record); EndDo; - - URL = "https://api.airtable.com/v0/" + Base + "/" + Table + RecordString; + + URL = "https://api.airtable.com/v0/" + Base + "/" + Table + RecordString; Headers = GetAuthorizationHeader(Token); Response = OPI_Tools.Delete(URL, , Headers); - - Return Response; - + + Return Response; + EndFunction #EndRegion @@ -514,67 +514,67 @@ EndFunction // Get comments // Gets the list of comments for a record in the table -// +// // Parameters: // Token - String - Token - token // Base - String - Database identifier - base // Table - String - Table identifier - table // Record - String - Record identifier in the table - record // Indent - String - Next page identifier of data from the previous request - offset -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Airtable Function GetComments(Val Token, Val Base, Val Table, Val Record, Val Indent = "") Export - + OPI_TypeConversion.GetLine(Base); OPI_TypeConversion.GetLine(Table); OPI_TypeConversion.GetLine(Record); - - URL = "https://api.airtable.com/v0/" + Base + "/" + Table + "/" + Record + "/comments"; + + URL = "https://api.airtable.com/v0/" + Base + "/" + Table + "/" + Record + "/comments"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure(); OPI_Tools.AddField("offset", Indent, "String", Parameters); - + Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; - + EndFunction // Create comment // Creates a comment for a record in the table -// +// // Parameters: // Token - String - Token - token // Base - String - Database identifier - base // Table - String - Table identifier - table // Record - String - Record identifier in the table - record // Text - String - Comment text - text -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Airtable Function CreateComment(Val Token, Val Base, Val Table, Val Record, Val Text) Export - + OPI_TypeConversion.GetLine(Base); OPI_TypeConversion.GetLine(Table); OPI_TypeConversion.GetLine(Record); - - URL = "https://api.airtable.com/v0/" + Base + "/" + Table + "/" + Record + "/comments"; + + URL = "https://api.airtable.com/v0/" + Base + "/" + Table + "/" + Record + "/comments"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure(); OPI_Tools.AddField("text", Text, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Modify comment // Changes the text of an existing comment -// +// // Parameters: // Token - String - Token - token // Base - String - Database identifier - base @@ -582,54 +582,54 @@ EndFunction // Record - String - Record identifier in the table - record // Comment - String - Comment identifier - comment // Text - String - New comment text - text -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Airtable Function EditComment(Val Token, Val Base, Val Table, Val Record, Val Comment, Val Text) Export - + OPI_TypeConversion.GetLine(Base); OPI_TypeConversion.GetLine(Table); OPI_TypeConversion.GetLine(Record); OPI_TypeConversion.GetLine(Comment); - - URL = "https://api.airtable.com/v0/" + Base + "/" + Table + "/" + Record + "/comments/" + Comment; + + URL = "https://api.airtable.com/v0/" + Base + "/" + Table + "/" + Record + "/comments/" + Comment; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure(); OPI_Tools.AddField("text", Text, "String", Parameters); - + Response = OPI_Tools.Patch(URL, Parameters, Headers); - + Return Response; - + EndFunction // Delete comment // Deletes a comment for a table record -// +// // Parameters: // Token - String - Token - token // Base - String - Database identifier - base // Table - String - Table identifier - table // Record - String - Record identifier in the table - record // Comment - String - Comment identifier - comment -// +// // Returns: -// Map Of KeyAndValue - serialized JSON response from Airtable +// Map Of KeyAndValue - serialized JSON response from Airtable Function DeleteComment(Val Token, Val Base, Val Table, Val Record, Val Comment) Export OPI_TypeConversion.GetLine(Base); OPI_TypeConversion.GetLine(Table); OPI_TypeConversion.GetLine(Record); OPI_TypeConversion.GetLine(Comment); - - URL = "https://api.airtable.com/v0/" + Base + "/" + Table + "/" + Record + "/comments/" + Comment; + + URL = "https://api.airtable.com/v0/" + Base + "/" + Table + "/" + Record + "/comments/" + Comment; Headers = GetAuthorizationHeader(Token); - + Response = OPI_Tools.Delete(URL, , Headers); - + Return Response; - + EndFunction #EndRegion @@ -639,58 +639,58 @@ EndFunction #Region Private Function GetAuthorizationHeader(Val Token) - + OPI_TypeConversion.GetLine(Token); - + Headers = New Map; Headers.Insert("Authorization", "Bearer " + Token); - + Return Headers; - + EndFunction Function GenerateTableDescription(Val Name, Val FieldArray, Val Description = "") - + OPI_TypeConversion.GetLine(Name); OPI_TypeConversion.GetCollection(FieldArray); - + TableDescription = New Structure("name,fields", Name, FieldArray); - + OPI_Tools.AddField("description", Description, "String", TableDescription); - + Return TableDescription; - + EndFunction Function PrimitiveFieldDescription(Val Name, Val Type, Val Options = "") - + FieldStructure = New Structure(); - OPI_Tools.AddField("name" , Name, "String" , FieldStructure); - OPI_Tools.AddField("type" , Type , "String" , FieldStructure); + OPI_Tools.AddField("name" , Name , "String" , FieldStructure); + OPI_Tools.AddField("type" , Type , "String" , FieldStructure); OPI_Tools.AddField("options", Options , "Collection", FieldStructure); - + Return FieldStructure; EndFunction Procedure AddDataDescription(Val Data, Parameters) - + If TypeOf(Data) = Type("Array") Then - + SendArray = New Array; - + For Each RecordDescription In Data Do - SendArray.Add(New Structure("fields", RecordDescription)); + SendArray.Add(New Structure("fields", RecordDescription)); EndDo; - + OPI_Tools.AddField("records", SendArray, "Array", Parameters); - + Else - - OPI_Tools.AddField("fields", Data, "Collection", Parameters); - + + OPI_Tools.AddField("fields", Data, "Collection", Parameters); + EndIf; - + EndProcedure #EndRegion diff --git a/src/en/OInt/core/Modules/OPI_Bitrix24.os b/src/en/OInt/core/Modules/OPI_Bitrix24.os index f127f4be93..afe4ab0c84 100644 --- a/src/en/OInt/core/Modules/OPI_Bitrix24.os +++ b/src/en/OInt/core/Modules/OPI_Bitrix24.os @@ -47,105 +47,105 @@ // Get app authentication link // Forms a link for authorization via the browser -// +// // Parameters: // Domain - String - Current Bitrix URL (like 'portal.bitrix24.com') - domain // ClientID - String - Client ID from app settings - clientid -// +// // Returns: // String - URL for browser transition Function GetAppAuthLink(Val Domain, Val ClientID) Export - + OPI_TypeConversion.GetLine(Domain); OPI_TypeConversion.GetLine(ClientID); - + If Not StrStartsWith(Domain, "http") Then URL = "https://" + Domain; EndIf; - + If Not StrEndsWith(URL, "/") Then URL = URL + "/"; EndIf; - + URL = URL + "oauth/authorize/?client_id=" + ClientID; - + Return URL; - + EndFunction // Get token // Get token by auth code -// +// // Parameters: // ClientID - String - Client ID from app settings - clientid // ClientSecret - String - Client secret from app settings - clientsecret // Code - String - Code from browser auth page - code -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetToken(Val ClientID, Val ClientSecret, Val Code) Export - - URL = "https://oauth.bitrix.info/oauth/token/"; + + URL = "https://oauth.bitrix.info/oauth/token/"; String_ = "String"; - + Parameters = New Structure; - OPI_Tools.AddField("grant_type" , "authorization_code", String_, Parameters); - OPI_Tools.AddField("client_id" , ClientID , String_, Parameters); - OPI_Tools.AddField("client_secret", ClientSecret , String_, Parameters); - OPI_Tools.AddField("code" , Code , String_, Parameters); - + OPI_Tools.AddField("grant_type" , "authorization_code", String_, Parameters); + OPI_Tools.AddField("client_id" , ClientID , String_, Parameters); + OPI_Tools.AddField("client_secret", ClientSecret , String_, Parameters); + OPI_Tools.AddField("code" , Code , String_, Parameters); + Response = OPI_Tools.Get(URL, Parameters); - + Return Response; - + EndFunction // Refresh token // Update token by refresh token -// +// // Parameters: // ClientID - String - Client ID from app settings - clientid // ClientSecret - String - Client secret from app settings - clientsecret // Refresh - String - Refresh token - refresh -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function RefreshToken(Val ClientID, Val ClientSecret, Val Refresh) Export - - URL = "https://oauth.bitrix.info/oauth/token/"; + + URL = "https://oauth.bitrix.info/oauth/token/"; String_ = "String"; - + Parameters = New Structure; - OPI_Tools.AddField("grant_type" , "refresh_token" , String_, Parameters); - OPI_Tools.AddField("client_id" , ClientID , String_, Parameters); - OPI_Tools.AddField("client_secret", ClientSecret , String_, Parameters); - OPI_Tools.AddField("refresh_token", Refresh , String_, Parameters); - + OPI_Tools.AddField("grant_type" , "refresh_token" , String_, Parameters); + OPI_Tools.AddField("client_id" , ClientID , String_, Parameters); + OPI_Tools.AddField("client_secret", ClientSecret , String_, Parameters); + OPI_Tools.AddField("refresh_token", Refresh , String_, Parameters); + Response = OPI_Tools.Get(URL, Parameters); - + Return Response; EndFunction // Server time // Get current server time -// +// // Note // Method at API documentation: [server_time](@dev.1c-bitrix.ru/rest_help/general/server_time.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function ServerTime(Val URL, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "server.time"); - Response = OPI_Tools.Get(URL, Parameters); - + Response = OPI_Tools.Get(URL, Parameters); + Return Response; - + EndFunction #EndRegion @@ -154,19 +154,19 @@ EndFunction // Create post // Create a new post at news feed -// +// // Note // Method at API documentation: [log.blogpost.add](@dev.1c-bitrix.ru/rest_help/log/log_blogpost_add.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Text - String - Text of post - text // Visibility - String - Array or 1 recipient: UA all, SGn w. group, Un user, DRn department, Gn group - vision // Files - Map Of KeyAndValue - Key > file name, value > path or binary data - files // Title - String - Post title - title -// Important - Boolean - Mark post as important - important +// Important - Boolean - Mark post as important - important // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function CreatePost(Val URL @@ -176,41 +176,41 @@ Function CreatePost(Val URL , Val Title = "" , Val Important = False , Val Token = "") Export - + MakeBoolean(Important); - + String_ = "String"; - + Parameters = NormalizeAuth(URL, Token, "log.blogpost.add"); - OPI_Tools.AddField("POST_MESSAGE", Text , String_, Parameters); - OPI_Tools.AddField("POST_TITLE" , Title , String_, Parameters); - OPI_Tools.AddField("DEST" , Visibility , "Array", Parameters); - OPI_Tools.AddField("IMPORTANT" , Important , String_, Parameters); - + OPI_Tools.AddField("POST_MESSAGE", Text , String_, Parameters); + OPI_Tools.AddField("POST_TITLE" , Title , String_, Parameters); + OPI_Tools.AddField("DEST" , Visibility , "Array", Parameters); + OPI_Tools.AddField("IMPORTANT" , Important , String_, Parameters); + If ValueIsFilled(Files) Then - + OPI_TypeConversion.GetCollection(Files); - + ArrayOfFiles = NormalizeFiles(Files); - + If Not ArrayOfFiles.Count() = 0 Then Parameters.Insert("FILES", ArrayOfFiles); EndIf; - + EndIf; - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Update post // Change post data -// +// // Note // Method at API documentation: [log.blogpost.update](@dev.1c-bitrix.ru/rest_help/log/log_blogpost_update.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // PostID - String, Number - Post ID - postid @@ -219,170 +219,170 @@ EndFunction // Files - Map Of KeyAndValue - Key > file name, value > path or binary data - files // Title - String - Post title - title // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function UpdatePost(Val URL - , Val PostID + , Val PostID , Val Text , Val Visibility = "UA" , Val Files = "" , Val Title = "" , Val Token = "") Export - + String_ = "String"; - + Parameters = NormalizeAuth(URL, Token, "log.blogpost.update"); - OPI_Tools.AddField("POST_MESSAGE", Text , String_, Parameters); - OPI_Tools.AddField("POST_TITLE" , Title , String_, Parameters); - OPI_Tools.AddField("DEST" , Visibility , "Array", Parameters); - OPI_Tools.AddField("POST_ID" , PostID , String_, Parameters); - + OPI_Tools.AddField("POST_MESSAGE", Text , String_, Parameters); + OPI_Tools.AddField("POST_TITLE" , Title , String_, Parameters); + OPI_Tools.AddField("DEST" , Visibility , "Array", Parameters); + OPI_Tools.AddField("POST_ID" , PostID , String_, Parameters); + If ValueIsFilled(Files) Then - + OPI_TypeConversion.GetCollection(Files); - + ArrayOfFiles = NormalizeFiles(Files); - + If Not ArrayOfFiles.Count() = 0 Then Parameters.Insert("FILES", ArrayOfFiles); EndIf; - + EndIf; - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Delete post // Remove post from a news feed -// +// // Note // Method at API documentation: [log.blogpost.delete](@dev.1c-bitrix.ru/rest_help/log/log_blogpost_delete.php) -// +// // Parameters: -// URL - String - URL of webhook or a Bitrix24 domain, when token used - url +// URL - String - URL of webhook or a Bitrix24 domain, when token used - url // PostID - String, Number - Id of post to remove - postid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeletePost(Val URL, Val PostID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "log.blogpost.delete"); OPI_Tools.AddField("POST_ID", PostID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get list of important post viewers // Return list of important post viewers ids -// +// // Note // Method at API documentation: [log.blogpost.getusers.important](@dev.1c-bitrix.ru/rest_help/log/log_blogpost_getusers_important.php) -// +// // Parameters: -// URL - String - URL of webhook or a Bitrix24 domain, when token used - url +// URL - String - URL of webhook or a Bitrix24 domain, when token used - url // PostID - String, Number - Id of important post - postid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetImportantPostViewers(Val URL, Val PostID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "log.blogpost.getusers.important"); OPI_Tools.AddField("POST_ID", PostID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get posts // Gen post or array of post with ID or rights selection -// +// // Note // Method at API documentation: [log.blogpost.get](@dev.1c-bitrix.ru/rest_help/log/log_blogpost_get.php) -// +// // Parameters: -// URL - String - URL of webhook or a Bitrix24 domain, when token used - url +// URL - String - URL of webhook or a Bitrix24 domain, when token used - url // PostID - String, Number - Id of important post - postid -// Filter - String - Post selection by rights: UA all, SGn work group, Un user, DRn depart, Gn group - sel +// Filter - String - Post selection by rights: UA all, SGn work group, Un user, DRn depart, Gn group - sel // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetPosts(Val URL, Val PostID = "", Val Filter = "UA", Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "log.blogpost.get"); - - OPI_Tools.AddField("POST_ID" , PostID, "String", Parameters); + + OPI_Tools.AddField("POST_ID" , PostID , "String", Parameters); OPI_Tools.AddField("LOG_RIGHTS", Filter , "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Add comment to post // Adds a comment to the post -// +// // Note // Method at API documentation: [log.blogcomment.add](@dev.1c-bitrix.ru/rest_help/log/log_blogcomment_add.php) -// +// // Parameters: -// URL - String - URL of webhook or a Bitrix24 domain, when token used - url +// URL - String - URL of webhook or a Bitrix24 domain, when token used - url // PostID - String, Number - Post ID - postid // Text - String - Comment text - text // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function AddPostComment(Val URL, Val PostID, Val Text, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "log.blogcomment.add"); - + OPI_Tools.AddField("POST_ID" , PostID, "String", Parameters); - OPI_Tools.AddField("TEXT" , Text , "String", Parameters); - + OPI_Tools.AddField("TEXT" , Text , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Add new recipients to a post // Adds new groups or users to the recipients -// +// // Note // Method at API documentation: [log.blogpost.share](@dev.1c-bitrix.ru/rest_help/log/log_blogpost_share.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // PostID - String, Number - Post ID - postid // Visibility - String - Array or 1 recipient: UA all, SGn w. group, Un user, DRn department, Gn group - vision // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function AddPostRecipients(Val URL, Val PostID, Val Visibility, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "log.blogpost.share"); - - OPI_Tools.AddField("POST_ID" , PostID, "String", Parameters); - OPI_Tools.AddField("DEST" , Visibility, "String", Parameters); - + + OPI_Tools.AddField("POST_ID" , PostID , "String", Parameters); + OPI_Tools.AddField("DEST" , Visibility, "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction #EndRegion @@ -391,629 +391,629 @@ EndFunction // Get task // Get task by ID -// +// // Note // Method at API documentation: [tasks.task.get](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_get.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetTask(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.get", Token); Return Response; - + EndFunction // Get tasks list // Get tasks list (50 at one response max)) -// +// // Note // Method at API documentation: [tasks.task.list](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_list.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Filter - Structure of KeyAndValue - Structure of task filter (see GetTaskFieldsStructure) - filter // Indent - Number, String - Offset of tasks list - offset // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetTasksList(Val URL, Val Filter = "", Val Indent = 0, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "tasks.task.list"); OPI_Tools.AddField("filter", Filter, "Collection", Parameters); - OPI_Tools.AddField("start" , Indent, "String" , Parameters); - + OPI_Tools.AddField("start" , Indent, "String" , Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Create task // Create new task by fields structure (see GetTaskFieldsStructure) -// +// // Note // Method at API documentation: [tasks.task.add](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_add.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FieldsStructure - Structure of KeyAndValue - Task fields structure (see GetTaskFieldsStructure) - fields // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function CreateTask(Val URL, Val FieldsStructure, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "tasks.task.add"); OPI_Tools.AddField("fields", FieldsStructure, "Collection", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; EndFunction // Update task // Update a task -// +// // Note // Method at API documentation: [tasks.task.update](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_update.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // FieldsStructure - Structure of KeyAndValue - Task fields structure - fields // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function UpdateTask(Val URL, Val TaskID, Val FieldsStructure, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "tasks.task.update"); OPI_Tools.AddField("fields", FieldsStructure, "Collection", Parameters); - OPI_Tools.AddField("taskId", TaskID , "String" , Parameters); - + OPI_Tools.AddField("taskId", TaskID , "String" , Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; EndFunction // Delete task // Delete task by ID -// +// // Note // Method at API documentation: [tasks.task.delete](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_delete.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeleteTask(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.delete", Token); Return Response; - + EndFunction // Attach file to the topic // Attaches a file to the selected task -// +// // Note // Method at API documentation: [tasks.task.files.attach](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_files_attach.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // FileID - Number, String - File ID - fileid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function AttachFileToTopic(Val URL, Val TaskID, Val FileID, Val Token = "") Export Parameters = NormalizeAuth(URL, Token, "tasks.task.files.attach"); OPI_Tools.AddField("fileId", FileID , "String", Parameters); - OPI_Tools.AddField("taskId", TaskID, "String", Parameters); - + OPI_Tools.AddField("taskId", TaskID , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Approve task // Approve task by ID -// +// // Note // Method at API documentation: [tasks.task.approve](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_approve.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function ApproveTask(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.approve", Token); Return Response; - + EndFunction // Disapprove task // Disapprove task by ID -// +// // Note // Method at API documentation: [tasks.task.disapprove](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_disapprove.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DisapproveTask(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.disapprove", Token); Return Response; - + EndFunction // Complete task // Complete task by ID -// +// // Note // Method at API documentation: [tasks.task.complete](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_complete.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function CompleteTask(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.complete", Token); Return Response; - + EndFunction // Renew task // Returns a task to work by ID -// +// // Note // Method at API documentation: [tasks.task.renew](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_renew.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function RenewTask(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.renew", Token); Return Response; - + EndFunction // Defer task // Defer task by ID -// +// // Note // Method at API documentation: [tasks.task.defer](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_defer.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeferTask(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.defer", Token); Return Response; - + EndFunction // Pause task // Pause a task by ID -// +// // Note // Method at API documentation: [tasks.task.pause](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_pause.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function PauseTask(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.pause", Token); Return Response; - + EndFunction // Start a task // Start a task by ID -// +// // Note // Method at API documentation: [tasks.task.start](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_start.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function StartTask(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.start", Token); Return Response; - + EndFunction // Start watching a task // Start watching a task by ID -// +// // Note // Method at API documentation: [tasks.task.startwatch](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_startwatch.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function StartWatchingTask(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.startwatch", Token); Return Response; - + EndFunction // Stop watching the task // Stop watching a task by ID -// +// // Note // Method at API documentation: [tasks.task.stopwatch](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_stopwatch.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function StopWatchingTask(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.stopwatch", Token); Return Response; - + EndFunction // Delegate task // Delegate task to another user -// +// // Note // Method at API documentation: [tasks.task.delegate](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_delegate.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // UserID - Number, String - ID of responsible user - user // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DelegateTask(Val URL, Val TaskID, Val UserID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "tasks.task.delegate"); OPI_Tools.AddField("taskId", TaskID , "String", Parameters); - OPI_Tools.AddField("userId", UserID, "String", Parameters); - + OPI_Tools.AddField("userId", UserID , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Add task to favorites list // Add task to favorites list -// +// // Note // Method at API documentation: [tasks.task.favorite.add](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_favorite_add.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function AddTaskToFavorites(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.favorite.add", Token); Return Response; - + EndFunction // Remove task from favorites list // Delete task from favorites list -// +// // Note // Method at API documentation: [tasks.task.favorite.remove](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_favorite_remove.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function RemoveTaskFromFavorites(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.favorite.remove", Token); Return Response; - + EndFunction // Get task history // Get history of task changing -// +// // Note // Method at API documentation: [tasks.task.history.list](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_history_list.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetTaskHistory(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.history.list", Token); Return Response; - + EndFunction // Check task acesses for users // Checks the availability of the task for users -// +// // Note // Method at API documentation: [tasks.task.getaccess](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_getaccess.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Users - Array of String - User IDs for access checking - users // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function CheckTaskAccesses(Val URL, Val TaskID, Val Users = "", Val Token = "") Export Parameters = NormalizeAuth(URL, Token, "tasks.task.getaccess"); OPI_Tools.AddField("taskId", TaskID , "String" , Parameters); - OPI_Tools.AddField("users" , Users, "Array", Parameters); - + OPI_Tools.AddField("users" , Users , "Array" , Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Mute task // Mute task by ID -// +// // Note // Method at API documentation: [tasks.task.mute](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/mute_unmute.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function MuteTask(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.mute", Token); Return Response; - + EndFunction // Unmute task // Unmute task by ID -// +// // Note // Method at API documentation: [tasks.task.unmute](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/mute_unmute.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function UnmuteTask(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.unmute", Token); Return Response; - + EndFunction // Create tasks dependencies // Creates the dependency of one task to another -// +// // Note // Method at API documentation: [task.dependence.add](@dev.1c-bitrix.ru/rest_help/tasks/task/dependence/task_dependence_add.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FromID - String, Number - From task ID - taskfrom // DestinationID - String, Number - To task ID - taskto // LinkType - String, Number - Link type: 0 start>start, 1 start>finish, 2 finish>start, 3 finish>finish - linktype // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function CreateTasksDependencies(Val URL, Val FromID, Val DestinationID, Val LinkType, Val Token = "") Export - + String_ = "String"; - + OPI_TypeConversion.GetLine(LinkType); - + Parameters = NormalizeAuth(URL, Token, "task.dependence.add"); - OPI_Tools.AddField("taskIdFrom", FromID, String_, Parameters); - OPI_Tools.AddField("taskIdTo" , DestinationID, String_, Parameters); - OPI_Tools.AddField("linkType" , LinkType , String_, Parameters); - + OPI_Tools.AddField("taskIdFrom", FromID , String_, Parameters); + OPI_Tools.AddField("taskIdTo" , DestinationID, String_, Parameters); + OPI_Tools.AddField("linkType" , LinkType , String_, Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Delete tasks dependencies // Removes the dependency of one task to another -// +// // Note // Method at API documentation: [task.dependence.delete](@dev.1c-bitrix.ru/rest_help/tasks/task/dependence/task_dependence_delete.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FromID - String, Number - From task ID - taskfrom // DestinationID - String, Number - To task ID - taskto // LinkType - String, Number - Link type: 0 start>start, 1 start>finish, 2 finish>start, 3 finish>finish - linktype // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeleteTasksDependencies(Val URL, Val FromID, Val DestinationID, Val LinkType, Val Token = "") Export - + String_ = "String"; - + OPI_TypeConversion.GetLine(LinkType); - + Parameters = NormalizeAuth(URL, Token, "task.dependence.delete"); - OPI_Tools.AddField("taskIdFrom", FromID, String_, Parameters); - OPI_Tools.AddField("taskIdTo" , DestinationID, String_, Parameters); - OPI_Tools.AddField("linkType" , LinkType , String_, Parameters); - + OPI_Tools.AddField("taskIdFrom", FromID , String_, Parameters); + OPI_Tools.AddField("taskIdTo" , DestinationID, String_, Parameters); + OPI_Tools.AddField("linkType" , LinkType , String_, Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get users daily tasks plan // Gets the task plan for the current users day -// +// // Note // Method at API documentation: [task.planner.getlist](@dev.1c-bitrix.ru/rest_help/tasks/task/planner/getlist.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetDailyPlan(Val URL, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "task.planner.getlist"); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get task fields structure // Gets a structure with a description of the fields for creating a task -// +// // Note // Method at API documentation: [tasks.task.getFields](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_getFields.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetTaskFieldsStructure(Val URL, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "tasks.task.getFields"); - Response = OPI_Tools.Get(URL, Parameters); - + Response = OPI_Tools.Get(URL, Parameters); + Return Response; - -EndFunction + +EndFunction // Get structure of tasks filter // Return filter structure for GetTasksList -// +// // Parameters: // Clear - Boolean - True > structure with empty valuse, False > field descriptions at values - empty -// +// // Returns: -// Structure of KeyAndValue - Fields structure +// Structure of KeyAndValue - Fields structure Function GetTasksFilterStructure(Val Clear = False) Export - + // More // https://dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_list.php - + OPI_TypeConversion.GetBoolean(Clear); - + FilterStructure = New Structure; - FilterStructure.Insert("ID" , ""); - FilterStructure.Insert("PARENT_ID" , ""); - FilterStructure.Insert("GROUP_ID" , ""); - FilterStructure.Insert("CREATED_BY" , ""); + FilterStructure.Insert("ID" , ""); + FilterStructure.Insert("PARENT_ID" , ""); + FilterStructure.Insert("GROUP_ID" , ""); + FilterStructure.Insert("CREATED_BY" , ""); FilterStructure.Insert("STATUS_CHANGED_BY", ""); - FilterStructure.Insert("PRIORITY" , ""); - FilterStructure.Insert("FORUM_TOPIC_ID" , ""); - FilterStructure.Insert("RESPONSIBLE_ID" , ""); - FilterStructure.Insert("TITLE" , ""); - FilterStructure.Insert("TAG" , ""); - FilterStructure.Insert("REAL_STATUS" , ""); - FilterStructure.Insert("MARK" , ""); - FilterStructure.Insert("SITE_ID" , ""); - FilterStructure.Insert("ADD_IN_REPORT" , ""); - FilterStructure.Insert("DATE_START" , ""); - FilterStructure.Insert("DEADLINE" , ""); - FilterStructure.Insert("CREATED_DATE" , ""); - FilterStructure.Insert("CLOSED_DATE" , ""); - FilterStructure.Insert("CHANGED_DATE" , ""); - FilterStructure.Insert("ACCOMPLICE" , ""); - FilterStructure.Insert("AUDITOR" , ""); - FilterStructure.Insert("DEPENDS_ON" , ""); - FilterStructure.Insert("ONLY_ROOT_TASKS" , ""); - FilterStructure.Insert("STAGE_ID" , ""); - FilterStructure.Insert("UF_CRM_TASK" , ""); + FilterStructure.Insert("PRIORITY" , ""); + FilterStructure.Insert("FORUM_TOPIC_ID" , ""); + FilterStructure.Insert("RESPONSIBLE_ID" , ""); + FilterStructure.Insert("TITLE" , ""); + FilterStructure.Insert("TAG" , ""); + FilterStructure.Insert("REAL_STATUS" , ""); + FilterStructure.Insert("MARK" , ""); + FilterStructure.Insert("SITE_ID" , ""); + FilterStructure.Insert("ADD_IN_REPORT" , ""); + FilterStructure.Insert("DATE_START" , ""); + FilterStructure.Insert("DEADLINE" , ""); + FilterStructure.Insert("CREATED_DATE" , ""); + FilterStructure.Insert("CLOSED_DATE" , ""); + FilterStructure.Insert("CHANGED_DATE" , ""); + FilterStructure.Insert("ACCOMPLICE" , ""); + FilterStructure.Insert("AUDITOR" , ""); + FilterStructure.Insert("DEPENDS_ON" , ""); + FilterStructure.Insert("ONLY_ROOT_TASKS" , ""); + FilterStructure.Insert("STAGE_ID" , ""); + FilterStructure.Insert("UF_CRM_TASK" , ""); FilterStructure.Insert("STATUS" , ""); - + If Clear Then For Each Filter In FilterStructure Do Filter.Value = ""; @@ -1022,7 +1022,7 @@ Function GetTasksFilterStructure(Val Clear = False) Export //@skip-check constructor-function-return-section Return FilterStructure; - + EndFunction #EndRegion @@ -1031,185 +1031,185 @@ EndFunction // Add tasks checklist element // Adds new element of tasks checklist -// +// // Note // Method at API documentation: [task.checklistitem.add](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/add.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Text - String - Text (title) of checklist element - text // Completed - Boolean - Mark as completed - complete // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function AddTasksChecklistElement(Val URL, Val TaskID, Val Text, Val Completed = False, Token = "") Export - + String_ = "String"; - + Parameters = NormalizeAuth(URL, Token, "task.checklistitem.add"); - Fields = New Structure; - + Fields = New Structure; + MakeBoolean(Completed); - - OPI_Tools.AddField("TITLE" , Text , String_, Fields); + + OPI_Tools.AddField("TITLE" , Text , String_, Fields); OPI_Tools.AddField("IS_COMPLETE", Completed, String_, Fields); - - OPI_Tools.AddField("TASKID", TaskID, String_ , Parameters); + + OPI_Tools.AddField("TASKID", TaskID , String_ , Parameters); OPI_Tools.AddField("FIELDS", Fields , "Collection", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Update tasks checklist element // Updates text of element of tasks checklist -// +// // Note // Method at API documentation: [task.checklistitem.update](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/update.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // ElementID - Number, String - Checklist element ID - element // Text - String - Text (title) of checklist element - text // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function UpdateTasksChecklistElement(Val URL, Val TaskID, Val ElementID, Val Text, Val Token = "") Export - + String_ = "String"; - + Parameters = NormalizeAuth(URL, Token, "task.checklistitem.update"); - Fields = New Structure; - + Fields = New Structure; + OPI_Tools.AddField("TITLE", Text, String_, Fields); - - OPI_Tools.AddField("TASKID", TaskID , String_ , Parameters); - OPI_Tools.AddField("ITEMID", ElementID, String_ , Parameters); - OPI_Tools.AddField("FIELDS", Fields , "Collection", Parameters); - + + OPI_Tools.AddField("TASKID", TaskID , String_ , Parameters); + OPI_Tools.AddField("ITEMID", ElementID, String_ , Parameters); + OPI_Tools.AddField("FIELDS", Fields , "Collection", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction - + // Delete tasks checklist element // Deletes element from tasks checklist -// +// // Note // Method at API documentation: [task.checklistitem.delete](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/delete.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // ElementID - Number, String - ID of deleted element - element // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeleteTasksChecklistElement(Val URL, Val TaskID, Val ElementID, Val Token = "") Export Response = ChecklistElementManagment(URL, TaskID, ElementID, "task.checklistitem.delete", Token); - + Return Response; - + EndFunction // Get tasks checklist // Gets the list of elements on the task checklist -// +// // Note // Method at API documentation: [task.checklistitem.getlist](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/getlist.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetTasksChecklist(Val URL, Val TaskID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "task.checklistitem.getlist"); - + OPI_Tools.AddField("TASKID", TaskID , "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get tasks checklist element // Gets tasks checklist element by ID -// +// // Note // Method at API documentation: [task.checklistitem.get](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/get.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // ElementID - Number, String - Element ID - element // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetTasksChecklistElement(Val URL, Val TaskID, Val ElementID, Val Token = "") Export - + Response = ChecklistElementManagment(URL, TaskID, ElementID, "task.checklistitem.get", Token); - + Return Response; - + EndFunction // Complete tasks checklist element // Mark an element as completed -// +// // Note // Method at API documentation: [task.checklistitem.complete](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/complete.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // ElementID - Number, String - Element ID - element // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function CompleteTasksChecklistElement(Val URL, Val TaskID, Val ElementID, Val Token = "") Export - + Response = ChecklistElementManagment(URL, TaskID, ElementID, "task.checklistitem.complete", Token); - + Return Response; - + EndFunction // Renew tasks checklist element -// Unmark an element as completed -// +// Unmark an element as completed +// // Note // Method at API documentation: [task.checklistitem.renew](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/renew.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // ElementID - Number, String - Element ID - element // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function RenewTasksChecklistElement(Val URL, Val TaskID, Val ElementID, Val Token = "") Export - + Response = ChecklistElementManagment(URL, TaskID, ElementID, "task.checklistitem.renew", Token); - + Return Response; - + EndFunction #EndRegion @@ -1218,15 +1218,15 @@ EndFunction // Get comments list for a task // Get user comments list for a task -// +// // Note // Method at API documentation: [task.commentitem.getlist](@dev.1c-bitrix.ru/rest_help/tasks/task/commentitem/getlist.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetTaskCommentsList(Val URL, Val TaskID, Val Token = "") Export @@ -1238,220 +1238,220 @@ EndFunction // Get task comment // Gets task comment data by ID -// +// // Note // Method at API documentation: [task.commentitem.get](@dev.1c-bitrix.ru/rest_help/tasks/task/commentitem/get.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // CommentID - Number, String - CommentID - comment // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetTaskComment(Val URL, Val TaskID, Val CommentID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "task.commentitem.get"); - OPI_Tools.AddField("TASKID", TaskID , "String", Parameters); + OPI_Tools.AddField("TASKID", TaskID , "String", Parameters); OPI_Tools.AddField("ITEMID", CommentID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Add comment to task // Create new comment to the task -// +// // Note // Method at API documentation: [task.commentitem.add](@dev.1c-bitrix.ru/rest_help/tasks/task/commentitem/add.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Text - String - Comment text - text // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function AddTaskComment(Val URL, Val TaskID, Val Text, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "task.commentitem.add"); - + Comment = New Structure; OPI_Tools.AddField("POST_MESSAGE", Text, "String", Comment); - - OPI_Tools.AddField("TASKID", TaskID , "String" , Parameters); + + OPI_Tools.AddField("TASKID", TaskID , "String" , Parameters); OPI_Tools.AddField("FIELDS", Comment, "Collection", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Update task comment // Changes task comment text -// +// // Note // Method at API documentation: [task.commentitem.update](@dev.1c-bitrix.ru/rest_help/tasks/task/commentitem/update.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // CommentID - Number, String - CommentID - comment // Text - String - Comment text - text // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function UpdateTaskComment(Val URL, Val TaskID, Val CommentID, Val Text, Val Token = "") Export - + String_ = "String"; - + Parameters = NormalizeAuth(URL, Token, "task.commentitem.update"); - + Comment = New Structure; OPI_Tools.AddField("POST_MESSAGE", Text, "String", Comment); - - OPI_Tools.AddField("TASKID", TaskID , String_ , Parameters); - OPI_Tools.AddField("ITEMID", CommentID, String_ , Parameters); - OPI_Tools.AddField("FIELDS", Comment , "Collection", Parameters); - + + OPI_Tools.AddField("TASKID", TaskID , String_ , Parameters); + OPI_Tools.AddField("ITEMID", CommentID, String_ , Parameters); + OPI_Tools.AddField("FIELDS", Comment , "Collection", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Delete comment // Delete task comment by ID -// +// // Note // Method at API documentation: [task.commentitem.delete](@dev.1c-bitrix.ru/rest_help/tasks/task/commentitem/delete.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // CommentID - Number, String - ID of comment to remove - comment // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeleteTaskComment(Val URL, Val TaskID, Val CommentID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "task.commentitem.delete"); - OPI_Tools.AddField("TASKID", TaskID , "String", Parameters); + OPI_Tools.AddField("TASKID", TaskID , "String", Parameters); OPI_Tools.AddField("ITEMID", CommentID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get results list // Gets results list for task -// +// // Note // Method at API documentation: [tasks.task.result.list](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_result.list.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetResultsList(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.result.list", Token); Return Response; - + EndFunction // Create result from comment // Create task result from comment -// +// // Note // Method at API documentation: [tasks.task.result.addFromComment](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_result_addFromComment.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // CommentID - Number, String - CommentID - comment // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function CreateResultFromComment(Val URL, Val CommentID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "tasks.task.result.addFromComment"); OPI_Tools.AddField("commentId", CommentID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Delete result from comment // Deletes task result, created from a comment -// +// // Note // Method at API documentation: [tasks.task.result.deleteFromComment](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_result_deleteFromComment.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // CommentID - Number, String - CommentID - comment // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeleteResultFromComment(Val URL, Val CommentID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "tasks.task.result.deleteFromComment"); OPI_Tools.AddField("commentId", CommentID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get comment structure // Get comment fields structure -// +// // Parameters: // Clear - Boolean - True > structure with empty valuse, False > field descriptions at values - empty -// +// // Returns: -// Structure of KeyAndValue - Fields structure +// Structure of KeyAndValue - Fields structure Function GetCommentStructure(Val Clear = False) Export - + // More // https://dev.1c-bitrix.ru/rest_help/tasks/task/commentitem/add.php - + OPI_TypeConversion.GetBoolean(Clear); - + FieldsStructure = New Structure; - FieldsStructure.Insert("AUTHOR_ID" , ""); - FieldsStructure.Insert("AUTHOR_NAME" , ""); - FieldsStructure.Insert("AUTHOR_EMAIL" , ""); - FieldsStructure.Insert("USE_SMILES" , "<(Y|N) - parse comments for emoticons or not>"); - FieldsStructure.Insert("POST_MESSAGE" , ""); + FieldsStructure.Insert("AUTHOR_ID" , ""); + FieldsStructure.Insert("AUTHOR_NAME" , ""); + FieldsStructure.Insert("AUTHOR_EMAIL" , ""); + FieldsStructure.Insert("USE_SMILES" , "<(Y|N) - parse comments for emoticons or not>"); + FieldsStructure.Insert("POST_MESSAGE" , ""); FieldsStructure.Insert("UF_FORUM_MESSAGE_DOC" , ""); - + If Clear Then For Each Field In FieldsStructure Do Field.Value = ""; EndDo; EndIf; - + //@skip-check constructor-function-return-section Return FieldsStructure; - + EndFunction #EndRegion @@ -1460,10 +1460,10 @@ EndFunction // Add kanban stage // Add new stage of kanban or My Plan -// +// // Note // Method at API documentation: [task.stages.add](@dev.1c-bitrix.ru/rest_help/tasks/task/kanban/task_stages_add.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Name - String - New stage name - title @@ -1472,7 +1472,7 @@ EndFunction // EntityID - String, Number - ID of kanban owner (group or user) - entityid // AsAdmin - Boolean - Allows you to add stages without checking permissions (for administrators) - admin // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function AddKanbanStage(Val URL @@ -1482,34 +1482,34 @@ Function AddKanbanStage(Val URL , Val EntityID = 0 , Val AsAdmin = False , Val Token = "") Export - + String_ = "String"; - + Parameters = NormalizeAuth(URL, Token, "task.stages.add"); - Fields = New Structure; - + Fields = New Structure; + MakeBoolean(AsAdmin); - - OPI_Tools.AddField("TITLE" , Name , String_, Fields); - OPI_Tools.AddField("COLOR" , Color , String_, Fields); + + OPI_Tools.AddField("TITLE" , Name , String_, Fields); + OPI_Tools.AddField("COLOR" , Color , String_, Fields); OPI_Tools.AddField("AFTER_ID" , PrevStageID , String_, Fields); - OPI_Tools.AddField("ENTITY_ID", EntityID , String_, Fields); - OPI_Tools.AddField("isAdmin" , AsAdmin, String_, Fields); - + OPI_Tools.AddField("ENTITY_ID", EntityID , String_, Fields); + OPI_Tools.AddField("isAdmin" , AsAdmin , String_, Fields); + Parameters.Insert("fields", Fields); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Change kanban stage // Changes the properties of the existing kanban or My plan stage -// +// // Note // Method at API documentation: [task.stages.update](@dev.1c-bitrix.ru/rest_help/tasks/task/kanban/task_stages_update.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Name - String - New stages name - title @@ -1518,7 +1518,7 @@ EndFunction // PrevStageID - String, Number - Stage ID, after which the selected stage should be inserted - prevstage // AsAdmin - Boolean - Allows you to add stages without checking permissions (for administrators) - admin // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function UpdateKanbansStage(Val URL @@ -1528,91 +1528,91 @@ Function UpdateKanbansStage(Val URL , Val PrevStageID = 0 , Val AsAdmin = False , Val Token = "") Export - + String_ = "String"; - + Parameters = NormalizeAuth(URL, Token, "task.stages.update"); - Fields = New Structure; - - OPI_Tools.AddField("TITLE" , Name , String_, Fields); - OPI_Tools.AddField("COLOR" , Color , String_, Fields); - OPI_Tools.AddField("AFTER_ID" , PrevStageID , String_, Fields); - OPI_Tools.AddField("isAdmin" , AsAdmin, "Boolean", Fields); - - OPI_Tools.AddField("id" , StageID, String_ , Parameters); + Fields = New Structure; + + OPI_Tools.AddField("TITLE" , Name , String_ , Fields); + OPI_Tools.AddField("COLOR" , Color , String_ , Fields); + OPI_Tools.AddField("AFTER_ID" , PrevStageID , String_ , Fields); + OPI_Tools.AddField("isAdmin" , AsAdmin , "Boolean", Fields); + + OPI_Tools.AddField("id" , StageID, String_ , Parameters); OPI_Tools.AddField("fields", Fields , "Collection", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // ID of the stage to be deleted // Removes a kanban (My Plan) stage, provided there are no tasks in it -// +// // Note // Method at API documentation: [task.stages.delete](@dev.1c-bitrix.ru/rest_help/tasks/task/kanban/task_stages_delete.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // StageID - String, Number - ID of stage to dele - stage // AsAdmin - Boolean - Allows you to add stages without checking permissions (for administrators) - admin // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeleteKanbanStage(Val URL, Val StageID, Val AsAdmin = False, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "task.stages.delete"); - + MakeBoolean(AsAdmin); - - OPI_Tools.AddField("id" , StageID , "String", Parameters); - OPI_Tools.AddField("isAdmin", AsAdmin, "String", Parameters); - + + OPI_Tools.AddField("id" , StageID , "String", Parameters); + OPI_Tools.AddField("isAdmin", AsAdmin , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get kanban stages // Get kanban (My Plan) stages info -// +// // Note // Method at API documentation: [task.stages.get](@dev.1c-bitrix.ru/rest_help/tasks/task/kanban/task_stages_get.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // EntityID - String, Number - ID of kanban owner (group or user) - entityid // AsAdmin - Boolean - Allows you to get stages without checking permissions (for administrators) - admin // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetKanbanStages(Val URL, Val EntityID = 0, Val AsAdmin = False, Val Token = "") Export - - EntityID = OPI_Tools.NumberToString(EntityID); + + EntityID = OPI_Tools.NumberToString(EntityID); Parameters = NormalizeAuth(URL, Token, "task.stages.get"); - + MakeBoolean(AsAdmin); - + OPI_Tools.AddField("entityId", EntityID , "String", Parameters); - OPI_Tools.AddField("isAdmin" , AsAdmin, "String", Parameters); - + OPI_Tools.AddField("isAdmin" , AsAdmin , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Move task to kanban stage // Move task to another kanban stage -// +// // Note // Method at API documentation: [task.stages.movetask](@dev.1c-bitrix.ru/rest_help/tasks/task/kanban/task_stages_movetask.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - String, Number - ID of task to move - task @@ -1620,7 +1620,7 @@ EndFunction // Prev - String, Number - ID of the task to put the selected one in front of (if After not filled) - before // After - String, Number - ID of the task to be followed by the selected (if Prev not filled) - after // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function MoveTaskToKanbanStage(Val URL @@ -1629,29 +1629,29 @@ Function MoveTaskToKanbanStage(Val URL , Val Prev = 0 , Val After = 0 , Val Token = "") Export - + String_ = "String"; - + Parameters = NormalizeAuth(URL, Token, "task.stages.movetask"); - - OPI_Tools.AddField("id" , TaskID, String_, Parameters); + + OPI_Tools.AddField("id" , TaskID , String_, Parameters); OPI_Tools.AddField("stageId", StageID, String_, Parameters); - + If ValueIsFilled(Prev) Then - + OPI_Tools.AddField("before", Prev, String_, Parameters); - + Else - + OPI_TypeConversion.GetLine(After); OPI_Tools.AddField("after", After, String_, Parameters); - + EndIf; - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction #EndRegion @@ -1660,10 +1660,10 @@ EndFunction // Add task time accounting // Adds information about the user's time spent to the task -// +// // Note // Method at API documentation: [task.elapseditem.add](@dev.1c-bitrix.ru/rest_help/tasks/task/elapseditem/add.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - String, Number - ID of task for time accounting - task @@ -1672,7 +1672,7 @@ EndFunction // Text - String - Comment text - text // SetupDate - String - Date the record was set - date // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function AddTaskTimeAccounting(Val URL @@ -1682,111 +1682,111 @@ Function AddTaskTimeAccounting(Val URL , Val Text = "" , Val SetupDate = "" , Val Token = "") Export - + String_ = "String"; - + Parameters = NormalizeAuth(URL, Token, "task.elapseditem.add"); - Fields = New Structure; - - OPI_Tools.AddField("SECONDS" , Time , String_ , Fields); - OPI_Tools.AddField("COMMENT_TEXT", Text , String_ , Fields); - OPI_Tools.AddField("USER_ID" , UserID, String_ , Fields); + Fields = New Structure; + + OPI_Tools.AddField("SECONDS" , Time , String_ , Fields); + OPI_Tools.AddField("COMMENT_TEXT", Text , String_ , Fields); + OPI_Tools.AddField("USER_ID" , UserID , String_ , Fields); OPI_Tools.AddField("CREATED_DATE", SetupDate , "DateISO", Fields); - - OPI_Tools.AddField("TASKID" , TaskID, String_ , Parameters); + + OPI_Tools.AddField("TASKID" , TaskID , String_ , Parameters); OPI_Tools.AddField("ARFIELDS", Fields , "Collection", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Delete task time accounting // Deletes record of time accounting -// +// // Note // Method at API documentation: [task.elapseditem.delete](@dev.1c-bitrix.ru/rest_help/tasks/task/elapseditem/delete.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - String, Number - ID of task for time accounting - task // RecordID - String, Number - Time record ID - record // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeleteTaskTimeAccounting(Val URL, Val TaskID, Val RecordID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "task.elapseditem.delete"); - - OPI_Tools.AddField("TASKID", TaskID, "String", Parameters); + + OPI_Tools.AddField("TASKID", TaskID , "String", Parameters); OPI_Tools.AddField("ITEMID", RecordID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get task time accounting list // Get list of time accounting records for task -// +// // Note // Method at API documentation: [task.elapseditem.getlist](@dev.1c-bitrix.ru/rest_help/tasks/task/elapseditem/getlist.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - String, Number - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetTaskTimeAccountingList(Val URL, Val TaskID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "task.elapseditem.getlist"); - + OPI_Tools.AddField("TASKID", TaskID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get task time accounting // Get time accounting record data -// +// // Note // Method at API documentation: [task.elapseditem.get](@dev.1c-bitrix.ru/rest_help/tasks/task/elapseditem/get.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - String, Number - Task ID - task // RecordID - String, Number - Time record ID - record // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetTaskTimeAccounting(Val URL, Val TaskID, Val RecordID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "task.elapseditem.get"); - - OPI_Tools.AddField("TASKID", TaskID, "String", Parameters); + + OPI_Tools.AddField("TASKID", TaskID , "String", Parameters); OPI_Tools.AddField("ITEMID", RecordID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Update task time accounting // Update time accounting record data -// +// // Note // Method at API documentation: [task.elapseditem.update](@dev.1c-bitrix.ru/rest_help/tasks/task/elapseditem/update.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - String, Number - Task ID - task @@ -1795,7 +1795,7 @@ EndFunction // Text - String - Comment text - text // SetupDate - String - Date the record was set - date // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function UpdateTaskTimeAccounting(Val URL @@ -1805,24 +1805,24 @@ Function UpdateTaskTimeAccounting(Val URL , Val Text = "" , Val SetupDate = "" , Val Token = "") Export - + String_ = "String"; - + Parameters = NormalizeAuth(URL, Token, "task.elapseditem.update"); - Fields = New Structure; - - OPI_Tools.AddField("SECONDS" , Time , String_ , Fields); - OPI_Tools.AddField("COMMENT_TEXT", Text , String_ , Fields); + Fields = New Structure; + + OPI_Tools.AddField("SECONDS" , Time , String_ , Fields); + OPI_Tools.AddField("COMMENT_TEXT", Text , String_ , Fields); OPI_Tools.AddField("CREATED_DATE", SetupDate , "DateISO", Fields); - - OPI_Tools.AddField("TASKID" , TaskID, String_ , Parameters); - OPI_Tools.AddField("ITEMID" , RecordID, String_ , Parameters); - OPI_Tools.AddField("ARFIELDS", Fields , "Collection", Parameters); - + + OPI_Tools.AddField("TASKID" , TaskID , String_ , Parameters); + OPI_Tools.AddField("ITEMID" , RecordID, String_ , Parameters); + OPI_Tools.AddField("ARFIELDS", Fields , "Collection", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction #EndRegion @@ -1831,142 +1831,142 @@ EndFunction // Get list of storages // Get list of available files storages -// +// // Note // Method at API documentation: [disk.storage.getlist](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_getlist.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetStoragesList(Val URL, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "disk.storage.getlist"); - Response = OPI_Tools.Post(URL, Parameters); - + Response = OPI_Tools.Post(URL, Parameters); + Return Response; EndFunction // Get storage for application data // Get information about storage with which the application can work to store its data -// +// // Note // Method at API documentation: [disk.storage.getforapp](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_getforapp.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetAppSotrage(Val URL, Val Token = "") Export - - Parameters = NormalizeAuth(URL, Token, "disk.storage.getforapp"); + + Parameters = NormalizeAuth(URL, Token, "disk.storage.getforapp"); Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get storage // Get information about storage -// +// // Note // Method at API documentation: [disk.storage.get](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_get.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // StorageID - String, Number - Storage ID - storageid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetStorage(Val URL, Val StorageID, Val Token = "") Export - + Response = FileManagement(URL, StorageID, "disk.storage.get", Token); Return Response; - + EndFunction // Rename storage // Change storage name (for app storage only, see. GetAppStorage) -// +// // Note // Method at API documentation: [disk.storage.rename](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_rename.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // StorageID - String, Number - Storage ID - storageid // Name - String - New storage name - title // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function RenameStorage(Val URL, Val StorageID, Val Name, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "disk.storage.rename"); - - OPI_Tools.AddField("id" , StorageID , "String", Parameters); - OPI_Tools.AddField("newName", Name, "String", Parameters); - + + OPI_Tools.AddField("id" , StorageID , "String", Parameters); + OPI_Tools.AddField("newName", Name , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get a list of child storage objects // Get a list of files and folders, located at the root of the storage -// +// // Note // Method at API documentation: [disk.storage.getchildren](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_getchildren.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // StorageID - String, Number - Storage ID - storageid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetStorageObjects(Val URL, Val StorageID, Val Token = "") Export - + Response = FileManagement(URL, StorageID, "disk.storage.getchildren", Token); Return Response; - + EndFunction // Create folder at the storage // Create new foldera at the storage -// +// // Note // Method at API documentation: [disk.storage.addfolder](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_addfolder.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // StorageID - String - Storage ID - storageid // Name - String - Folder name - title // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function CreateStorageFolder(Val URL, Val StorageID, Val Name, Val Token = "") Export - + OPI_TypeConversion.GetLine(Name); - + FolderStructure = New Structure("NAME", Name); - + Parameters = NormalizeAuth(URL, Token, "disk.storage.addfolder"); - - OPI_Tools.AddField("id" , StorageID , "String" , Parameters); + + OPI_Tools.AddField("id" , StorageID , "String" , Parameters); OPI_Tools.AddField("data", FolderStructure, "Collection", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - - Return Response; - + + Return Response; + EndFunction #EndRegion @@ -1975,279 +1975,279 @@ EndFunction // Get information about folder // Get folder information -// +// // Note // Method at API documentation: [disk.folder.get](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_get.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FolderID - String, Number - Folder identifier - folderid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetFolderInformation(Val URL, Val FolderID, Val Token = "") Export - + Response = FileManagement(URL, FolderID, "disk.folder.get", Token); Return Response; - + EndFunction // Create new subfolder // Create new folder inside another folder -// +// // Note // Method at API documentation: [disk.folder.addsubfolder](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_addsubfolder.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FolderID - String, Number - Parent folder identifier - folderid // Name - String - Name of new folder - title // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function CreateSubfolder(Val URL, Val FolderID, Val Name, Val Token = "") Export - + OPI_TypeConversion.GetLine(Name); - + FolderStructure = New Structure("NAME", Name); - + Parameters = NormalizeAuth(URL, Token, "disk.folder.addsubfolder"); - - OPI_Tools.AddField("id" , FolderID , "String" , Parameters); + + OPI_Tools.AddField("id" , FolderID , "String" , Parameters); OPI_Tools.AddField("data", FolderStructure, "Collection", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - - Return Response; - + + Return Response; + EndFunction // Copy folder // Copy one folder to another -// +// // Note // Method at API documentation: [disk.folder.copyto](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_copyto.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FolderID - String, Number - Folder identifier - folderid // DestinationID - String, Number - ID of target folder - tagetid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function MakeFolderCopy(Val URL, Val FolderID, Val DestinationID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "disk.folder.copyto"); - - OPI_Tools.AddField("id" , FolderID , "String", Parameters); + + OPI_Tools.AddField("id" , FolderID , "String", Parameters); OPI_Tools.AddField("targetFolderId", DestinationID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - - Return Response; - + + Return Response; + EndFunction // Move folder // Moves one folder inside another -// +// // Note // Method at API documentation: [disk.folder.moveto](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_moveto.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FolderID - String, Number - Folder identifier - folderid // DestinationID - String, Number - ID of target folder - tagetid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function MoveFolder(Val URL, Val FolderID, Val DestinationID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "disk.folder.moveto"); - - OPI_Tools.AddField("id" , FolderID , "String", Parameters); + + OPI_Tools.AddField("id" , FolderID , "String", Parameters); OPI_Tools.AddField("targetFolderId", DestinationID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - - Return Response; - + + Return Response; + EndFunction // Delete folder // Remove folder with subfolders -// +// // Note // Method at API documentation: [disk.folder.deletetree](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_deletetree.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FolderID - String, Number - ID of folder to be deleted - folderid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeleteFolder(Val URL, Val FolderID, Val Token = "") Export - + Response = FileManagement(URL, FolderID, "disk.folder.deletetree", Token); Return Response; - + EndFunction // Get external link for folder // Get external link to folder -// +// // Note // Method at API documentation: [disk.folder.getExternalLink](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_getexternallink.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FolderID - String, Number - Folder identifier - folderid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetFolderExternalLink(Val URL, Val FolderID, Val Token = "") Export - + Response = FileManagement(URL, FolderID, "disk.folder.getExternalLink", Token); Return Response; - + EndFunction // Get folder child elements // Get folder child elements -// +// // Note // Method at API documentation: [disk.folder.getchildren](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_getchildren.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FolderID - String, Number - Folder identifier - folderid // Filter - Structure of KeyAndValue - Items filter (see GetFolderFilterStructure) - filter // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetFolderItems(Val URL, Val FolderID, Val Filter = "", Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "disk.folder.getchildren"); - OPI_Tools.AddField("id" , FolderID, "String" , Parameters); - OPI_Tools.AddField("filter", Filter , "Collection", Parameters); - + OPI_Tools.AddField("id" , FolderID, "String" , Parameters); + OPI_Tools.AddField("filter", Filter , "Collection", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Mark folder as deleted // Move folder to recycle bin -// +// // Note // Method at API documentation: [disk.folder.markdeleted](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_markdeleted.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FolderID - String, Number - Folder identifier - folderid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function MarkFolderAsDeleted(Val URL, Val FolderID, Val Token = "") Export - + Response = FileManagement(URL, FolderID, "disk.folder.markdeleted", Token); Return Response; - + EndFunction // Restore folder // Resotre folder form recycle bin -// +// // Note // Method at API documentation: [disk.folder.restore](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_restore.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FolderID - String, Number - Folder identifier - folderid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function RestoreFolder(Val URL, Val FolderID, Val Token = "") Export - + Response = FileManagement(URL, FolderID, "disk.folder.restore", Token); - Return Response; - + Return Response; + EndFunction // Rename folder // Change folder name -// +// // Note // Method at API documentation: [disk.folder.rename](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_rename.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FolderID - String, Number - Folder identifier - folderid // Name - String - New folders name - title // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function RenameFolder(Val URL, Val FolderID, Val Name, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "disk.folder.rename"); - - OPI_Tools.AddField("id" , FolderID , "String", Parameters); - OPI_Tools.AddField("newName", Name, "String", Parameters); - + + OPI_Tools.AddField("id" , FolderID , "String", Parameters); + OPI_Tools.AddField("newName", Name , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - - Return Response; - + + Return Response; + EndFunction // Get fields structure for folder items filter // Returns filter structure for child folder items -// +// // Note // Method at API documentation: [disk.folder.getfields](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_getfields.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Clear - Boolean - True > structure with empty values, False > field types at values - empty // Token - String - Access token, when app auth method used - token -// +// // Returns: -// Structure of KeyAndValue - Fields structure +// Structure of KeyAndValue - Fields structure Function GetFolderFilterStructure(Val URL, Val Clear = False, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "disk.folder.getfields"); - Filter = New Structure; - + Filter = New Structure; + Response = OPI_Tools.Post(URL, Parameters); - Fields = Response["result"]; - + Fields = Response["result"]; + For Each Field In Fields Do - - Name = Field.Key; + + Name = Field.Key; Description = Field.Value; - + If Description["USE_IN_FILTER"] Then - - DataType = ?(Clear, "", Description["TYPE"]); + + DataType = ?(Clear, "", Description["TYPE"]); Filter.Insert(Name, DataType); - + EndIf; - + EndDo; - + Return Filter; - + EndFunction #EndRegion @@ -2256,18 +2256,18 @@ EndFunction // Upload file to a storage // Upload file to storage root -// +// // Note // Method at API documentation: [disk.storage.uploadfile](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_uploadfile.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Name - String - File name with extension - title -// File - String, BinaryData - File for upload - file +// File - String, BinaryData - File for upload - file // StorageID - String - Storage id - storageid // Rights - String - Rights array if required - rights // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function UploadFileToStorage(Val URL @@ -2276,118 +2276,118 @@ Function UploadFileToStorage(Val URL , Val StorageID , Val Rights = "" , Val Token = "") Export - + OPI_TypeConversion.GetLine(StorageID); OPI_TypeConversion.GetLine(Name); - + Method = "disk.storage.uploadfile"; - FileData = New Structure("NAME", Name); + FileData = New Structure("NAME", Name); FileContent = New Map(); FileContent.Insert(Name, File); - + Parameters = NormalizeAuth(URL, Token, Method); - OPI_Tools.AddField("data" , FileData, "Collection", Parameters); - OPI_Tools.AddField("rights", Rights , "Array" , Parameters); - OPI_Tools.AddField("id" , StorageID, "String" , Parameters); + OPI_Tools.AddField("data" , FileData , "Collection", Parameters); + OPI_Tools.AddField("rights", Rights , "Array" , Parameters); + OPI_Tools.AddField("id" , StorageID, "String" , Parameters); FileArray = NormalizeFiles(FileContent); - + If Not FileArray.Count() = 0 Then Parameters.Insert("fileContent", FileArray[0]); EndIf; - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Upload file to the folder // Upload local file to the folder -// +// // Note // Method at API documentation: [disk.folder.uploadfile](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_uploadfile.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Name - String - File name with extension - title -// File - String, BinaryData - File for upload - file +// File - String, BinaryData - File for upload - file // FolderID - String - Folder identifier - folderid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function UploadFileToFolder(Val URL, Val Name, Val File, Val FolderID, Val Token = "") Export OPI_TypeConversion.GetLine(Name); OPI_TypeConversion.GetBinaryData(File); - + Parameters = NormalizeAuth(URL, Token, "disk.folder.uploadFile"); OPI_Tools.AddField("id", FolderID, "String", Parameters); - + Response = OPI_Tools.Get(URL, Parameters); - Result = Response["result"]; - + Result = Response["result"]; + If ValueIsFilled(Result) Then - + FieldName = Result["field"]; UploadURL = Result["uploadUrl"]; - + If ValueIsFilled(FieldName) And ValueIsFilled(UploadURL) Then - + FieldName = TrimAll(FieldName); UploadURL = TrimAll(UploadURL); - FileName = FieldName + "|" + Name; - + FileName = FieldName + "|" + Name; + FileMapping = New Map; - FileMapping.Insert(FileName, File); - - Response = OPI_Tools.PostMultipart(UploadURL, , FileMapping, ""); - + FileMapping.Insert(FileName, File); + + Response = OPI_Tools.PostMultipart(UploadURL, , FileMapping, ""); + EndIf; - - EndIf; - - Return Response; - + + EndIf; + + Return Response; + EndFunction // Get information about file // Get information about file by ID -// +// // Note // Method at API documentation: [disk.file.get](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_get.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FileID - String, Number - File identifier - fileid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetFileInformation(Val URL, Val FileID, Val Token = "") Export - + Response = FileManagement(URL, FileID, "disk.file.get", Token); Return Response; - + EndFunction // Delete file // Delete file by ID -// +// // Note // Method at API documentation: [disk.file.delete](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_delete.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FileID - String, Number - ID of removing file - fileid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeleteFile(Val URL, Val FileID, Val Token = "") Export - + Response = FileManagement(URL, FileID, "disk.file.delete", Token); Return Response; @@ -2395,143 +2395,143 @@ EndFunction // Get external link for a file // Get external link to file -// +// // Note // Method at API documentation: [disk.file.getExternalLink](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_getexternallink.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FileID - String, Number - File identifier - fileid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetFileExternalLink(Val URL, Val FileID, Val Token = "") Export - + Response = FileManagement(URL, FileID, "disk.file.getExternalLink", Token); Return Response; - + EndFunction // Mark file as deleted // Move file to recycle bin -// +// // Note // Method at API documentation: [disk.file.markdeleted](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_markdeleted.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FileID - String, Number - File identifier - fileid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function MarkFileAsDeleted(Val URL, Val FileID, Val Token = "") Export - + Response = FileManagement(URL, FileID, "disk.file.markdeleted", Token); Return Response; - + EndFunction // Restore file // Restore file from recycle bin -// +// // Note // Method at API documentation: [disk.file.restore](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_restore.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FileID - String, Number - File identifier - fileid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function RestoreFile(Val URL, Val FileID, Val Token = "") Export - + Response = FileManagement(URL, FileID, "disk.file.restore", Token); Return Response; - + EndFunction // Copy file // Copy file from one destination to another -// +// // Note // Method at API documentation: [disk.file.copyto](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_copyto.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FileID - String, Number - Original file ID - fileid -// FolderID - String, Number - ID of copy destination folder - folderid +// FolderID - String, Number - ID of copy destination folder - folderid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function MakeCopyFile(Val URL, Val FileID, Val FolderID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "disk.file.copyto"); - - OPI_Tools.AddField("id" , FileID , "String", Parameters); + + OPI_Tools.AddField("id" , FileID , "String", Parameters); OPI_Tools.AddField("targetFolderId", FolderID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - - Return Response; - + + Return Response; + EndFunction // Move file // Move file from one destination to another -// +// // Note // Method at API documentation: [disk.file.moveto](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_moveto.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FileID - String, Number - File ID - fileid -// FolderID - String, Number - ID of new destination folder - folderid +// FolderID - String, Number - ID of new destination folder - folderid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function MoveFileToFolder(Val URL, Val FileID, Val FolderID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "disk.file.moveto"); - - OPI_Tools.AddField("id" , FileID , "String", Parameters); + + OPI_Tools.AddField("id" , FileID , "String", Parameters); OPI_Tools.AddField("targetFolderId", FolderID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - - Return Response; - + + Return Response; + EndFunction // Rename file // Changes the name of an existing file -// +// // Note // Method at API documentation: [disk.file.rename](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_rename.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FileID - String, Number - File identifier - fileid // Name - String - New folders name - title // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function RenameFile(Val URL, Val FileID, Val Name, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "disk.file.rename"); - - OPI_Tools.AddField("id" , FileID , "String", Parameters); - OPI_Tools.AddField("newName", Name, "String", Parameters); - + + OPI_Tools.AddField("id" , FileID , "String", Parameters); + OPI_Tools.AddField("newName", Name , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - - Return Response; - + + Return Response; + EndFunction #EndRegion @@ -2540,109 +2540,109 @@ EndFunction // Create chat // Creates a new chat based on the field structure -// +// // Note // Method at API documentation: [im.chat.add](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12093) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url -// ChatStructure - Structure of KeyAndValue - Chat fields structure. See GetChatStructure - fields +// ChatStructure - Structure of KeyAndValue - Chat fields structure. See GetChatStructure - fields // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function CreateChat(Val URL, Val ChatStructure, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.chat.add"); - + For Each Element In ChatStructure Do Parameters.Insert(Element.Key, Element.Value); EndDo; - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get chats users // Gets the list of chat users by ID -// +// // Note // Method at API documentation: [im.chat.user.list](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12095) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID - chat // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetChatUsers(Val URL, Val ChatID, Val Token = "") Export - - Response = ChatManagment(URL, ChatID, "im.chat.user.list", Token); + + Response = ChatManagment(URL, ChatID, "im.chat.user.list", Token); Return Response; - + EndFunction // Leave chat // Removes the current user from the chat room -// +// // Note // Method at API documentation: [im.chat.leave](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12101) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID - chat // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function LeaveChat(Val URL, Val ChatID, Val Token = "") Export - - Response = ChatManagment(URL, ChatID, "im.chat.leave", Token); + + Response = ChatManagment(URL, ChatID, "im.chat.leave", Token); Return Response; - + EndFunction // Get users // Get users information for dialog -// +// // Note // Method at API documentation: [im.user.list.get ](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=11493) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // UserIDs - Array of String, Number - Usesr ID or array of users IDs - users // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetUsers(Val URL, Val UserIDs, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.user.list.get"); - + OPI_Tools.AddField("ID", UserIDs, "Array", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Add users to chat // Adds users to the chat by ID array -// +// // Note // Method at API documentation: [im.chat.user.add](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12097) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID - chat // UserIDs - Array of string, number - New members IDs - users // HideHistory - Boolean - Hide old messages from new members - hide // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function AddUsersToChat(Val URL @@ -2650,213 +2650,213 @@ Function AddUsersToChat(Val URL , Val UserIDs , Val HideHistory = False , Val Token = "") Export - + MakeBoolean(HideHistory); - + Parameters = NormalizeAuth(URL, Token, "im.chat.user.add"); - - OPI_Tools.AddField("CHAT_ID" , ChatID , "String" , Parameters); - OPI_Tools.AddField("USERS" , UserIDs, "Collection", Parameters); - OPI_Tools.AddField("HIDE_HISTORY", HideHistory , "String" , Parameters); - + + OPI_Tools.AddField("CHAT_ID" , ChatID , "String" , Parameters); + OPI_Tools.AddField("USERS" , UserIDs , "Collection", Parameters); + OPI_Tools.AddField("HIDE_HISTORY", HideHistory , "String" , Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Delete user from chat // Deletes user from chat -// +// // Note // Method at API documentation: [im.chat.user.delete](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12099) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID - chat // UserID - String, Number - User ID - user // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeleteUserFromChat(Val URL, Val ChatID, Val UserID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.chat.user.delete"); - + OPI_Tools.AddField("CHAT_ID", ChatID , "String", Parameters); - OPI_Tools.AddField("USER_ID", UserID, "String", Parameters); - + OPI_Tools.AddField("USER_ID", UserID , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Change chat title // Change text of chat title -// +// // Note // Method at API documentation: [im.chat.updateTitle](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12105) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID - chat // Title - String - New title - title // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function ChangeChatTitle(Val URL, Val ChatID, Val Title, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.chat.updateTitle"); - + OPI_Tools.AddField("CHAT_ID", ChatID , "String", Parameters); - OPI_Tools.AddField("TITLE" , Title, "String", Parameters); - + OPI_Tools.AddField("TITLE" , Title , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Change chat color // Chat chat color for mobile app -// +// // Note // Method at API documentation: [im.chat.updateTitle](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12105) // Available colors: RED, GREEN, MINT, LIGHT_BLUE, DARK_BLUE, PURPLE, AQUA, PINK, LIME, BROWN, AZURE, KHAKI, SAND, MARENGO, GRAY, GRAPHITE -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID - chat // Color - String - New chat color - color // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function ChangeChatColor(Val URL, Val ChatID, Val Color, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.chat.updateColor"); - + OPI_Tools.AddField("CHAT_ID", ChatID, "String", Parameters); - OPI_Tools.AddField("COLOR" , Color , "String", Parameters); - + OPI_Tools.AddField("COLOR" , Color , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Change chat picture // Setup new chat picture -// +// // Note // Method at API documentation: [im.chat.updateAvatar](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12109) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID - chat // Image - String, BinaryData - Picture data - picture // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function ChangeChatPicture(Val URL, Val ChatID, Val Image, Val Token = "") Export - + OPI_TypeConversion.GetBinaryData(Image); - - Image = Base64String(Image); + + Image = Base64String(Image); Parameters = NormalizeAuth(URL, Token, "im.chat.updateAvatar"); - + OPI_Tools.AddField("CHAT_ID", ChatID , "String", Parameters); - OPI_Tools.AddField("AVATAR" , Image, "String", Parameters); - + OPI_Tools.AddField("AVATAR" , Image , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Change chat owner // Change chat owner -// +// // Note // Method at API documentation: [im.chat.setOwner](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12111) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID - chat // UserID - String, Number - User ID - user // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function ChangeChatOwner(Val URL, Val ChatID, Val UserID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.chat.setOwner"); - + OPI_Tools.AddField("CHAT_ID", ChatID , "String", Parameters); - OPI_Tools.AddField("USER_ID", UserID, "String", Parameters); - + OPI_Tools.AddField("USER_ID", UserID , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Disable chat notifications // Disable chat notifications -// +// // Note // Method at API documentation: [im.chat.mute](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=11473) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID - chat // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DisableChatNotifications(Val URL, Val ChatID, Val Token = "") Export - + Response = ChatNotificationsSwitch(URL, ChatID, True, Token); Return Response; - + EndFunction // Enable chat notifications // Enable chat notifications -// +// // Note // Method at API documentation: [im.chat.mute](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=11473) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID - chat // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function EnableChatNotifications(Val URL, Val ChatID, Val Token = "") Export - + Response = ChatNotificationsSwitch(URL, ChatID, False, Token); Return Response; - + EndFunction // Get chat messages list // Gets a list of 20 chat or dialog messages, depending on the FirstID and LastID specified -// +// // Note // Method at API documentation: [im.dialog.messages.get](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=11479) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID (as chatXXX) or User ID (as XXX) - chat // LastID - String, Number - Id of last message - last // FirstID - String, Number - ID of first message - first // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetChatMessagesList(Val URL @@ -2864,209 +2864,209 @@ Function GetChatMessagesList(Val URL , Val LastID = "" , Val FirstID = "" , Val Token = "") Export - + String_ = "String"; - + OPI_TypeConversion.GetLine(LastID); OPI_TypeConversion.GetLine(FirstID); - + Parameters = NormalizeAuth(URL, Token, "im.dialog.messages.get"); - - OPI_Tools.AddField("DIALOG_ID", ChatID , String_, Parameters); - OPI_Tools.AddField("LAST_ID" , LastID, String_, Parameters); + + OPI_Tools.AddField("DIALOG_ID", ChatID , String_, Parameters); + OPI_Tools.AddField("LAST_ID" , LastID , String_, Parameters); OPI_Tools.AddField("FIRST_ID" , FirstID , String_, Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get dialog // Get chat data by ID -// +// // Note // Method at API documentation: [im.dialog.get](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12886) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID (as chatXXX) or User ID (as XXX) - chat // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetDialog(Val URL, Val ChatID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.dialog.get"); - + OPI_Tools.AddField("DIALOG_ID", ChatID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get chat members list // Get chat members list -// +// // Note // Method at API documentation: [im.dialog.users.list](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=23800) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID (as chatXXX) or User ID (as XXX) - chat // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetChatMembersList(Val URL, Val ChatID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.dialog.users.list"); - + OPI_Tools.AddField("DIALOG_ID", ChatID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Send write notification // Send Writing... status to dialog... -// +// // Note // Method at API documentation: [im.dialog.writing](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=23802) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID (as chatXXX) or User ID (as XXX) - chat // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function SendWritingNotification(Val URL, Val ChatID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.dialog.writing"); - + OPI_Tools.AddField("DIALOG_ID", ChatID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get user status // Gets the status (online) of the current user -// +// // Note // Method at API documentation: [im.user.status.get](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=11497) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetUserStatus(Val URL, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.user.status.get"); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Set user status // Sets the status (online) of the current user -// +// // Note // Method at API documentation: [im.user.status.set](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=11499) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Status - String, Number - Status value: online, dnd, away - status // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function SetUserStatus(Val URL, Val Status, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.user.status.set"); - + OPI_Tools.AddField("STATUS", Status, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Read all // Mark all message as readed -// +// // Note // Method at API documentation: [im.dialog.read.all](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=23804) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function ReadAll(Val URL, Val Token = "") Export - - Parameters = NormalizeAuth(URL, Token, "im.dialog.read.all"); - Response = OPI_Tools.Post(URL, Parameters); - + + Parameters = NormalizeAuth(URL, Token, "im.dialog.read.all"); + Response = OPI_Tools.Post(URL, Parameters); + Return Response; - + EndFunction // Get chat files folder // Get information about folder for chat files -// +// // Note // Method at API documentation: [im.disk.folder.get](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=11483) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID - chat // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetChatFilesFolder(Val URL, Val ChatID, Val Token = "") Export - - Response = ChatManagment(URL, ChatID, "im.disk.folder.get", Token); + + Response = ChatManagment(URL, ChatID, "im.disk.folder.get", Token); Return Response; - + EndFunction // Get chats structure // Get chat fields structure -// +// // Parameters: // Clear - Boolean - True > structure with empty values, False > field types at values - empty -// +// // Returns: -// Structure of KeyAndValue - Fields structure +// Structure of KeyAndValue - Fields structure Function GetChatStructure(Val Clear = False) Export - + OPI_TypeConversion.GetBoolean(Clear); - + ChatStructure = New Structure; - ChatStructure.Insert("TYPE" , ""); - ChatStructure.Insert("TITLE" , ""); + ChatStructure.Insert("TYPE" , ""); + ChatStructure.Insert("TITLE" , ""); ChatStructure.Insert("DESCRIPTION", ""); - ChatStructure.Insert("COLOR" , ""); - ChatStructure.Insert("MESSAGE" , ""); - ChatStructure.Insert("USERS" , ""); - ChatStructure.Insert("AVATAR" , ""); - ChatStructure.Insert("OWNER_ID" , ""); - + ChatStructure.Insert("COLOR" , ""); + ChatStructure.Insert("MESSAGE" , ""); + ChatStructure.Insert("USERS" , ""); + ChatStructure.Insert("AVATAR" , ""); + ChatStructure.Insert("OWNER_ID" , ""); + If Clear Then For Each Element In ChatStructure Do Element.Value = ""; @@ -3075,7 +3075,7 @@ Function GetChatStructure(Val Clear = False) Export //@skip-check constructor-function-return-section Return ChatStructure; - + EndFunction #EndRegion @@ -3084,253 +3084,253 @@ EndFunction // Send message // Send message to dialog -// +// // Note // Method at API documentation: [im.message.add](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12115) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID (as chatXXX) or User ID (as XXX) - chat // Text - String - Message text - text // Attachments - Array of Structure - Array of attachments - blocks // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function SendMessage(Val URL, Val ChatID, Val Text, Val Attachments = "", Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.message.add"); - - OPI_Tools.AddField("DIALOG_ID", ChatID , "String", Parameters); - OPI_Tools.AddField("MESSAGE" , Text , "String", Parameters); - OPI_Tools.AddField("ATTACH" , Attachments, "Array", Parameters); - + + OPI_Tools.AddField("DIALOG_ID", ChatID , "String", Parameters); + OPI_Tools.AddField("MESSAGE" , Text , "String", Parameters); + OPI_Tools.AddField("ATTACH" , Attachments, "Array" , Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Edit message // Edit dialog message content -// +// // Note // Method at API documentation: [im.message.update](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12117) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // MessageID - String, Number - ID of the message to be edited - message // Text - String - New message text - text // Attachments - Array of Structure - New blocks array - blocks // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function EditMessage(Val URL, Val MessageID, Val Text = "", Val Attachments = "", Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.message.update"); - - OPI_Tools.AddField("MESSAGE_ID", MessageID, "String", Parameters); - OPI_Tools.AddField("MESSAGE" , Text , "String", Parameters); - OPI_Tools.AddField("ATTACH" , Attachments , "Array", Parameters); - + + OPI_Tools.AddField("MESSAGE_ID", MessageID , "String", Parameters); + OPI_Tools.AddField("MESSAGE" , Text , "String", Parameters); + OPI_Tools.AddField("ATTACH" , Attachments , "Array" , Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Set message reaction // Set or remove reaction mark on the message -// +// // Note // Method at API documentation: [im.message.like](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12121) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // MessageID - String, Number - Message ID - message // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function SetMessageReaction(Val URL, Val MessageID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.message.like"); - + OPI_Tools.AddField("MESSAGE_ID", MessageID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Delete message // Deletes a dialog message -// +// // Note // Method at API documentation: [im.message.delete](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12119) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // MessageID - String, Number - ID of the message to be deleted - message // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeleteMessage(Val URL, Val MessageID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.message.delete"); - + OPI_Tools.AddField("MESSAGE_ID", MessageID , "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // SendFile // Send disk file to chat -// +// // Note // Method at API documentation: [im.disk.file.commit](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=11485) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID - chat // FileID - String, Number - File ID from UploadFileToFolder method - fileid // Description - String - File description - description // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function SendFile(Val URL, Val ChatID, Val FileID, Val Description = "", Val Token = "") Export - + String_ = "String"; - + Parameters = NormalizeAuth(URL, Token, "im.disk.file.commit"); - - OPI_Tools.AddField("CHAT_ID" , ChatID , String_, Parameters); - OPI_Tools.AddField("UPLOAD_ID", FileID , String_, Parameters); - OPI_Tools.AddField("MESSAGE" , Description, String_, Parameters); - + + OPI_Tools.AddField("CHAT_ID" , ChatID , String_, Parameters); + OPI_Tools.AddField("UPLOAD_ID", FileID , String_, Parameters); + OPI_Tools.AddField("MESSAGE" , Description, String_, Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Mark message as readed // Mark current and all previous messages as readed -// +// // Note // Method at API documentation: [im.dialog.read](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12053) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID (as chatXXX) or User ID (as XXX) - chat // MessageID - String, Number - Id of last readed message - message // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function MarkMessageAsReaded(Val URL, Val ChatID, Val MessageID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.dialog.read"); - - OPI_Tools.AddField("DIALOG_ID" , ChatID , "String", Parameters); + + OPI_Tools.AddField("DIALOG_ID" , ChatID , "String", Parameters); OPI_Tools.AddField("MESSAGE_ID", MessageID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Mark message as unreaded // Mark current and all messages after as unreaded -// +// // Note // Method at API documentation: [im.dialog.unread](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12055) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID (as chatXXX) or User ID (as XXX) - chat // MessageID - String, Number - ID of last unreaded message - message // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function MarkMessageAsUnreaded(Val URL, Val ChatID, Val MessageID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.dialog.unread"); - - OPI_Tools.AddField("DIALOG_ID" , ChatID , "String", Parameters); + + OPI_Tools.AddField("DIALOG_ID" , ChatID , "String", Parameters); OPI_Tools.AddField("MESSAGE_ID", MessageID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction - + // Get picture block // Make picture block for SendMessage method -// +// // Note // Blocks at API documentation: [Link](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&CHAPTER_ID=07867) -// +// // Parameters: // Name - String - Picture name - title // URL - String - URL of sending picture - url -// +// // Returns: // Structure - PictureBlock Function GetPictureBlock(Val Name, Val URL) Export - PictureStructure = New Structure; + PictureStructure = New Structure; OPI_Tools.AddField("NAME", Name, "String", PictureStructure); OPI_Tools.AddField("LINK", URL , "String", PictureStructure); - + //@skip-check constructor-function-return-section Return New Structure("IMAGE", PictureStructure); - + EndFunction // Get file block // Make file block for SendMessage method -// +// // Note // Blocks at API documentation: [Link](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&CHAPTER_ID=07867) -// +// // Parameters: // Name - String - Picture name - title // URL - String - File URL - url -// +// // Returns: // Structure - FileBlock Function GetFileBlock(Val Name, Val URL) Export - PictureStructure = New Structure; + PictureStructure = New Structure; OPI_Tools.AddField("NAME", Name, "String", PictureStructure); OPI_Tools.AddField("LINK", URL , "String", PictureStructure); - + //@skip-check constructor-function-return-section Return New Structure("FILE", PictureStructure); - + EndFunction - + #EndRegion #Region NotificationsManagment // Create personal notification // Creates a personal notification to the user -// +// // Note // Method at API documentation: [im.notify.personal.add](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=12129) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // UserID - String, Number - User ID for sending the notification - user @@ -3338,7 +3338,7 @@ EndFunction // Tag - String - Uniqueness Tag. Id already exist - another notif. will be deleted - tag // Attachments - Array of Structure - Array of attachments - blocks // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function CreatePersonalNotification(Val URL @@ -3347,26 +3347,26 @@ Function CreatePersonalNotification(Val URL , Val Tag , Val Attachments = "" , Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.notify.personal.add"); - - OPI_Tools.AddField("USER_ID", UserID, "String", Parameters); - OPI_Tools.AddField("MESSAGE", Text , "String", Parameters); - OPI_Tools.AddField("TAG" , Tag , "String", Parameters); - OPI_Tools.AddField("ATTACH" , Attachments , "Array", Parameters); - + + OPI_Tools.AddField("USER_ID", UserID , "String", Parameters); + OPI_Tools.AddField("MESSAGE", Text , "String", Parameters); + OPI_Tools.AddField("TAG" , Tag , "String", Parameters); + OPI_Tools.AddField("ATTACH" , Attachments , "Array" , Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Create system notification // Creates a system notification to the user -// +// // Note // Method at API documentation: [im.notify.system.add](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=12131) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // UserID - String, Number - User ID for sending the notification - user @@ -3374,7 +3374,7 @@ EndFunction // Tag - String - Uniqueness Tag. Id already exist - another notif. will be deleted - tag // Attachments - Array of Structure - Array of attachments - blocks // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function CreateSystemNotification(Val URL @@ -3383,43 +3383,43 @@ Function CreateSystemNotification(Val URL , Val Tag , Val Attachments = "" , Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.notify.system.add"); - - OPI_Tools.AddField("USER_ID", UserID, "String", Parameters); - OPI_Tools.AddField("MESSAGE", Text , "String", Parameters); - OPI_Tools.AddField("TAG" , Tag , "String", Parameters); - OPI_Tools.AddField("ATTACH" , Attachments , "Array", Parameters); - + + OPI_Tools.AddField("USER_ID", UserID , "String", Parameters); + OPI_Tools.AddField("MESSAGE", Text , "String", Parameters); + OPI_Tools.AddField("TAG" , Tag , "String", Parameters); + OPI_Tools.AddField("ATTACH" , Attachments , "Array" , Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Delete notification // Delete notification by ID -// +// // Note // Method at API documentation: [im.notify.delete](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=12133) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // NotificationID - String, Number - Notification ID - notif // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeleteNotification(Val URL, Val NotificationID, Val Token = "") Export Parameters = NormalizeAuth(URL, Token, "im.notify.delete"); - + OPI_Tools.AddField("ID", NotificationID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction #EndRegion @@ -3432,137 +3432,137 @@ Procedure MakeBoolean(Value) OPI_TypeConversion.GetBoolean(Value); Value = ?(Value, "Y", "N"); - + EndProcedure Function NormalizeAuth(URL, Val Token, Val Method = "") - + OPI_TypeConversion.GetLine(URL); OPI_TypeConversion.GetLine(Token); - - Parameters = New Structure; + + Parameters = New Structure; IsTokenAuth = ValueIsFilled(Token); - + UncorrectItems = New Array; UncorrectItems.Add("https://"); UncorrectItems.Add("http://"); UncorrectItems.Add("www."); - + For Each DeletedElement In UncorrectItems Do URL = StrReplace(URL, DeletedElement, ""); EndDo; - + URL = TrimAll(URL); - + If Not StrEndsWith(URL, "/") Then URL = URL + "/"; EndIf; - + If IsTokenAuth Then - + If Not StrEndsWith(URL, "rest/") Then URL = URL + "rest/"; EndIf; - + Parameters.Insert("auth", Token); - + EndIf; - + If ValueIsFilled(Method) Then URL = URL + TrimAll(Method); EndIf; - + Return Parameters; EndFunction Function NormalizeFiles(Val Files) - + NormalizedFiles = New Array; If TypeOf(Files) = Type("Map") Then - - For Each File In Files Do - + + For Each File In Files Do + CurrentArray = New Array; - CurrentFile = File.Value; - CurrentName = File.Key; - + CurrentFile = File.Value; + CurrentName = File.Key; + OPI_TypeConversion.GetBinaryData(CurrentFile); OPI_TypeConversion.GetLine(CurrentName); - + CurrentArray.Add(CurrentName); CurrentArray.Add(Base64String(CurrentFile)); - + NormalizedFiles.Add(CurrentArray); - + EndDo; - + EndIf; - + Return NormalizedFiles; - + EndFunction Function ManageTask(Val URL, Val TaskID, Val Method, Val Token = "") - + Parameters = NormalizeAuth(URL, Token, Method); OPI_Tools.AddField("taskId", TaskID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction Function FileManagement(Val URL, Val FileID, Val Method, Val Token = "") Parameters = NormalizeAuth(URL, Token, Method); OPI_Tools.AddField("id", FileID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - - Return Response; - + + Return Response; + EndFunction -Function ChecklistElementManagment(Val URL, Val TaskID, Val ElementID, Val Method, Val Token = "") - +Function ChecklistElementManagment(Val URL, Val TaskID, Val ElementID, Val Method, Val Token = "") + Parameters = NormalizeAuth(URL, Token, Method); - - OPI_Tools.AddField("TASKID", TaskID , "String", Parameters); + + OPI_Tools.AddField("TASKID", TaskID , "String", Parameters); OPI_Tools.AddField("ITEMID", ElementID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction Function ChatManagment(Val URL, Val ChatID, Val Method, Val Token = "") Parameters = NormalizeAuth(URL, Token, Method); OPI_Tools.AddField("CHAT_ID", ChatID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - - Return Response; - + + Return Response; + EndFunction Function ChatNotificationsSwitch(Val URL, Val ChatID, Val Off, Val Token = "") MakeBoolean(Off); - + Parameters = NormalizeAuth(URL, Token, "im.chat.mute"); - + OPI_Tools.AddField("CHAT_ID", ChatID , "String", Parameters); - OPI_Tools.AddField("MUTE" , Off, "String", Parameters); - + OPI_Tools.AddField("MUTE" , Off , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - - Return Response; - + + Return Response; + EndFunction #EndRegion diff --git a/src/en/OInt/core/Modules/OPI_Dropbox.os b/src/en/OInt/core/Modules/OPI_Dropbox.os index 9d5cc6983a..e243e28259 100644 --- a/src/en/OInt/core/Modules/OPI_Dropbox.os +++ b/src/en/OInt/core/Modules/OPI_Dropbox.os @@ -42,128 +42,128 @@ // Get authorization link // Generates an authorization link for browser transition -// +// // Parameters: // AppKey - String - Application key - appkey -// +// // Returns: // String - URL for browser transition Function GetAuthorizationLink(Val AppKey) Export - + OPI_TypeConversion.GetLine(AppKey); - Return "https://www.dropbox.com/oauth2/authorize?client_id=" - + AppKey + Return "https://www.dropbox.com/oauth2/authorize?client_id=" + + AppKey + "&response_type=code&token_access_type=offline"; - + EndFunction // Get token // Gets token based on the code from the GetAuthorizationLink page -// +// // Parameters: // AppKey - String - Application key - appkey // AppSecret - String - Application secret - appsecret // Code - String - Code from the authorization page - code -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function GetToken(Val AppKey, Val AppSecret, Val Code) Export - - URL = "https://api.dropbox.com/oauth2/token"; + + URL = "https://api.dropbox.com/oauth2/token"; DataType = "application/x-www-form-urlencoded; charset=utf-8"; - - Parameters = New Structure; - OPI_Tools.AddField("code" , Code , "String", Parameters); + + Parameters = New Structure; + OPI_Tools.AddField("code" , Code , "String", Parameters); OPI_Tools.AddField("grant_type", "authorization_code", "String", Parameters); - + URLStructure = OPI_Tools.SplitURL(URL); - Server = URLStructure["Server"]; - Address = URLStructure["Address"]; - - Request = OPI_Tools.CreateRequest(Address, , DataType); + Server = URLStructure["Server"]; + Address = URLStructure["Address"]; + + Request = OPI_Tools.CreateRequest(Address, , DataType); Connection = OPI_Tools.CreateConnection(Server, AppKey, AppSecret); ParameterString = OPI_Tools.RequestParametersToString(Parameters); - Data = Right(ParameterString, StrLen(ParameterString) - 1); + Data = Right(ParameterString, StrLen(ParameterString) - 1); Request.SetBodyFromString(Data); - + Response = Connection.CallHTTPMethod("POST", Request); OPI_Tools.ProcessResponse(Response); - + Return Response; - + EndFunction // Refresh token // Gets a new token based on the refresh token -// +// // Parameters: // AppKey - String - Application key - appkey // AppSecret - String - Application secret - appsecret // RefreshToken - String - Refresh token - refresh -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function RefreshToken(Val AppKey, Val AppSecret, Val RefreshToken) Export - + String_ = "String"; - URL = "https://api.dropbox.com/oauth2/token"; - + URL = "https://api.dropbox.com/oauth2/token"; + Parameters = New Structure; - OPI_Tools.AddField("refresh_token", RefreshToken , String_, Parameters); - OPI_Tools.AddField("grant_type" , "refresh_token" , String_, Parameters); - OPI_Tools.AddField("client_id" , AppKey , String_, Parameters); - OPI_Tools.AddField("client_secret", AppSecret, String_, Parameters); - + OPI_Tools.AddField("refresh_token", RefreshToken , String_, Parameters); + OPI_Tools.AddField("grant_type" , "refresh_token" , String_, Parameters); + OPI_Tools.AddField("client_id" , AppKey , String_, Parameters); + OPI_Tools.AddField("client_secret", AppSecret , String_, Parameters); + Response = OPI_Tools.Post(URL, Parameters, , False); - + Return Response; - + EndFunction // Get account information // Gets account information -// +// // Parameters: // Token - String - Token - token // Account - String - Account ID. Current token account if not filled - account -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function GetAccountInformation(Val Token, Val Account = "") Export - + If ValueIsFilled(Account) Then Result = GetAccount(Token, Account); Else Result = GetOwnAccount(Token); EndIf; - + Return Result; - + EndFunction // Get space usage data // Gets information on the amount of used disk space -// +// // Parameters: -// Token - String - Token - token -// +// Token - String - Token - token +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function GetSpaceUsageData(Val Token) Export - - URL = "https://api.dropboxapi.com/2/users/get_space_usage"; + + URL = "https://api.dropboxapi.com/2/users/get_space_usage"; Headers = GetRequestHeaders(Token); - + Response = OPI_Tools.PostBinary(URL , GetBinaryDataFromString("null") , Headers - , - , "text/plain; charset=dropbox-cors-hack"); - + , + , "text/plain; charset=dropbox-cors-hack"); + Return Response; - + EndFunction #EndRegion @@ -172,344 +172,344 @@ EndFunction // Get object information // Gets information about a file or directory -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the object - path -// Detailed - Boolean - Add information fields for mediafiles - detail -// +// Detailed - Boolean - Add information fields for mediafiles - detail +// // Returns: -// Map Of KeyAndValue - serialized JSON response from Dropbox +// Map Of KeyAndValue - serialized JSON response from Dropbox Function GetObjectInformation(Val Token, Val Path, Val Detailed = False) Export - - URL = "https://api.dropboxapi.com/2/files/get_metadata"; - + + URL = "https://api.dropboxapi.com/2/files/get_metadata"; + Parameters = New Structure; - OPI_Tools.AddField("path" , Path , "String", Parameters); + OPI_Tools.AddField("path" , Path , "String" , Parameters); OPI_Tools.AddField("include_media_info", Detailed, "Boolean", Parameters); - - Headers = GetRequestHeaders(Token); + + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Get list of folder files // Gets the list of the first files in the directory or continues getting the next ones when the cursor is specified -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the directory. Optional if the cursor is specified - path // Detailed - Boolean - Add information fields for mediafiles - detail // Cursor - String - Cursor from the previous request to get the next set of files - cursor -// +// // Returns: // HTTPResponse - Get list of folder files Function GetListOfFolderFiles(Val Token, Val Path = "", Val Detailed = False, Val Cursor = "") Export - + If Not ValueIsFilled(Cursor) Then - + URL = "https://api.dropboxapi.com/2/files/list_folder"; - + Parameters = New Structure; - OPI_Tools.AddField("path" , Path , "String", Parameters); + OPI_Tools.AddField("path" , Path , "String" , Parameters); OPI_Tools.AddField("include_media_info", Detailed , "Boolean", Parameters); - + Else - + URL = "https://api.dropboxapi.com/2/files/list_folder/continue"; - + Parameters = New Structure; - OPI_Tools.AddField("cursor", Cursor, "String", Parameters); - + OPI_Tools.AddField("cursor", Cursor, "String", Parameters); + EndIf; - + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Get preview // Gets PDF or HTML preview of the object (for documents only) -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the object - path -// +// // Returns: -// BinaryData - document preview +// BinaryData - document preview Function GetPreview(Val Token, Val Path) Export - - URL = "https://content.dropboxapi.com/2/files/get_preview"; + + URL = "https://content.dropboxapi.com/2/files/get_preview"; Response = ProcessObject(Token, URL, Path, True); - + Return Response; - + EndFunction // Upload file // Uploads a file to the cloud drive -// +// // Parameters: // Token - String - Token - token // File - String, BinaryData - Data file for upload - file // Path - String - Save path on Dropbox - path // Overwrite - Boolean - Overwrite file in case of path conflicts - overwrite -// +// // Returns: -// Map Of KeyAndValue - serialized JSON response from Dropbox +// Map Of KeyAndValue - serialized JSON response from Dropbox Function UploadFile(Val Token, Val File, Val Path, Val Overwrite = False) Export - + OPI_TypeConversion.GetBinaryData(File); OPI_TypeConversion.GetBoolean(Overwrite); OPI_TypeConversion.GetLine(Path); - - Mode = ?(Overwrite, "overwrite", "add"); - Size = File.Size(); + + Mode = ?(Overwrite, "overwrite", "add"); + Size = File.Size(); Border = 100000000; - + If Size > Border Then Response = UploadLargeFile(Token, File, Path, Mode); Else Response = UploadSmallFile(Token, File, Path, Mode); EndIf; - + Return Response; - + EndFunction // Upload file by URL -// Uploads a file to the cloud drive by fetching it from the specified URL -// +// Uploads a file to the cloud drive by fetching it from the specified URL +// // Parameters: // Token - String - Token - token // FileURL - String - URL source of the file - url // Path - String - Save path on Dropbox - path -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function UploadFileByURL(Val Token, Val FileURL, Val Path) Export - - URL = "https://api.dropboxapi.com/2/files/save_url"; - + + URL = "https://api.dropboxapi.com/2/files/save_url"; + Parameters = New Structure; - OPI_Tools.AddField("path", Path , "String", Parameters); + OPI_Tools.AddField("path", Path , "String", Parameters); OPI_Tools.AddField("url" , FileURL , "String", Parameters); - - Headers = GetRequestHeaders(Token); + + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Get upload status by URL // Gets the upload status of the file by URL -// +// // Parameters: // Token - String - Token - token -// JobID - String - ID of async jsob from UploadFileByURL response - job -// +// JobID - String - ID of async jsob from UploadFileByURL response - job +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function GetUploadStatusByURL(Val Token, Val JobID) Export - - URL = "https://api.dropboxapi.com/2/files/save_url/check_job_status"; - + + URL = "https://api.dropboxapi.com/2/files/save_url/check_job_status"; + Parameters = New Structure; OPI_Tools.AddField("async_job_id", JobID, "String", Parameters); - - Headers = GetRequestHeaders(Token); + + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Delete object // Deletes an object from the cloud drive -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the object to delete - path // Irrecoverable - String - Delete object without the possibility of recovery - permanently -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function DeleteObject(Val Token, Val Path, Val Irrecoverable = False) Export - + OPI_TypeConversion.GetBoolean(Irrecoverable); - + If Irrecoverable Then URL = "https://api.dropboxapi.com/2/files/permanently_delete"; Else URL = "https://api.dropboxapi.com/2/files/delete_v2"; EndIf; - + Response = ProcessObject(Token, URL, Path); - + Return Response; EndFunction // Copy object // Copies a file or directory to the selected path -// +// // Parameters: // Token - String - Token - token // From - String - Path to the original object - form // Target - String - Target path for the new object - to -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function CopyObject(Val Token, Val From, Val Target) Export - + URL = "https://api.dropboxapi.com/2/files/copy_v2"; - + Parameters = New Structure; - OPI_Tools.AddField("from_path", From, "String", Parameters); - OPI_Tools.AddField("to_path" , Target , "String", Parameters); - + OPI_Tools.AddField("from_path", From , "String", Parameters); + OPI_Tools.AddField("to_path" , Target , "String", Parameters); + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Move object // Moves an object to the selected path -// +// // Parameters: // Token - String - Token - token // From - String - Path to the original object - form // Target - String - Target path for the new object - to -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function MoveObject(Val Token, Val From, Val Target) Export URL = "https://api.dropboxapi.com/2/files/move_v2"; - + Parameters = New Structure; - OPI_Tools.AddField("from_path", From, "String", Parameters); - OPI_Tools.AddField("to_path" , Target , "String", Parameters); - + OPI_Tools.AddField("from_path", From , "String", Parameters); + OPI_Tools.AddField("to_path" , Target , "String", Parameters); + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Create folder // Creates an empty directory at the selected path -// +// // Parameters: // Token - String - Token - token // Path - String - Target path for creating the directory - path -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function CreateFolder(Val Token, Val Path) Export - - URL = "https://api.dropboxapi.com/2/files/create_folder_v2"; + + URL = "https://api.dropboxapi.com/2/files/create_folder_v2"; Response = ProcessObject(Token, URL, Path); - + Return Response; - + EndFunction // Download file // Downloads a file by the specified path or ID -// +// // Parameters: // Token - String - Token - token // Path - String - Path or ID of the file - path -// +// // Returns: // BinaryData - binary data of the file Function DownloadFile(Val Token, Val Path) Export - - URL = "https://content.dropboxapi.com/2/files/download"; + + URL = "https://content.dropboxapi.com/2/files/download"; Response = ProcessObject(Token, URL, Path, True); - + Return Response; - + EndFunction // Download folder // Downloads a zip archive with the contents of the specified directory -// +// // Parameters: // Token - String - Token - token // Path - String - Path or ID of the directory - path -// +// // Returns: // BinaryData - binary data of the zip archive with the contents of the directory Function DownloadFolder(Val Token, Val Path) Export - - URL = "https://content.dropboxapi.com/2/files/download_zip"; + + URL = "https://content.dropboxapi.com/2/files/download_zip"; Response = ProcessObject(Token, URL, Path, True); - + Return Response; - + EndFunction // Get list of object versions // Gets the list of versions (revisions) of the object -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the object - path // Count - String, Number - Number of the latest versions of the object to display - amount -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function GetObjectVersionList(Val Token, Val Path, Val Count = 10) Export - - URL = "https://api.dropboxapi.com/2/files/list_revisions"; - + + URL = "https://api.dropboxapi.com/2/files/list_revisions"; + Parameters = New Structure; - OPI_Tools.AddField("path" , Path , "String", Parameters); + OPI_Tools.AddField("path" , Path , "String" , Parameters); OPI_Tools.AddField("limit", Count, "Number" , Parameters); - - Headers = GetRequestHeaders(Token); + + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Restore object to version // Restores object state to required version (revision) -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the object - path // Version - String - ID of the version (revision) for restoration - rev -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function RestoreObjectToVersion(Val Token, Val Path, Val Version) Export - - URL = "https://api.dropboxapi.com/2/files/restore"; - + + URL = "https://api.dropboxapi.com/2/files/restore"; + Parameters = New Structure; - OPI_Tools.AddField("path", Path , "String", Parameters); + OPI_Tools.AddField("path", Path , "String", Parameters); OPI_Tools.AddField("rev" , Version, "String", Parameters); - - Headers = GetRequestHeaders(Token); + + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction #EndRegion @@ -518,58 +518,58 @@ EndFunction // Get list of tags // Gets the list of tags of the selected files -// +// // Parameters: // Token - String - Token - token // Paths - String, Array of String - Path or set of paths to the files - paths -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function GetTagList(Val Token, Val Paths) Export - + URL = "https://api.dropboxapi.com/2/files/tags/get"; - + Parameters = New Structure; OPI_Tools.AddField("paths", Paths, "Array", Parameters); - + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Add tag // Add new tag to file or folder -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the object for which the tag needs to be created - path // Tag - String - Tag text - tag -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function AddTag(Val Token, Val Path, Val Tag) Export - + Return ProcessTag(Token, Path, Tag); - + EndFunction // Delete tag // Deletes the text tag of a file or directory -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the object whose tag needs to be deleted - path // Tag - String - Tag text - tag -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function DeleteTag(Val Token, Val Path, Val Tag) Export - + Return ProcessTag(Token, Path, Tag, True); - + EndFunction #EndRegion @@ -578,39 +578,39 @@ EndFunction // Publish folder // Sets the directory to public access mode -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the target directory - path -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function PublishFolder(Val Token, Val Path) Export - - URL = "https://api.dropboxapi.com/2/sharing/share_folder"; + + URL = "https://api.dropboxapi.com/2/sharing/share_folder"; Response = ProcessObject(Token, URL, Path); - + Return Response; - + EndFunction // Unpublish folder // Cancels the public access mode for the directory -// +// // Parameters: // Token - String - Token - token // FolderID - String - ID of the public catalog (shared folder ID) - folder -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function CancelFolderPublication(Val Token, Val FolderID) Export - + URL = "https://api.dropboxapi.com/2/sharing/unshare_folder"; - + Parameters = New Structure; OPI_Tools.AddField("shared_folder_id", FolderID, "String", Parameters); - - Headers = GetRequestHeaders(Token); + + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); Return Response; @@ -619,121 +619,121 @@ EndFunction // Add user to file // Defines access to the file for an external user -// +// // Parameters: // Token - String - Token - token // FileID - String - ID of the file to be accessed - fileid // EmailAddresses - String, Array of String - List of email addresses of users being added - emails // ViewOnly - Boolean - Prohibits file editing for the external user - readonly -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function AddUsersToFile(Val Token, Val FileID, Val EmailAddresses, Val ViewOnly = True) Export - + String_ = "String"; - + OPI_TypeConversion.GetArray(EmailAddresses); OPI_TypeConversion.GetLine(FileID); OPI_TypeConversion.GetBoolean(ViewOnly); - + If Not StrStartsWith(FileID, "id:") Then FileID = "id:" + FileID; EndIf; - + URL = "https://api.dropboxapi.com/2/sharing/add_file_member"; - + ArrayOfUsers = New Array; - + For Each Address In EmailAddresses Do - + UserData = New Map; - OPI_Tools.AddField(".tag" , "email", String_, UserData); + OPI_Tools.AddField(".tag" , "email" , String_, UserData); OPI_Tools.AddField("email", Address , String_, UserData); - + ArrayOfUsers.Add(UserData); EndDo; - + Parameters = New Structure; - OPI_Tools.AddField("file" , FileID , String_, Parameters); + OPI_Tools.AddField("file" , FileID , String_, Parameters); OPI_Tools.AddField("members", ArrayOfUsers , "Array", Parameters); - + Mode = ?(ViewOnly, "viewer", "editor"); - + OPI_Tools.AddField("access_level", Mode , String_, Parameters); - + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Add users to folder // Grants external users access to the directory -// +// // Parameters: // Token - String - Token - token // FolderID - String - ID of the public catalog (shared folder ID) - folder // EmailAddresses - String, Array of String - List of email addresses of users being added - emails // ViewOnly - Boolean - Prohibits file editing for the external user - readonly -// +// // Returns: // Undefined - empty response Function AddUsersToFolder(Val Token, Val FolderID, Val EmailAddresses, Val ViewOnly = True) Export - + String_ = "String"; - + OPI_TypeConversion.GetArray(EmailAddresses); OPI_TypeConversion.GetBoolean(ViewOnly); Mode = ?(ViewOnly, "viewer", "editor"); - + URL = "https://api.dropboxapi.com/2/sharing/add_folder_member"; - + ArrayOfUsers = New Array; - + For Each Address In EmailAddresses Do - + UserData = New Map; - OPI_Tools.AddField(".tag" , "email", String_, UserData); + OPI_Tools.AddField(".tag" , "email" , String_, UserData); OPI_Tools.AddField("email", Address , String_, UserData); - - UserStructure = New Structure("member,access_level", UserData, Mode); - + + UserStructure = New Structure("member,access_level", UserData, Mode); + ArrayOfUsers.Add(UserStructure); EndDo; - + Parameters = New Structure; - OPI_Tools.AddField("shared_folder_id", FolderID , String_, Parameters); - OPI_Tools.AddField("members" , ArrayOfUsers , "Array", Parameters); - + OPI_Tools.AddField("shared_folder_id", FolderID , String_, Parameters); + OPI_Tools.AddField("members" , ArrayOfUsers , "Array", Parameters); + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction // Get asynchronous change status // Get async job status for access changes -// +// // Parameters: // Token - String - Token - token // JobID - String - AsynchronousJobID - job -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function GetAsynchronousChangeStatus(Val Token, Val JobID) Export - + URL = "https://api.dropboxapi.com/2/sharing/check_job_status"; - + Parameters = New Structure; OPI_Tools.AddField("async_job_id", JobID, "String", Parameters); - - Headers = GetRequestHeaders(Token); + + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); Return Response; @@ -742,31 +742,31 @@ EndFunction // Unpublish file // Prohibits access to the file for external users -// +// // Parameters: // Token - String - Token - token // FileID - String - ID of the file to be accessed - fileid -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function CancelFilePublication(Val Token, Val FileID) Export - + OPI_TypeConversion.GetLine(FileID); - + If Not StrStartsWith(FileID, "id:") Then FileID = "id:" + FileID; EndIf; - + URL = "https://api.dropboxapi.com/2/sharing/unshare_file"; - + Parameters = New Structure; OPI_Tools.AddField("file", FileID, "String", Parameters); - - Headers = GetRequestHeaders(Token); + + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); Return Response; - + EndFunction #EndRegion @@ -776,20 +776,20 @@ EndFunction #Region Private Function ProcessObject(Val Token, Val URL, Val Path, Val InHeaders = False) - + Parameters = New Structure; OPI_Tools.AddField("path", Path, "String", Parameters); - + If InHeaders Then - Headers = GetRequestHeaders(Token, Parameters); + Headers = GetRequestHeaders(Token, Parameters); Response = OPI_Tools.PostBinary(URL, GetBinaryDataFromString(""), Headers); Else - Headers = GetRequestHeaders(Token); + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); EndIf; - + Return Response; - + EndFunction Function ProcessTag(Val Token, Val Path, Val Tag, Val ThisIsDeletion = False) @@ -799,168 +799,168 @@ Function ProcessTag(Val Token, Val Path, Val Tag, Val ThisIsDeletion = False) Else URL = "https://api.dropboxapi.com/2/files/tags/add"; EndIf; - + Parameters = New Structure; - OPI_Tools.AddField("path" , Path, "String", Parameters); + OPI_Tools.AddField("path" , Path, "String", Parameters); OPI_Tools.AddField("tag_text" , Tag , "String", Parameters); - + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction Function GetRequestHeaders(Val Token, Val Parameters = "") - + OPI_TypeConversion.GetLine(Token); - + Headers = New Map; Headers.Insert("Authorization" , "Bearer " + Token); - + If ValueIsFilled(Parameters) Then - + JSON = OPI_Tools.JSONString(Parameters, "None"); JSON = StrReplace(JSON, Chars.CR + Chars.LF, ""); Headers.Insert("Dropbox-API-Arg", JSON); - + EndIf; - + Return Headers; - + EndFunction Function UploadLargeFile(Val Token, Val File, Val Path, Val Mode) - - URL = "https://content.dropboxapi.com/2/files/upload_session/append_v2"; - ChunkSize = 100000000; + URL = "https://content.dropboxapi.com/2/files/upload_session/append_v2"; + + ChunkSize = 100000000; CurrentPosition = 0; - BytesRead = 0; - TotalSize = File.Size(); - Session = OpenSession(Token); - + BytesRead = 0; + TotalSize = File.Size(); + Session = OpenSession(Token); + WHile BytesRead < TotalSize Do - + Indent = CurrentPosition; Cursor = New Structure("offset,session_id", Indent, Session); - + Parameters = New Structure("cursor", Cursor); - Headers = GetRequestHeaders(Token, Parameters); - - DataReader = New DataReader(File); - BytesRead = DataReader.Skip(CurrentPosition); - Result = DataReader.Read(ChunkSize); - CurrentData = Result.GetBinaryData(); - CurrentSize = CurrentData.Size(); - NextPosition = CurrentPosition + CurrentSize; - + Headers = GetRequestHeaders(Token, Parameters); + + DataReader = New DataReader(File); + BytesRead = DataReader.Skip(CurrentPosition); + Result = DataReader.Read(ChunkSize); + CurrentData = Result.GetBinaryData(); + CurrentSize = CurrentData.Size(); + NextPosition = CurrentPosition + CurrentSize; + If Not ValueIsFilled(CurrentData) Then Break; EndIf; Response = OPI_Tools.PostBinary(URL, CurrentData, Headers); - + CurrentPosition = NextPosition; - + KBytes = 1024; - MByte = KBytes * KBytes; + MByte = KBytes * KBytes; Message(OPI_Tools.ProgressInformation(CurrentPosition, TotalSize, "MB", MByte)); - + RunGarbageCollection(); FreeObject(CurrentData); - + EndDo; - + Response = CloseSession(Token, Path, Mode, TotalSize, Session); - + Return Response; - + EndFunction Function UploadSmallFile(Val Token, Val File, Val Path, Val Mode) - + Boolean_ = "Boolean"; - String_ = "String"; - URL = "https://content.dropboxapi.com/2/files/upload"; - + String_ = "String"; + URL = "https://content.dropboxapi.com/2/files/upload"; + Parameters = New Structure; - - OPI_Tools.AddField("autorename" , False , Boolean_, Parameters); - OPI_Tools.AddField("mode" , Mode, String_, Parameters); - OPI_Tools.AddField("mute" , False , Boolean_, Parameters); - OPI_Tools.AddField("path" , Path , String_, Parameters); + + OPI_Tools.AddField("autorename" , False , Boolean_, Parameters); + OPI_Tools.AddField("mode" , Mode , String_ , Parameters); + OPI_Tools.AddField("mute" , False , Boolean_, Parameters); + OPI_Tools.AddField("path" , Path , String_ , Parameters); OPI_Tools.AddField("strict_conflict", False , Boolean_, Parameters); - + Headers = GetRequestHeaders(Token, Parameters); Response = OPI_Tools.PostBinary(URL, File, Headers); - + Return Response; - + EndFunction Function OpenSession(Val Token) - + SessionId = "session_id"; - URL = "https://content.dropboxapi.com/2/files/upload_session/start"; - Headers = GetRequestHeaders(Token); - - Response = OPI_Tools.PostBinary(URL, GetBinaryDataFromString(""), Headers); - + URL = "https://content.dropboxapi.com/2/files/upload_session/start"; + Headers = GetRequestHeaders(Token); + + Response = OPI_Tools.PostBinary(URL, GetBinaryDataFromString(""), Headers); + Return Response[SessionId]; - + EndFunction Function CloseSession(Val Token, Val Path, Val Mode, Val TotalSize, Val Session) URL = "https://content.dropboxapi.com/2/files/upload_session/finish"; - + Commit = New Structure(); OPI_Tools.AddField("mode", Mode, "String", Commit); - OPI_Tools.AddField("path", Path, "String", Commit); - + OPI_Tools.AddField("path", Path, "String", Commit); + Cursor = New Structure("offset,session_id", TotalSize, Session); - + Parameters = New Structure("commit,cursor", Commit, Cursor); - Headers = GetRequestHeaders(Token, Parameters); - + Headers = GetRequestHeaders(Token, Parameters); + Response = OPI_Tools.PostBinary(URL, GetBinaryDataFromString(""), Headers); - + Return Response; - + EndFunction Function GetAccount(Val Token, Val Account) - + URL = "https://api.dropboxapi.com/2/users/get_account"; - + Parameters = New Structure; OPI_Tools.AddField("account_id", Account, "String", Parameters); - + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction Function GetOwnAccount(Val Token) - - URL = "https://api.dropboxapi.com/2/users/get_current_account"; + + URL = "https://api.dropboxapi.com/2/users/get_current_account"; Headers = GetRequestHeaders(Token); - + Response = OPI_Tools.PostBinary(URL , GetBinaryDataFromString("null") , Headers - , - , "text/plain; charset=dropbox-cors-hack"); - + , + , "text/plain; charset=dropbox-cors-hack"); + Return Response; - + EndFunction #EndRegion diff --git a/src/en/OInt/core/Modules/OPI_GoogleCalendar.os b/src/en/OInt/core/Modules/OPI_GoogleCalendar.os index 4daa35bb29..566d5455cb 100644 --- a/src/en/OInt/core/Modules/OPI_GoogleCalendar.os +++ b/src/en/OInt/core/Modules/OPI_GoogleCalendar.os @@ -43,131 +43,131 @@ // Create calendar // Creates an empty calendar -// +// // Parameters: // Token - String - Token - token // Name - String - Name of the created calendar - title -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function CreateCalendar(Val Token, Val Name) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Name); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/calendar/v3/calendars"; - + URL = "https://www.googleapis.com/calendar/v3/calendars"; + Parameters = New Structure; Parameters.Insert("summary" , Name); Parameters.Insert("timeZone", "Europe/Moscow"); - + Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Get calendar // Gets calendar information by ID -// +// // Parameters: // Token - String - Token - token // Calendar - String - Calendar ID - calendar -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function GetCalendarMetadata(Val Token, Val Calendar) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Calendar); - - Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/calendar/v3/calendars/" + Calendar; + + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); + URL = "https://www.googleapis.com/calendar/v3/calendars/" + Calendar; Response = OPI_Tools.Get(URL, , Headers); - + Return Response; EndFunction // Edit calendar // Edits properties of an existing calendar -// +// // Parameters: // Token - String - Token - token // Calendar - String - Calendar ID - calendar // Name - String - New name - title // Description - String - New calendar description - description -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function EditCalendarMetadata(Val Token , Val Calendar , Val Name = "" , Val Description = "") Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Calendar); OPI_TypeConversion.GetLine(Name); OPI_TypeConversion.GetLine(Description); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/calendar/v3/calendars/" + Calendar; - + URL = "https://www.googleapis.com/calendar/v3/calendars/" + Calendar; + Parameters = New Structure; - + If ValueIsFilled(Name) Then Parameters.Insert("summary", Name); EndIf; - + If ValueIsFilled(Description) Then Parameters.Insert("description", Description); EndIf; - + Response = OPI_Tools.Patch(URL, Parameters, Headers, True); - + Return Response; EndFunction // Clear primary calendar // Clears the event list of the primary calendar -// +// // Parameters: // Token - String - Token - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function ClearMainCalendar(Val Token) Export - + OPI_TypeConversion.GetLine(Token); - - Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/calendar/v3/calendars/primary/clear"; + + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); + URL = "https://www.googleapis.com/calendar/v3/calendars/primary/clear"; Response = OPI_Tools.Post(URL, , Headers, False); - + Return Response; EndFunction // Delete calendar // Deletes a calendar by ID -// +// // Parameters: // Token - String - Token - token // Calendar - String - Calendar ID - calendar -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function DeleteCalendar(Val Token, Val Calendar) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Calendar); - - Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/calendar/v3/calendars/" + Calendar; + + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); + URL = "https://www.googleapis.com/calendar/v3/calendars/" + Calendar; Response = OPI_Tools.Delete(URL, , Headers); - + Return Response; EndFunction @@ -178,105 +178,105 @@ EndFunction // Get list of calendars // Gets an array of account calendars -// +// // Parameters: // Token - String - Token - token -// +// // Returns: // Map Of KeyAndValue - Array of calendar data mappings Function GetCalendarList(Val Token) Export - + OPI_TypeConversion.GetLine(Token); - - Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); + + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); ArrayOfCalendars = New Array; - + GetCalendarsListRecursively(Headers, ArrayOfCalendars); - + Return ArrayOfCalendars; - + EndFunction // Add calendar to list // Adds an existing calendar to the user's list -// +// // Parameters: // Token - String - Token - token // Calendar - String - Calendar ID - calendar -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function AddCalendarToList(Val Token, Val Calendar) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Calendar); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/calendar/v3/users/me/calendarList"; - + URL = "https://www.googleapis.com/calendar/v3/users/me/calendarList"; + Parameters = New Structure; Parameters.Insert("id", Calendar); - + Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Get list calendar // Gets a calendar from the user's list by ID -// +// // Parameters: // Token - String - Token - token // Calendar - String - Calendar ID - calendar -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function GetListCalendar(Val Token, Val Calendar) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Calendar); - - Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/calendar/v3/users/me/calendarList/" + Calendar; + + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); + URL = "https://www.googleapis.com/calendar/v3/users/me/calendarList/" + Calendar; Response = OPI_Tools.Get(URL, , Headers); - + Return Response; EndFunction // Remove calendar from list // Removes a calendar from the user's list -// +// // Parameters: // Token - String - Token - token // Calendar - String - Calendar ID - calendar -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function DeleteCalendarFromList(Val Token, Val Calendar) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Calendar); - - Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/calendar/v3/users/me/calendarList/" + Calendar; + + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); + URL = "https://www.googleapis.com/calendar/v3/users/me/calendarList/" + Calendar; Response = OPI_Tools.Delete(URL, , Headers); - + Return Response; EndFunction // Edit list calendar // Edits the properties of a calendar from the user's list -// +// // Parameters: // Token - String - Token - token // Calendar - String - Calendar ID - calendar // PrimaryColor - String - HEX primary color (#ffffff) - primary // SecondaryColor - String - HEX secondary color (#ffffff) - secondary // Hidden - Boolean - Hidden calendar - hidden -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function EditListCalendar(Val Token @@ -284,23 +284,23 @@ Function EditListCalendar(Val Token , Val PrimaryColor , Val SecondaryColor , Val Hidden = False) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Calendar); OPI_TypeConversion.GetLine(PrimaryColor); OPI_TypeConversion.GetLine(SecondaryColor); OPI_TypeConversion.GetBoolean(Hidden); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/calendar/v3/users/me/calendarList/" + Calendar + "?colorRgbFormat=true"; - + URL = "https://www.googleapis.com/calendar/v3/users/me/calendarList/" + Calendar + "?colorRgbFormat =true"; + Parameters = New Map; - Parameters.Insert("hidden" , Hidden); + Parameters.Insert("hidden" , Hidden); Parameters.Insert("foregroundColor", PrimaryColor); Parameters.Insert("backgroundColor", SecondaryColor); - + Response = OPI_Tools.Put(URL, Parameters, Headers); - + Return Response; EndFunction @@ -310,167 +310,167 @@ EndFunction #Region EventManagement // Get event description !NOCLI -// +// // Returns: // Map Of KeyAndValue - Empty event template Function GetEventDescription() Export - + CurrentDate = OPI_Tools.GetCurrentDate(); - Hour = 3600; - Event = New Map; - - Event.Insert("Description" , ""); // Event description - Event.Insert("Title" , "New event"); // Title events - Event.Insert("Venue" , ""); // String description of the venue of the event - Event.Insert("StartDate" , CurrentDate); // Date of start events - Event.Insert("EndDate" , CurrentDate + Hour); // Date of end events + Hour = 3600; + Event = New Map; + + Event.Insert("Description" , ""); // Event description + Event.Insert("Title" , "New event"); // Title events + Event.Insert("Venue" , ""); // String description of the venue of the event + Event.Insert("StartDate" , CurrentDate); // Date of start events + Event.Insert("EndDate" , CurrentDate + Hour); // Date of end events Event.Insert("ArrayOfAttachmentURLs", New Map); // Key - name, Value - URL to file - Event.Insert("SendNotifications" , True); // Indication of sending notifications to participants + Event.Insert("SendNotifications" , True); // Indication of sending notifications to participants Return Event; - + EndFunction // Get list of events // Gets the list of all calendar events -// +// // Parameters: // Token - String - Token - token // Calendar - String - Calendar ID - calendar -// +// // Returns: // Map Of KeyAndValue - Array of event maps Function GetEventList(Val Token, Val Calendar) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Calendar); - - Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); + + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); ArrayOfEvents = New Array; - + GetEventsListRecursively(Headers, Calendar, ArrayOfEvents); - + Return ArrayOfEvents; - + EndFunction // Get event // Gets an event by ID -// +// // Parameters: // Token - String - Token - token // Calendar - String - Calendar ID - calendar // Event - String - Event ID - event -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function GetEvent(Val Token, Val Calendar, Val Event) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Calendar); OPI_TypeConversion.GetLine(Event); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/calendar/v3/calendars/" - + Calendar + URL = "https://www.googleapis.com/calendar/v3/calendars/" + + Calendar + "/events/" - + Event; - + + Event; + Response = OPI_Tools.Get(URL, , Headers); - + Return Response; EndFunction // Create event // Creates a new event -// +// // Parameters: -// Token - String - Token - token +// Token - String - Token - token // Calendar - String - Calendar ID - calendar // EventDescription - Map Of KeyAndValue - Event description - props -// +// // Returns: // String, Arbitrary, HTTPResponse, BinaryData, Undefined - Google server response -Function CreateEvent(Val Token, Val Calendar, Val EventDescription) Export - +Function CreateEvent(Val Token, Val Calendar, Val EventDescription) Export + Return EventManagement(Token, Calendar, EventDescription); - + EndFunction // Move event // Moves an event to another calendar -// +// // Parameters: // Token - String - Token - token // SourceCalendar - String - ID of the source calendar - from // TargetCalendar - String - ID of the target calendar - to // Event - String - ID of the source calendar event - event -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function MoveEvent(Val Token, Val SourceCalendar, Val TargetCalendar, Val Event) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(SourceCalendar); OPI_TypeConversion.GetLine(TargetCalendar); OPI_TypeConversion.GetLine(Event); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/calendar/v3/calendars/" - + SourceCalendar + URL = "https://www.googleapis.com/calendar/v3/calendars/" + + SourceCalendar + "/events/" + Event + "/move?destination=" - + TargetCalendar; - + + TargetCalendar; + Response = OPI_Tools.Post(URL, , Headers); - + Return Response; EndFunction // Edit event // Edits an existing event -// +// // Parameters: // Token - String - Token - token // Calendar - String - Calendar ID - calendar // EventDescription - String - New event description - props // Event - String - Event ID - event -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function EditEvent(Val Token, Val Calendar, Val EventDescription, Val Event) Export - + Return EventManagement(Token, Calendar, EventDescription, Event); - + EndFunction // Delete event // Deletes an event by ID -// +// // Parameters: // Token - String - Token - token // Calendar - String - Calendar ID - calendar // Event - String - Event ID - event -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function DeleteEvent(Val Token, Val Calendar, Val Event) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Calendar); OPI_TypeConversion.GetLine(Event); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/calendar/v3/calendars/" - + Calendar + URL = "https://www.googleapis.com/calendar/v3/calendars/" + + Calendar + "/events/" - + Event; - + + Event; + Response = OPI_Tools.Delete(URL, , Headers); - + Return Response; EndFunction @@ -482,51 +482,51 @@ EndFunction #Region Private Function ConvertDate(Val Date) - + OPI_TypeConversion.GetDate(Date); - + DateStructure = New Structure; - + If Not TypeOf(Date) = Type("Date") Then Return Undefined; EndIf; - - If Date = BegOfDay(Date) Then + + If Date = BegOfDay(Date) Then DateFormat = "DF=yyyy-MM-dd"; - Field = "date"; + Field = "date"; Else DateFormat = "DF=yyyy-MM-ddTHH:mm:ssZ"; - Field = "dateTime"; + Field = "dateTime"; EndIf; - + Date = Format(Date, DateFormat); - DateStructure.Insert(Field , Date); + DateStructure.Insert(Field , Date); DateStructure.Insert("timeZone", "Europe/Moscow"); - + Return DateStructure; - + EndFunction Function ConvertAttachments(Val Attachments) - + OPI_TypeConversion.GetCollection(Attachments); - + AttachmentsArray = New Array; - + If TypeOf(Attachments) = Type("Map") Or TypeOf(Attachments) = Type("Structure") Then - + For Each Attachment In Attachments Do - + CurrentAttachment = New Structure; - CurrentAttachment.Insert("title" , Attachment.Key); + CurrentAttachment.Insert("title" , Attachment.Key); CurrentAttachment.Insert("fileUrl", Attachment.Value); - + AttachmentsArray.Add(CurrentAttachment); - + EndDo; - + EndIf; - + If AttachmentsArray.Count() > 0 Then Return AttachmentsArray; Else @@ -536,105 +536,105 @@ Function ConvertAttachments(Val Attachments) EndFunction Function EventManagement(Val Token, Val Calendar, Val EventDescription, Val Event = "") - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Calendar); OPI_TypeConversion.GetLine(Event); OPI_TypeConversion.GetCollection(EventDescription); - - Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); + + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); Existing = ValueIsFilled(Event); - URL = "https://www.googleapis.com/calendar/v3/calendars/" - + Calendar + URL = "https://www.googleapis.com/calendar/v3/calendars/" + + Calendar + "/events" - + ?(Existing, "/" + Event, ""); - - Date0 = EventDescription["StartDate"]; - Date1 = EventDescription["EndDate"]; - Attachments = EventDescription["ArrayOfAttachmentURLs"]; - Attachments = ConvertAttachments(Attachments); + + ?(Existing, "/" + Event, ""); + + Date0 = EventDescription["StartDate"]; + Date1 = EventDescription["EndDate"]; + Attachments = EventDescription["ArrayOfAttachmentURLs"]; + Attachments = ConvertAttachments(Attachments); Notifications = ?(EventDescription["SendNotifications"] = Undefined , False , EventDescription["SendNotifications"]); - + Parameters = New Structure; - Parameters.Insert("summary" , EventDescription["Title"]); + Parameters.Insert("summary" , EventDescription["Title"]); Parameters.Insert("description", EventDescription["Description"]); - Parameters.Insert("location" , EventDescription["Venue"]); - Parameters.Insert("start" , ConvertDate(Date0)); - Parameters.Insert("end" , ConvertDate(Date1)); - Parameters.Insert("attachments", Attachments); - - URLParameters = New Structure; - URLParameters.Insert("sendUpdates" , ?(Notifications, "all", "none")); + Parameters.Insert("location" , EventDescription["Venue"]); + Parameters.Insert("start" , ConvertDate(Date0)); + Parameters.Insert("end" , ConvertDate(Date1)); + Parameters.Insert("attachments", Attachments); + + URLParameters = New Structure; + URLParameters.Insert("sendUpdates" , ?(Notifications , "all" , "none")); URLParameters.Insert("supportsAttachments" , ?(ValueIsFilled(Attachments), "true", "false")); - + URL = URL + OPI_Tools.RequestParametersToString(URLParameters); - + OPI_Tools.RemoveEmptyCollectionFields(Parameters); - + If Existing Then Response = OPI_Tools.Patch(URL, Parameters, Headers, True); Else Response = OPI_Tools.Post(URL, Parameters, Headers, True); EndIf; - + Return Response; EndFunction -Procedure GetCalendarsListRecursively(Val Headers, ArrayOfCalendars, Page = "") - - Items = "items"; - NPT = "nextPageToken"; +Procedure GetCalendarsListRecursively(Val Headers, ArrayOfCalendars, Page = "") + + Items = "items"; + NPT = "nextPageToken"; Parameters = New Structure; - + If ValueIsFilled(Page) Then Parameters.Insert("pageToken", Page); EndIf; - + Result = OPI_Tools.Get("https://www.googleapis.com/calendar/v3/users/me/calendarList" , Parameters , Headers); - + Calendars = Result[Items]; - Page = Result[NPT]; - + Page = Result[NPT]; + For Each Calendar In Calendars Do - ArrayOfCalendars.Add(Calendar); - EndDo; - + ArrayOfCalendars.Add(Calendar); + EndDo; + If Calendars.Count() > 0 And ValueIsFilled(Page) Then - GetCalendarsListRecursively(Headers, ArrayOfCalendars, Page); + GetCalendarsListRecursively(Headers, ArrayOfCalendars, Page); EndIf; - + EndProcedure -Procedure GetEventsListRecursively(Val Headers, Val Calendar, ArrayOfEvents, Page = "") - - Items = "items"; - NPT = "nextPageToken"; +Procedure GetEventsListRecursively(Val Headers, Val Calendar, ArrayOfEvents, Page = "") + + Items = "items"; + NPT = "nextPageToken"; Parameters = New Structure; - + If ValueIsFilled(Page) Then Parameters.Insert("pageToken", Page); EndIf; - + Result = OPI_Tools.Get("https://www.googleapis.com/calendar/v3/calendars/" + Calendar + "/events" , Parameters , Headers); - + Events = Result[Items]; - Page = Result[NPT]; - + Page = Result[NPT]; + For Each Event In Events Do - ArrayOfEvents.Add(Event); - EndDo; - + ArrayOfEvents.Add(Event); + EndDo; + If Events.Count() > 0 And ValueIsFilled(Page) Then - GetEventsListRecursively(Headers, ArrayOfEvents, Page); + GetEventsListRecursively(Headers, ArrayOfEvents, Page); EndIf; - + EndProcedure #EndRegion diff --git a/src/en/OInt/core/Modules/OPI_GoogleDrive.os b/src/en/OInt/core/Modules/OPI_GoogleDrive.os index 35418d7732..a0dcc76691 100644 --- a/src/en/OInt/core/Modules/OPI_GoogleDrive.os +++ b/src/en/OInt/core/Modules/OPI_GoogleDrive.os @@ -43,277 +43,277 @@ // Get object information // Gets information about a folder or file by ID -// +// // Parameters: // Token - String - Token - token // Identifier - String - Identifier of the file or folder - object -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function GetObjectInformation(Val Token, Val Identifier) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Identifier); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/drive/v3/files/" + Identifier; - + URL = "https://www.googleapis.com/drive/v3/files/" + Identifier; + Parameters = New Structure; Parameters.Insert("fields", "*"); - + Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; EndFunction // Get list of directories // Gets the list of drive directories -// +// // Parameters: // Token - String - Token - token // NameContains - String - Filter by name - querry // Detailed - Boolean - Adds a list of files to the directory fields - depth -// +// // Returns: // Map Of KeyAndValue - Array of directory mappings Function GetDirectoriesList(Val Token, Val NameContains = "", Val Detailed = False) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(NameContains); OPI_TypeConversion.GetBoolean(Detailed); - - Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); + + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); ArrayOfObjects = New Array; - Filter = New Array; - + Filter = New Array; + Filter.Add("mimeType = 'application/vnd.google-apps.folder'"); - + If ValueIsFilled(NameContains) Then Filter.Add("name contains '" + NameContains + "'"); EndIf; - + GetObjectsListRecursively(Headers, ArrayOfObjects, Detailed, Filter); - + If Detailed Then - BreakDownObjectsInDetail(Token, ArrayOfObjects); + BreakDownObjectsInDetail(Token, ArrayOfObjects); EndIf; - + Return ArrayOfObjects; - + EndFunction // Get list of files // Gets the list of files -// +// // Parameters: // Token - String - Token - token // NameContains - String - Filter by name - querry // Directory - String - Filter by parent directory ID - catalog -// +// // Returns: // Map Of KeyAndValue - Array of file mappings Function GetFilesList(Val Token, Val NameContains = "", Val Directory = "") Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(NameContains); OPI_TypeConversion.GetLine(Directory); - - Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); + + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); ArrayOfObjects = New Array; - Filter = New Array; - + Filter = New Array; + Filter.Add("mimeType != 'application/vnd.google-apps.folder'"); - + If ValueIsFilled(NameContains) Then Filter.Add("name contains '" + NameContains + "'"); EndIf; - + If ValueIsFilled(Directory) Then Filter.Add("'" + Directory + "' in parents"); EndIf; - + GetObjectsListRecursively(Headers, ArrayOfObjects, , Filter); - + Return ArrayOfObjects; EndFunction // Upload file // Uploads a file to the drive -// +// // Parameters: // Token - String - Token - token // File - BinaryData,String - File to be uploaded - file // Description - Map Of KeyAndValue - See GetFileDescription - props - JSON description or path to .json -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function UploadFile(Val Token, Val File, Val Description) Export - - Return FileManagement(Token, File, Description); - + + Return FileManagement(Token, File, Description); + EndFunction // Create folder // Creates an empty directory on the drive -// +// // Parameters: // Token - String - Token - token // Name - String - Folder name - title // Parent - String - Parent - catalog -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function CreateFolder(Val Token, Val Name, Val Parent = "") Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Name); OPI_TypeConversion.GetLine(Parent); - + Description = New Map; - Description.Insert("MIME" , "application/vnd.google-apps.folder"); - Description.Insert("Name" , Name); + Description.Insert("MIME" , "application/vnd.google-apps.folder"); + Description.Insert("Name" , Name); Description.Insert("Description", ""); - Description.Insert("Parent", ?(ValueIsFilled(Parent), Parent, "root")); - + Description.Insert("Parent" , ?(ValueIsFilled(Parent), Parent, "root")); + Return FileManagement(Token, , Description); - + EndFunction // Download file // Gets file by ID -// +// // Parameters: // Token - String - Token - token // Identifier - String - File identifier - object -// SavePath - String - File save path - out -// +// SavePath - String - File save path - out +// // Returns: // BinaryData,String - Binary data or file path when SavePath parameter is specified Function DownloadFile(Val Token, Val Identifier, Val SavePath = "") Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Identifier); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/drive/v3/files/" + Identifier; - + URL = "https://www.googleapis.com/drive/v3/files/" + Identifier; + Parameters = New Map; Parameters.Insert("alt", "media"); - + Response = OPI_Tools.Get(URL, Parameters , Headers, SavePath); - + Return Response; EndFunction // Copy object // Copies file or directory -// +// // Parameters: // Token - String - Token - token // Identifier - String - Object identifier - object // NewName - String - New object name - title // NewParent - String - New parent directory - catalog -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function CopyObject(Val Token, Val Identifier, Val NewName = "", Val NewParent = "") Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(NewName); OPI_TypeConversion.GetLine(Identifier); OPI_TypeConversion.GetLine(NewParent); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/drive/v3/files/" + Identifier + "/copy"; - + URL = "https://www.googleapis.com/drive/v3/files/" + Identifier + "/copy"; + Parameters = New Structure; - + If ValueIsFilled(NewName) Then Parameters.Insert("name", NewName); EndIf; - + If ValueIsFilled(NewParent) Then - + ArrayOfParents = New Array; ArrayOfParents.Add(NewParent); Parameters.Insert("parents", ArrayOfParents); - + EndIf; - + Response = OPI_Tools.Post(URL, Parameters , Headers, True); - + Return Response; EndFunction // Update file // Updates file binary data -// +// // Parameters: // Token - String - Token - token // Identifier - String - Identifier of the object to update - object // File - BinaryData,String - File source for update - file // NewName - String - New file name (if necessary) - title -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function UpdateFile(Val Token, Val Identifier, Val File, Val NewName = "") Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Identifier); OPI_TypeConversion.GetLine(NewName); OPI_TypeConversion.GetBinaryData(File); - + If ValueIsFilled(NewName) Then Description = New Map; Description.Insert("Name", NewName); Else Description = ""; EndIf; - + Return FileManagement(Token, File, Description, Identifier); - + EndFunction // Delete object // Deletes file or directory by ID -// +// // Parameters: // Token - String - Token - token // Identifier - String - Identifier of the object to delete - object -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function DeleteObject(Val Token, Val Identifier) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Identifier); - - Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/drive/v3/files/" + Identifier; + + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); + URL = "https://www.googleapis.com/drive/v3/files/" + Identifier; Response = OPI_Tools.Delete(URL, , Headers); - + Return Response; EndFunction // Get file description !NOCLI -// +// // Returns: // Map Of KeyAndValue - File description Function GetFileDescription() Export - + Description = New Map; - Description.Insert("MIME" , "image/jpeg"); // MIME-type uploading file - Description.Insert("Name" , "New file.jpg"); // File name with extension + Description.Insert("MIME" , "image/jpeg"); // MIME-type uploading file + Description.Insert("Name" , "New file.jpg"); // File name with extension Description.Insert("Description" , "This is a new file"); // File description - Description.Insert("Parent" , "root"); // ID directory upload or "root" for upload in root - + Description.Insert("Parent" , "root"); // ID directory upload or "root" for upload in root + Return Description; - + EndFunction #EndRegion @@ -322,107 +322,107 @@ EndFunction // Create comment // Creates a comment for a file or directory -// +// // Parameters: // Token - String - Token - token -// Identifier - String - Identifier of the object that needs a comment - object +// Identifier - String - Identifier of the object that needs a comment - object // Comment - String - Comment text - text -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function CreateComment(Val Token, Val Identifier, Val Comment) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Identifier); OPI_TypeConversion.GetLine(Comment); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/drive/v3/files/" + Identifier + "/comments?fields=*"; - + URL = "https://www.googleapis.com/drive/v3/files/" + Identifier + "/comments?fields =*"; + Parameters = New Structure; Parameters.Insert("content", Comment); - + Response = OPI_Tools.POST(URL, Parameters, Headers); - + Return Response; EndFunction // Get comment // Gets comment by ID -// +// // Parameters: // Token - String - Token - token // ObjectID - String - Identifier of the file or directory where the comment is located - object // CommentID - String - Comment identifier - comment -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function GetComment(Val Token, Val ObjectID, Val CommentID) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(ObjectID); OPI_TypeConversion.GetLine(CommentID); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/drive/v3/files/" + ObjectID + "/comments/" + CommentID; - + URL = "https://www.googleapis.com/drive/v3/files/" + ObjectID + "/comments/" + CommentID; + Parameters = New Structure; Parameters.Insert("fields", "*"); - + Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; EndFunction // Get list of comments // Gets the list of all comments of the object -// +// // Parameters: // Token - String - Token - token // ObjectID - String - Object identifier - object -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function GetCommentList(Val Token, Val ObjectID) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(ObjectID); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/drive/v3/files/" + ObjectID + "/comments"; - + URL = "https://www.googleapis.com/drive/v3/files/" + ObjectID + "/comments"; + Parameters = New Structure; Parameters.Insert("fields", "*"); - + Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; EndFunction // Delete comment // Deletes comment by ID -// +// // Parameters: // Token - String - Token - token // ObjectID - String - Identifier of the file or directory where the comment is located - object // CommentID - String - Comment identifier - comment -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function DeleteComment(Val Token, Val ObjectID, Val CommentID) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(ObjectID); OPI_TypeConversion.GetLine(CommentID); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/drive/v3/files/" + ObjectID + "/comments/" + CommentID; - + URL = "https://www.googleapis.com/drive/v3/files/" + ObjectID + "/comments/" + CommentID; + Response = OPI_Tools.Delete(URL, , Headers); - + Return Response; EndFunction @@ -433,294 +433,294 @@ EndFunction #Region Private -Procedure GetObjectsListRecursively(Val Headers, ArrayOfObjects, Detailed = False, Filter = "", Page = "") - - URL = "https://www.googleapis.com/drive/v3/files"; - Files = "files"; - NPT = "nextPageToken"; +Procedure GetObjectsListRecursively(Val Headers, ArrayOfObjects, Detailed = False, Filter = "", Page = "") + + URL = "https://www.googleapis.com/drive/v3/files"; + Files = "files"; + NPT = "nextPageToken"; Parameters = New Structure; Parameters.Insert("fields", "*"); - + If ValueIsFilled(Page) Then Parameters.Insert("pageToken", Page); EndIf; - - If ValueIsFilled(Filter) And TypeOf(Filter) = Type("Array") Then + + If ValueIsFilled(Filter) And TypeOf(Filter) = Type("Array") Then FilterString = StrConcat(Filter, " and "); - Parameters.Insert("q", FilterString); + Parameters.Insert("q", FilterString); EndIf; - + Result = OPI_Tools.Get(URL, Parameters, Headers); - + Objects = Result[Files]; - Page = Result[NPT]; - + Page = Result[NPT]; + For Each CurrentObject In Objects Do ArrayOfObjects.Add(CurrentObject); - EndDo; - + EndDo; + If Objects.Count() > 0 And ValueIsFilled(Page) Then - GetObjectsListRecursively(Headers, ArrayOfObjects, Detailed, Filter, Page); + GetObjectsListRecursively(Headers, ArrayOfObjects, Detailed, Filter, Page); EndIf; - + EndProcedure -Procedure BreakDownObjectsInDetail(Val Token, ArrayOfObjects) - +Procedure BreakDownObjectsInDetail(Val Token, ArrayOfObjects) + For Each CurrentObject In ArrayOfObjects Do - + ArrayOfFiles = New Array; - CurrentID = CurrentObject["id"]; - + CurrentID = CurrentObject["id"]; + Result = GetFilesList(Token, , CurrentID); - + For Each File In Result Do - ArrayOfFiles.Add(File); + ArrayOfFiles.Add(File); EndDo; - + CurrentObject.Insert("files", ArrayOfFiles); - + EndDo; - + EndProcedure Procedure FormFileUploadParameters(Description) - + FormedDescription = New Map; OPI_Tools.RemoveEmptyCollectionFields(Description); FieldMapping = New Map; - FieldMapping.Insert("MIME" , "mimeType"); - FieldMapping.Insert("Name" , "name"); + FieldMapping.Insert("MIME" , "mimeType"); + FieldMapping.Insert("Name" , "name"); FieldMapping.Insert("Description" , "description"); - FieldMapping.Insert("Parent" , "parents"); - FieldMapping.Insert("Extension", "fileExtension"); - + FieldMapping.Insert("Parent" , "parents"); + FieldMapping.Insert("Extension" , "fileExtension"); + For Each Element In Description Do - + If Element.Key = "Parent" Then - + CurrentValue = New Array; CurrentValue.Add(Element.Value); - + Else - + CurrentValue = Element.Value; - + EndIf; - + FieldName = FieldMapping.Get(Element.Key); FormedDescription.Insert(FieldName, CurrentValue); - + EndDo; - + Description = FormedDescription; - + EndProcedure -Function FileManagement(Val Token, Val File = "", Val Description = "", Val Identifier = "") - +Function FileManagement(Val Token, Val File = "", Val Description = "", Val Identifier = "") + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Identifier); - + If ValueIsFilled(Description) Then OPI_TypeConversion.GetCollection(Description); EndIf; - + MimeType = "mimeType"; - + If ValueIsFilled(Identifier) Then MIME = GetObjectInformation(Token, Identifier)[MimeType]; Else MIME = Description["MIME"]; - EndIf; - + EndIf; + If Not ValueIsFilled(Description) Then Description = New Map; EndIf; - - Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); + + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); FormFileUploadParameters(Description); JSONDescription = OPI_Tools.JSONString(Description); - + FileMapping = New Map; - + If ValueIsFilled(File) Then - - ChunkSize = 268435457; - Size = OPI_Tools.ConvertDataWithSizeRetrieval(File, ChunkSize); - + + ChunkSize = 268435457; + Size = OPI_Tools.ConvertDataWithSizeRetrieval(File, ChunkSize); + FileMapping.Insert(File, MIME); - + If Size < ChunkSize And TypeOf(File) = Type("BinaryData") Then Response = UploadSmallFile(JSONDescription, FileMapping, Headers, Identifier); Else Response = UploadLargeFile(Description, FileMapping, Headers, Identifier); EndIf; - + Else - Response = UploadSmallFile(JSONDescription, FileMapping, Headers, Identifier); + Response = UploadSmallFile(JSONDescription, FileMapping, Headers, Identifier); EndIf; - + Return Response; - + EndFunction Function UploadSmallFile(Val Description, Val FileMapping, Val Headers, Val Identifier = "") - + URL = "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart"; - + If ValueIsFilled(Identifier) Then - URL = StrReplace(URL, "/files", "/files/" + Identifier); + URL = StrReplace(URL, "/files", "/files/" + Identifier); Response = OPI_Tools.PatchMultipartRelated(URL, Description, FileMapping, Headers); Else Response = OPI_Tools.PostMultipartRelated(URL, Description, FileMapping, Headers); EndIf; Return Response; - + EndFunction Function UploadLargeFile(Val Description, Val FileMapping, Val Headers, Val Identifier = "") - + For Each File In FileMapping Do Binary = File.Key; Break; EndDo; - + URL = "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable"; - + If ValueIsFilled(Identifier) Then - URL = StrReplace(URL, "/files", "/files/" + Identifier); + URL = StrReplace(URL, "/files", "/files/" + Identifier); Response = OPI_Tools.Patch(URL, Description, Headers, True, True); Else Response = OPI_Tools.Post(URL, Description, Headers, True, True); EndIf; - + UploadURL = Response.Headers["Location"]; - + If Not ValueIsFilled(UploadURL) Then OPI_Tools.ProcessResponse(Response); Return Response; EndIf; - + UploadResponse = UploadFileInParts(Binary, UploadURL); - Response = ?(ValueIsFilled(UploadResponse), UploadResponse, Response); - + Response = ?(ValueIsFilled(UploadResponse), UploadResponse, Response); + OPI_Tools.ProcessResponse(Response); Return Response; - + EndFunction Function UploadFileInParts(Val Binary, Val UploadURL) - - Response = ""; - ChunkSize = 268435456; - BytesRead = 0; + + Response = ""; + ChunkSize = 268435456; + BytesRead = 0; CurrentPosition = 0; - TotalSize = Binary.Size(); - StrTotalSize = OPI_Tools.NumberToString(TotalSize); - DataReader = New DataReader(Binary); - SourceStream = DataReader.SourceStream(); - + TotalSize = Binary.Size(); + StrTotalSize = OPI_Tools.NumberToString(TotalSize); + DataReader = New DataReader(Binary); + SourceStream = DataReader.SourceStream(); + WHile BytesRead < TotalSize Do - - BytesRead = SourceStream.CurrentPosition(); - Result = DataReader.Read(ChunkSize); - CurrentData = Result.GetBinaryData(); - CurrentSize = CurrentData.Size(); - NextPosition = CurrentPosition + CurrentSize - 1; - + + BytesRead = SourceStream.CurrentPosition(); + Result = DataReader.Read(ChunkSize); + CurrentData = Result.GetBinaryData(); + CurrentSize = CurrentData.Size(); + NextPosition = CurrentPosition + CurrentSize - 1; + If Not ValueIsFilled(CurrentData) Then Break; EndIf; - + StreamHeader = "bytes " + OPI_Tools.NumberToString(CurrentPosition) - + "-" - + OPI_Tools.NumberToString(NextPosition) - + "/" + + "-" + + OPI_Tools.NumberToString(NextPosition) + + "/" + StrTotalSize; - + AdditionalHeaders = New Map; AdditionalHeaders.Insert("Content-Length", OPI_Tools.NumberToString(CurrentSize)); - AdditionalHeaders.Insert("Content-Range" , StreamHeader); - AdditionalHeaders.Insert("Content-Type" , "application/octet-stream"); - + AdditionalHeaders.Insert("Content-Range" , StreamHeader); + AdditionalHeaders.Insert("Content-Type" , "application/octet-stream"); + Response = OPI_Tools.Put(UploadURL, CurrentData, AdditionalHeaders, False, True); - + CheckResult = CheckPartUpload(Response, StrTotalSize, AdditionalHeaders, UploadURL, CurrentPosition); - + If ValueIsFilled(CheckResult) Then Return CheckResult; EndIf; - + KBytes = 1024; - MByte = KBytes * KBytes; + MByte = KBytes * KBytes; Message(OPI_Tools.ProgressInformation(CurrentPosition, TotalSize, "MB", MByte)); - + RunGarbageCollection(); FreeObject(CurrentData); - + EndDo; - + Return Response; - + EndFunction Function CheckPartUpload(Response, StrTotalSize, AdditionalHeaders, UploadURL, CurrentPosition) - - StartOfErrorCodes = 400; - EndOfFailureCodes = 600; + + StartOfErrorCodes = 400; + EndOfFailureCodes = 600; StartOfSuccessCodes = 200; - EndOfSuccessCodes = 300; - Redirection = 308; - + EndOfSuccessCodes = 300; + Redirection = 308; + If Response.StatusCode >= StartOfErrorCodes And Response.StatusCode < EndOfFailureCodes Then - + StreamHeader = "bytes */" + StrTotalSize; AdditionalHeaders.Insert("Content-Range" , StreamHeader); - + CheckResponse = OPI_Tools.Put(UploadURL, "", AdditionalHeaders, False, True); - + If CheckResponse.StatusCode >= StartOfSuccessCodes And CheckResponse.StatusCode < EndOfSuccessCodes Then - + OPI_Tools.ProcessResponse(CheckResponse); Return CheckResponse; - + ElsIf CheckResponse.StatusCode = Redirection Then - + UploadedData = Response.Headers["Range"]; - + Else - + OPI_Tools.ProcessResponse(Response); Return Response; - + EndIf; - + Else UploadedData = Response.Headers["Range"]; EndIf; - + If Not ValueIsFilled(UploadedData) Then OPI_Tools.ProcessResponse(Response); Return Response; EndIf; - - UploadedData = StrReplace(UploadedData, "bytes=", ""); + + UploadedData = StrReplace(UploadedData, "bytes =", ""); ArrayOfInformation = StrSplit(UploadedData, "-", False); - PartsRequired = 2; - + PartsRequired = 2; + If Not ArrayOfInformation.Count() = PartsRequired Then OPI_Tools.ProcessResponse(Response); Return Response; EndIf; - + CurrentPosition = Number(ArrayOfInformation[1]) + 1; - + Return ""; - + EndFunction #EndRegion diff --git a/src/en/OInt/core/Modules/OPI_GoogleSheets.os b/src/en/OInt/core/Modules/OPI_GoogleSheets.os index 5a87bac1b7..19eba68b33 100644 --- a/src/en/OInt/core/Modules/OPI_GoogleSheets.os +++ b/src/en/OInt/core/Modules/OPI_GoogleSheets.os @@ -43,90 +43,90 @@ // Create spreadsheet // Creates a new spreadsheet -// +// // Parameters: // Token - String - Token - token // Name - String - Name - title // ArrayOfSheetNames - Array of String - Array of names to add new sheets to the spreadsheet - sheets -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function CreateSpreadsheet(Val Token, Val Name, Val ArrayOfSheetNames) Export - + OPI_TypeConversion.GetLine(Name); OPI_TypeConversion.GetCollection(ArrayOfSheetNames); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://sheets.googleapis.com/v4/spreadsheets"; - + URL = "https://sheets.googleapis.com/v4/spreadsheets"; + Properties = New Structure("title" , Name); - Sheets = New Array; - + Sheets = New Array; + FillSheetArray(ArrayOfSheetNames, Sheets); - + Parameters = New Structure; OPI_Tools.AddField("properties", Properties, "Collection", Parameters); - OPI_Tools.AddField("sheets" , Sheets , "Collection", Parameters); - + OPI_Tools.AddField("sheets" , Sheets , "Collection", Parameters); + Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction // Get spreadsheet // Gets information about the spreadsheet by ID -// +// // Parameters: // Token - String - Token - token // Identifier - String - Spreadsheet identifier - spreadsheet -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function GetSpreadsheet(Val Token, Val Identifier) Export - OPI_TypeConversion.GetLine(Identifier); - + OPI_TypeConversion.GetLine(Identifier); + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Identifier; - + URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Identifier; + Response = OPI_Tools.Get(URL, , Headers); - + Return Response; EndFunction // Change spreadsheet name // Changes the name of the existing spreadsheet -// +// // Parameters: // Token - String - Token - token // Spreadsheet - String - SpreadsheetID - spreadsheet // Name - String - New name - title -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function EditSpreadsheetTitle(Val Token, Val Spreadsheet, Val Name) Export - + OPI_TypeConversion.GetLine(Spreadsheet); OPI_TypeConversion.GetLine(Name); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Spreadsheet + ":batchUpdate"; - - Change = New Structure("title", Name); + URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Spreadsheet + ":batchUpdate"; + + Change = New Structure("title", Name); ChangeRequest = New Structure("properties,fields", Change, "title"); - Request = New Structure("updateSpreadsheetProperties", ChangeRequest); - + Request = New Structure("updateSpreadsheetProperties", ChangeRequest); + ArrayOfRequests = New Array; ArrayOfRequests.Add(Request); - + Parameters = New Structure("requests", ArrayOfRequests); - + Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction #EndRegion @@ -135,95 +135,95 @@ EndFunction // Add sheet // Adds a new sheet to the spreadsheet -// -// +// +// // Parameters: // Token - String - Token - token // Spreadsheet - String - Spreadsheet identifier - spreadsheet // Name - String - NewSheetName - title -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function AddSheet(Val Token, Val Spreadsheet, Val Name) Export - + OPI_TypeConversion.GetLine(Spreadsheet); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Spreadsheet + ":batchUpdate"; - Sheet = CreateSheet(Name); - + URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Spreadsheet + ":batchUpdate"; + Sheet = CreateSheet(Name); + Requests = New Array; - Change = New Structure("addSheet", Sheet); + Change = New Structure("addSheet", Sheet); Requests.Add(Change); - + Parameters = New Structure("requests", Requests); - + Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction // Delete sheet // Deletes a sheet from the spreadsheet -// +// // Parameters: // Token - String - Token - token // Spreadsheet - String - Spreadsheet identifier - spreadsheet // Sheet - String - IdentifierOfSheetToDelete - sheet -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function DeleteSheet(Val Token, Val Spreadsheet, Val Sheet) Export - + OPI_TypeConversion.GetLine(Spreadsheet); OPI_TypeConversion.GetLine(Sheet); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Spreadsheet + ":batchUpdate"; - + URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Spreadsheet + ":batchUpdate"; + Requests = New Array; - Sheet = New Structure("sheetId" , Sheet); - Change = New Structure("deleteSheet", Sheet); + Sheet = New Structure("sheetId" , Sheet); + Change = New Structure("deleteSheet", Sheet); Requests.Add(Change); - + Parameters = New Structure("requests", Requests); - + Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction // Copy sheet // Copies a sheet from one spreadsheet to another -// +// // Parameters: // Token - String - Token - token // From - String - Source spreadsheet ID - from // Target - String - Destination spreadsheet ID - to // Sheet - String - CopiedSheetID - sheet -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function CopySheet(Val Token, Val From, Val Target, Val Sheet) Export - + OPI_TypeConversion.GetLine(From); OPI_TypeConversion.GetLine(Target); OPI_TypeConversion.GetLine(Sheet); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://sheets.googleapis.com/v4/spreadsheets/" + URL = "https://sheets.googleapis.com/v4/spreadsheets/" + From + "/sheets/" + Sheet + ":copyTo"; - - Parameters = New Structure("destinationSpreadsheetId", Target); - Response = OPI_Tools.Post(URL, Parameters, Headers); - + + Parameters = New Structure("destinationSpreadsheetId", Target); + Response = OPI_Tools.Post(URL, Parameters, Headers); + Return Response; - + EndFunction #EndRegion @@ -232,14 +232,14 @@ EndFunction // Set cell values // Sets sheet cell values -// +// // Parameters: // Token - String - Token - token -// Spreadsheet - String - SpreadsheetID - spreadsheet +// Spreadsheet - String - SpreadsheetID - spreadsheet // ValueMapping - Map Of KeyAndValue - Fill data where the key is the cell name like A1 - data // Sheet - String - Sheet name (first sheet by default) - sheetname // MajorDimension - String - Main dimension when filling the array range - dim -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function SetCellValues(Val Token @@ -247,90 +247,90 @@ Function SetCellValues(Val Token , Val ValueMapping , Val Sheet = "" , Val MajorDimension = "COLUMNS") Export - + OPI_TypeConversion.GetLine(Spreadsheet); OPI_TypeConversion.GetCollection(ValueMapping); - - If Not TypeOf(ValueMapping) = Type("Structure") + + If Not TypeOf(ValueMapping) = Type("Structure") And Not TypeOf(ValueMapping) = Type("Map") Then Return "Failed to convert the structure of values to a collection"; EndIf; - - Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Spreadsheet + "/values:batchUpdate"; + + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); + URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Spreadsheet + "/values:batchUpdate"; DataArray = FormCellDataArray(ValueMapping, MajorDimension, Sheet); Parameters = New Structure("data,valueInputOption", DataArray, "USER_ENTERED"); - Response = OPI_Tools.Post(URL, Parameters, Headers); - + Response = OPI_Tools.Post(URL, Parameters, Headers); + Return Response; - + EndFunction // Clear cells // Clears the value in cells -// +// // Parameters: // Token - String - Token - token // Spreadsheet - String - SpreadsheetID - spreadsheet // CellsArray - Array of String - Array of cells like A1 to be cleared - cells // Sheet - String - Sheet name (first sheet by default) - sheetname -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function ClearCells(Val Token, Val Spreadsheet, Val CellsArray, Val Sheet = "") Export - + OPI_TypeConversion.GetLine(Spreadsheet); OPI_TypeConversion.GetCollection(CellsArray); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Spreadsheet + "/values:batchClear"; - + URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Spreadsheet + "/values:batchClear"; + FormCellNameArray(CellsArray, Sheet); - + Parameters = New Structure("ranges", CellsArray); - Response = OPI_Tools.Post(URL, Parameters, Headers); - + Response = OPI_Tools.Post(URL, Parameters, Headers); + Return Response; - + EndFunction // Get cell values // Gets cell values of the table -// +// // Parameters: // Token - String - Token - token // Spreadsheet - String - SpreadsheetID - spreadsheet // CellsArray - Array of String - Array of A1 type cells to get (whole sheet if not filled) - cells // Sheet - String - Sheet name (first sheet by default) - sheetname -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function GetCellValues(Val Token, Val Spreadsheet, Val CellsArray = "", Val Sheet = "") Export - + OPI_TypeConversion.GetLine(Spreadsheet); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Spreadsheet + "/values:batchGet"; - + URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Spreadsheet + "/values:batchGet"; + If ValueIsFilled(CellsArray) Then - OPI_TypeConversion.GetCollection(CellsArray); + OPI_TypeConversion.GetCollection(CellsArray); FormCellNameArray(CellsArray, Sheet); - - First = True; + + First = True; For Each Cell In CellsArray Do Delimiter = ?(First, "?", "&"); - URL = URL + Delimiter + "ranges=" + Cell; - First = False; + URL = URL + Delimiter + "ranges =" + Cell; + First = False; EndDo; Else - URL = URL + "?ranges='" + Sheet + "'"; + URL = URL + "?ranges ='" + Sheet + "'"; EndIf; - + Response = OPI_Tools.Get(URL, , Headers); - + Return Response; - + EndFunction #EndRegion @@ -340,75 +340,75 @@ EndFunction #Region Private Procedure FillSheetArray(Val ArrayOfNames, SheetArray) - + For Each SheetName In ArrayOfNames Do - + Sheet = CreateSheet(SheetName); SheetArray.Add(Sheet); - + EndDo; EndProcedure Procedure AddSheetName(Cell, Val Sheet) - + If ValueIsFilled(Sheet) Then Cell = "'" + Sheet + "'!" + Cell; EndIf; - + EndProcedure Function CreateSheet(Val Name) - + OPI_TypeConversion.GetLine(Name); - + SheetProperties = New Structure("title" , Name); - Sheet = New Structure("properties", SheetProperties); + Sheet = New Structure("properties", SheetProperties); Return Sheet; - + EndFunction Function FormCellDataArray(Val ValueStructure, Val MajorDimension, Val Sheet) - + OPI_TypeConversion.GetLine(Sheet); - + DataArray = New Array; - + For Each CellData In ValueStructure Do - + CurrentValue = CellData.Value; - CurrentKey = CellData.Key; - + CurrentKey = CellData.Key; + AddSheetName(CurrentKey, Sheet); - + OPI_TypeConversion.GetArray(CurrentValue); - - CurrentData = New Map; + + CurrentData = New Map; CurrentArray = New Array; - + CurrentArray.Add(CurrentValue); - - OPI_Tools.AddField("range" , CurrentKey , "String", CurrentData); - OPI_Tools.AddField("values" , CurrentArray , "Array", CurrentData); + + OPI_Tools.AddField("range" , CurrentKey , "String", CurrentData); + OPI_Tools.AddField("values" , CurrentArray , "Array" , CurrentData); OPI_Tools.AddField("majorDimension", MajorDimension, "String", CurrentData); - + DataArray.Add(CurrentData); - + EndDo; - + Return DataArray; - + EndFunction Procedure FormCellNameArray(Val ArrayOfNames, Val Sheet) - OPI_TypeConversion.GetLine(Sheet); - - For N = 0 To ArrayOfNames.UBound() Do + OPI_TypeConversion.GetLine(Sheet); + + For N = 0 To ArrayOfNames.UBound() Do AddSheetName(ArrayOfNames[N], Sheet); EndDo; - + EndProcedure #EndRegion diff --git a/src/en/OInt/core/Modules/OPI_GoogleWorkspace.os b/src/en/OInt/core/Modules/OPI_GoogleWorkspace.os index 68d509439f..dd6f5187f9 100644 --- a/src/en/OInt/core/Modules/OPI_GoogleWorkspace.os +++ b/src/en/OInt/core/Modules/OPI_GoogleWorkspace.os @@ -41,97 +41,97 @@ // Generate code retrieval link // Returns URL for browser authorization -// +// // Parameters: // ClientID - String - Client ID - id // Calendar - Boolean - Calendar methods permission - calendar // Drive - Boolean - Drive methods permission - drive // Sheets - Boolean - Sheets methods permission - sheets -// +// // Returns: // String - Code retrieval link Function FormCodeRetrievalLink(Val ClientID , Val Calendar = True , Val Drive = True , Val Sheets = True) Export - + OPI_TypeConversion.GetLine(ClientID); OPI_TypeConversion.GetBoolean(Calendar); OPI_TypeConversion.GetBoolean(Sheets); OPI_TypeConversion.GetBoolean(Drive); - + URL = "https://accounts.google.com/o/oauth2/auth"; - + URLParameters = New Structure; URLParameters.Insert("response_type", "code"); - URLParameters.Insert("client_id" , ClientID); + URLParameters.Insert("client_id" , ClientID); URLParameters.Insert("redirect_uri" , "http://localhost"); - URLParameters.Insert("access_type" , "offline"); - URLParameters.Insert("scope" , GetPermissionsList(Calendar, Drive, Sheets)); - + URLParameters.Insert("access_type" , "offline"); + URLParameters.Insert("scope" , GetPermissionsList(Calendar, Drive, Sheets)); + URL = URL + OPI_Tools.RequestParametersToString(URLParameters); - + Return URL; - + EndFunction // Get token by code // Gets token by code from browser authorization -// +// // Parameters: // ClientID - String - Client ID - id // ClientSecret - String - Client secret - secret // Code - String - Code from browser - code -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function GetTokenByCode(Val ClientID, Val ClientSecret, Val Code) Export - + OPI_TypeConversion.GetLine(ClientID); OPI_TypeConversion.GetLine(ClientSecret); OPI_TypeConversion.GetLine(Code); - + URL = "https://accounts.google.com/o/oauth2/token"; - + URLParameters = New Structure; - URLParameters.Insert("grant_type" , "authorization_code"); - URLParameters.Insert("client_id" , ClientID); + URLParameters.Insert("grant_type" , "authorization_code"); + URLParameters.Insert("client_id" , ClientID); URLParameters.Insert("client_secret", ClientSecret); - URLParameters.Insert("redirect_uri" , "http://localhost"); - URLParameters.Insert("code" , Code); - + URLParameters.Insert("redirect_uri" , "http://localhost"); + URLParameters.Insert("code" , Code); + Response = OPI_Tools.Post(URL, URLParameters, , False); - + Return Response; EndFunction // Refresh token // Updates token by Refresh token -// +// // Parameters: // ClientID - String - Client ID - id // ClientSecret - String - Client secret - secret // RefreshToken - String - Refresh token - refresh -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function RefreshToken(Val ClientID, Val ClientSecret, Val RefreshToken) Export - + OPI_TypeConversion.GetLine(ClientID); OPI_TypeConversion.GetLine(ClientSecret); OPI_TypeConversion.GetLine(RefreshToken); - + URL = "https://accounts.google.com/o/oauth2/token"; - + URLParameters = New Structure; - URLParameters.Insert("grant_type" , "refresh_token"); - URLParameters.Insert("client_id" , ClientID); - URLParameters.Insert("client_secret", ClientSecret); + URLParameters.Insert("grant_type" , "refresh_token"); + URLParameters.Insert("client_id" , ClientID); + URLParameters.Insert("client_secret", ClientSecret); URLParameters.Insert("refresh_token", RefreshToken); - + Response = OPI_Tools.Post(URL, URLParameters, , False); - + Return Response; EndFunction @@ -141,14 +141,14 @@ EndFunction #Region Internal Function GetAuthorizationHeader(Val Token) Export - + OPI_TypeConversion.GetLine(Token); - + Headers = New Map; Headers.Insert("Authorization", "Bearer " + Token); - + Return Headers; - + EndFunction #EndRegion @@ -156,23 +156,23 @@ EndFunction #Region ServiceProceduresAndFunctions Function GetPermissionsList(Calendar, Drive, Sheets) - + PermissionsArray = New Array; - + If Calendar Then PermissionsArray.Add("https://www.googleapis.com/auth/calendar"); EndIf; - + If Drive Then PermissionsArray.Add("https://www.googleapis.com/auth/drive"); EndIf; - + If Sheets Then PermissionsArray.Add("https://www.googleapis.com/auth/spreadsheets"); EndIf; - + Return StrConcat(PermissionsArray, " "); - + EndFunction #EndRegion diff --git a/src/en/OInt/core/Modules/OPI_Notion.os b/src/en/OInt/core/Modules/OPI_Notion.os index d6d2623a31..a7ffd1122d 100644 --- a/src/en/OInt/core/Modules/OPI_Notion.os +++ b/src/en/OInt/core/Modules/OPI_Notion.os @@ -45,91 +45,91 @@ // Create page // Creates a child page above another parent page -// +// // Parameters: // Token - String - Token - token // Parent - String - Parent ID - page // Title - String - Page title - title -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Notion Function CreatePage(Val Token, Val Parent, Val Title) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Parent); OPI_TypeConversion.GetLine(Title); - - Headers = CreateRequestHeaders(Token); + + Headers = CreateRequestHeaders(Token); Properties = New Structure; Parameters = New Structure; - + AddPageHeader(Title, Properties); AddPageParent(Parent, False, Parameters); - + Parameters.Insert("properties", Properties); - + Response = OPI_Tools.Post("https://api.notion.com/v1/pages", Parameters, Headers); - + Return Response; - + EndFunction // Create page in database // Creates a page in the parent database -// +// // Parameters: -// Token - String - Token - token +// Token - String - Token - token // Parent - String - Parent database ID - base // Data - Map Of KeyAndValue - Properties map - data -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Notion Function CreatePageInDatabase(Val Token, Val Parent, Val Data) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Parent); OPI_TypeConversion.GetCollection(Data); - - Headers = CreateRequestHeaders(Token); + + Headers = CreateRequestHeaders(Token); Parameters = New Structure; - + AddPageParent(Parent, True, Parameters); - Properties = FillDataBySchema(Parent, Data, Token); + Properties = FillDataBySchema(Parent, Data, Token); Parameters.Insert("properties", Properties); - + Response = OPI_Tools.Post("https://api.notion.com/v1/pages", Parameters, Headers); - + Return Response; - + EndFunction // Get page // Gets information about the page by ID -// +// // Parameters: // Token - String - Token - token -// Page - String - Page ID - page -// +// Page - String - Page ID - page +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Notion Function GetPage(Val Token, Val Page) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Page); - + Headers = CreateRequestHeaders(Token); - ConvertID(Page); - + ConvertID(Page); + Response = OPI_Tools.Get("https://api.notion.com/v1/pages/" + Page, , Headers); - + Return Response; - + EndFunction // Edit page properties // Changes the properties of an existing page -// +// // Parameters: // Token - String - Token - token // Page - String - ID of the page being modified - page @@ -137,7 +137,7 @@ EndFunction // Icon - String - URL of the page icon image - icon // Cover - String - URL of the page cover image - cover // Archived - Boolean - Archive page or not (boolean) - archive -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Notion Function EditPageProperties(Val Token @@ -146,36 +146,36 @@ Function EditPageProperties(Val Token , Val Icon = "" , Val Cover = "" , Val Archived = False) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Page); OPI_TypeConversion.GetLine(Icon); OPI_TypeConversion.GetLine(Cover); OPI_TypeConversion.GetBoolean(Archived); OPI_TypeConversion.GetCollection(Data); - - Headers = CreateRequestHeaders(Token); + + Headers = CreateRequestHeaders(Token); Parameters = New Structure; - Files = "files"; - - If ValueIsFilled(Data) + Files = "files"; + + If ValueIsFilled(Data) And (TypeOf(Data) = Type("Map") Or TypeOf(Data) = Type("Structure")) Then - Properties = FillDataBySchema(Page, Data, Token, False); - Else - Properties = New Map; + Properties = FillDataBySchema(Page, Data, Token, False); + Else + Properties = New Map; EndIf; - + If ValueIsFilled(Icon) Then IconMap = New Map; IconMap.Insert("Icon", Icon); - + IconObject = ConvertValueByType(Files, IconMap); IconObject = IconObject[Files][0]; IconObject.Delete("name"); - + Parameters.Insert("icon", IconObject); EndIf; - + If ValueIsFilled(Cover) Then CoverMap = New Map; CoverMap.Insert("Cover", Cover); @@ -188,14 +188,14 @@ Function EditPageProperties(Val Token EndIf; Parameters.Insert("properties", Properties); - Parameters.Insert("archived" , Archived); - + Parameters.Insert("archived" , Archived); + ConvertID(Page); Response = OPI_Tools.Patch("https://api.notion.com/v1/pages/" + Page, Parameters, Headers); - + Return Response; - + EndFunction #EndRegion @@ -204,13 +204,13 @@ EndFunction // Create database // Creates a database -// +// // Parameters: -// Token - String - Token - token +// Token - String - Token - token // Parent - String - Parent page ID - page // Title - String - Database title - title // Properties - Structure Of String - Database properties - props -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Notion Function CreateDatabase(Val Token, Val Parent, Val Title, Val Properties = "") Export @@ -219,273 +219,273 @@ Function CreateDatabase(Val Token, Val Parent, Val Title, Val Properties = "") E OPI_TypeConversion.GetLine(Parent); OPI_TypeConversion.GetLine(Title); OPI_TypeConversion.GetCollection(Properties); - + // Example structure/property map - + // Name : title // Description : rich_text - // InProgress : checkbox + // InProgress : checkbox // Count : number // Date : date // Status : Map // Active : green // Inactive : red // Archive : yellow - + // All pages created as children must have parent base properties If Not TypeOf(Properties) = Type("Structure") And Not TypeOf(Properties) = Type("Map") Then - Properties = New Structure("Name", "title"); + Properties = New Structure("Name", "title"); EndIf; - Headers = CreateRequestHeaders(Token); + Headers = CreateRequestHeaders(Token); Parameters = New Structure; - + AddDatabaseParent(Parent, False, Parameters); AddDatabaseHeader(Title, Parameters); AddDatabaseProperties(Properties, Parameters); Response = OPI_Tools.Post("https://api.notion.com/v1/databases", Parameters, Headers); - + Return Response; - + EndFunction // Get database // Get database information -// +// // Parameters: // Token - String - Token - token // Base - String - Database ID - base -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Notion Function GetDatabase(Val Token, Val Base) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Base); - + Headers = CreateRequestHeaders(Token); - ConvertID(Base); - + ConvertID(Base); + Response = OPI_Tools.Get("https://api.notion.com/v1/databases/" + Base, , Headers); - - Return Response; - + + Return Response; + EndFunction // Edit database properties // Edits properties of an existing database -// +// // Parameters: // Token - String - Token - token // Base - String - Target database ID - base // Properties - Map of KeyAndValue - New or modified database properties - props // Title - String - New database title - title // Description - String - New database description - description -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Notion Function EditDatabaseProperties(Val Token, Val Base, Val Properties = "", Val Title = "", Val Description = "") Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Base); OPI_TypeConversion.GetLine(Title); OPI_TypeConversion.GetLine(Description); OPI_TypeConversion.GetCollection(Properties); - + Parameters = New Structure; - Headers = CreateRequestHeaders(Token); - ConvertID(Base); - + Headers = CreateRequestHeaders(Token); + ConvertID(Base); + If ValueIsFilled(Title) Then AddDatabaseHeader(Title, Parameters); EndIf; - + If ValueIsFilled(Description) Then AddDatabaseDescription(Description, Parameters); EndIf; - + If TypeOf(Properties) = Type("Structure") Or TypeOf(Properties) = Type("Map") Then AddDatabaseProperties(Properties, Parameters); EndIf; - + Response = OPI_Tools.Patch("https://api.notion.com/v1/databases/" + Base, Parameters, Headers); - + Return Response; - + EndFunction -#EndRegion +#EndRegion #Region BlocksManagment // Create block // Creates a new block based on an existing block -// +// // Parameters: // Token - String - Token - token // Parent - String - Parent block or page ID - page // Block - String, Map Of KeyAndValue - Block ID or block sample itself - block // InsertAfter - String - Block ID after which to insert the new one - prev -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Notion Function CreateBlock(Val Token, Val Parent, Val Block, Val InsertAfter = "") Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Parent); OPI_TypeConversion.GetLine(InsertAfter); OPI_TypeConversion.GetCollection(Block); - + If TypeOf(Block) = Type("Array") Then - Block = Block[0]; + Block = Block[0]; EndIf; - - Headers = CreateRequestHeaders(Token); + + Headers = CreateRequestHeaders(Token); ConvertID(Parent); - + If TypeOf(Block) = Type("String") Then ConvertID(Block); - Block = ReturnBlock(Token, Block); + Block = ReturnBlock(Token, Block); EndIf; - + BlockArray = New Array; BlockArray.Add(Block); - + Parameters = New Map; Parameters.Insert("children", BlockArray); - + If ValueIsFilled(InsertAfter) Then Parameters.Insert("after", InsertAfter); EndIf; - - URL = "https://api.notion.com/v1/blocks/" + Parent + "/children"; + + URL = "https://api.notion.com/v1/blocks/" + Parent + "/children"; Response = OPI_Tools.Patch(URL, Parameters, Headers); - + Return Response; - + EndFunction // Return block // Returns the block structure by ID -// +// // Parameters: // Token - String - Token - token // BlockID - String - Block ID - block // OnlyBase - Boolean - True > service fields are deleted, only the block itself remains - core -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Notion Function ReturnBlock(Val Token, Val BlockID, Val OnlyBase = True) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(BlockID); OPI_TypeConversion.GetBoolean(OnlyBase); - + ConvertID(BlockID); - - Headers = CreateRequestHeaders(Token); + + Headers = CreateRequestHeaders(Token); Response = OPI_Tools.Get("https://api.notion.com/v1/blocks/" + BlockID, , Headers); - + If OnlyBase Then - RemoveExtraBlockFields(Response); + RemoveExtraBlockFields(Response); EndIf; - + Return Response; - + EndFunction // Return child blocks // Returns list of child blocks of parent block -// +// // Parameters: // Token - String - Token - token // BlockID - String - Parent block ID - block -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Notion Function ReturnChildBlocks(Val Token, Val BlockID) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(BlockID); - + ConvertID(BlockID); - - Headers = CreateRequestHeaders(Token); + + Headers = CreateRequestHeaders(Token); Response = OPI_Tools.Get("https://api.notion.com/v1/blocks/" + BlockID + "/children", , Headers); - + Return Response; - + EndFunction // Delete block // Deletes block by ID -// +// // Parameters: // Token - String - Token - token // BlockID - String - Block ID - block -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Notion Function DeleteBlock(Val Token, Val BlockID) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(BlockID); - + ConvertID(BlockID); - - Headers = CreateRequestHeaders(Token); + + Headers = CreateRequestHeaders(Token); Response = OPI_Tools.Delete("https://api.notion.com/v1/blocks/" + BlockID, , Headers); - + Return Response; - + EndFunction - + #EndRegion #Region Users // User list // Returns a list of workspace users -// +// // Parameters: // Token - String - Token - token -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Notion Function UserList(Val Token) Export OPI_TypeConversion.GetLine(Token); - - Headers = CreateRequestHeaders(Token); + + Headers = CreateRequestHeaders(Token); Response = OPI_Tools.Get("https://api.notion.com/v1/users", , Headers); - + Return Response; - + EndFunction // Get user data // Gets user data by ID -// +// // Parameters: // Token - String - Token - token // UserID - String - Target user ID - user -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Notion Function GetUserData(Val Token, Val UserID) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(UserID); - + ConvertID(UserID); - - Headers = CreateRequestHeaders(Token); + + Headers = CreateRequestHeaders(Token); Response = OPI_Tools.Get("https://api.notion.com/v1/users/" + UserID, , Headers); - + Return Response; - + EndFunction #EndRegion @@ -495,183 +495,183 @@ EndFunction #Region Private Function CreateRequestHeaders(Val Token) - + OPI_TypeConversion.GetLine(Token); - + Headers = New Map; Headers.Insert("Authorization" , "Bearer " + Token); Headers.Insert("Notion-Version", "2022-06-28"); - + Return Headers; - + EndFunction Procedure ConvertID(Identifier) - + OPI_TypeConversion.GetLine(Identifier); - + Identifier = StrReplace(Identifier, "-", ""); - + EndProcedure Procedure AddPageParent(Val Parent, Val ParentBase, MainStructure) - + OPI_TypeConversion.GetLine(ParentBase); - + ConvertID(Parent); - + IdentifierField = ?(ParentBase, "database_id", "page_id"); ParentStructure = New Structure(IdentifierField, Parent); MainStructure.Insert("parent", ParentStructure); - + EndProcedure Procedure AddDatabaseParent(Val Parent, Val ParentBase, MainStructure) - + OPI_TypeConversion.GetLine(ParentBase); - + ConvertID(Parent); - + IdentifierField = ?(ParentBase, "database_id", "page_id"); - + ParentStructure = New Structure(); - ParentStructure.Insert("type" , IdentifierField); + ParentStructure.Insert("type" , IdentifierField); ParentStructure.Insert(IdentifierField, Parent); MainStructure.Insert("parent", ParentStructure); - + EndProcedure -Procedure AddPageHeader(Val Title, MainStructure) - +Procedure AddPageHeader(Val Title, MainStructure) + OPI_TypeConversion.GetLine(Title); - + SubordinateStructure = New Structure; - DataStructure = New Structure; - TextStructure = New Structure; - DataArray = New Array; + DataStructure = New Structure; + TextStructure = New Structure; + DataArray = New Array; Title = "title"; - + TextStructure.Insert("content", Title); - TextStructure.Insert("link" , Undefined); - + TextStructure.Insert("link" , Undefined); + DataStructure.Insert("text", TextStructure); DataStructure.Insert("type", "text"); - + DataArray.Add(DataStructure); - - SubordinateStructure.Insert("id" , Title); + + SubordinateStructure.Insert("id" , Title); SubordinateStructure.Insert("type" , Title); - SubordinateStructure.Insert(Title , DataArray); - + SubordinateStructure.Insert(Title , DataArray); + MainStructure.Insert(Title, SubordinateStructure); - + EndProcedure Procedure AddDatabaseHeader(Val Title, MainStructure) - + OPI_TypeConversion.GetLine(Title); - - Title = ConvertHeader(Title); + + Title = ConvertHeader(Title); MainStructure.Insert("title", Title["title"]); - + EndProcedure Procedure AddDatabaseDescription(Val Description, MainStructure) - + OPI_TypeConversion.GetLine(Description); - - Title = ConvertHeader(Description); + + Title = ConvertHeader(Description); MainStructure.Insert("description", Title["title"]); - + EndProcedure Procedure AddDatabaseProperties(Val Properties, MainStructure) - + If Properties.Count() = 0 Then MainStructure.Insert("properties", New Structure); - Return; + Return; EndIf; - + ParameterMap = New Map; - + For Each Property In Properties Do - + If TypeOf(Property.Value) = Type("String") Then - + ParameterMap.Insert(Property.Key, New Structure(Property.Value, New Structure)); - - ElsIf TypeOf(Property.Value) = Type("Structure") + + ElsIf TypeOf(Property.Value) = Type("Structure") Or TypeOf(Property.Value) = Type("Map") Then - + ValueSelection = FormSelectionValues(Property.Value); ParameterMap.Insert(Property.Key, New Structure("select", ValueSelection)); - + Else - + ParameterMap.Insert(Property.Key, Property.Value); - + EndIf; - + EndDo; - + MainStructure.Insert("properties", ParameterMap); - + EndProcedure Function FormSelectionValues(Val VariantStructure) - + OptionArray = New Array; - + For Each Option In VariantStructure Do - + OptionMap = New Map; OptionMap.Insert("name" , Option.Key); OptionMap.Insert("color", Option.Value); - + OptionArray.Add(OptionMap); - + EndDo; - + Return New Structure("options", OptionArray); - + EndFunction Function FillDataBySchema(Val Scheme, Val Data, Val Token, Val ThisIsBase = True) - + If ThisIsBase Then SchemaData = GetDatabase(Token, Scheme); Else - SchemaData = GetPage(Token, Scheme); + SchemaData = GetPage(Token, Scheme); EndIf; - + BaseFields = SchemaData["properties"]; Properties = New Map; - + If ValueIsFilled(BaseFields) Then - + For Each Field In BaseFields Do - + FieldData = Field.Value; FieldType = FieldData["type"]; - + FillableData = Data.Get(Field.Key); - + If FillableData = Undefined Then Continue; EndIf; - + ConvertedData = ConvertValueByType(FieldType, FillableData); - + If ConvertedData = Undefined Then Continue; EndIf; - - Properties.Insert(FieldData["id"], ConvertedData); - + + Properties.Insert(FieldData["id"], ConvertedData); + EndDo; - + EndIf; Return Properties; @@ -679,7 +679,7 @@ Function FillDataBySchema(Val Scheme, Val Data, Val Token, Val ThisIsBase = True EndFunction Procedure RemoveExtraBlockFields(Val Block) - + ExtraArray = New Array; ExtraArray.Add("request_id"); ExtraArray.Add("archived"); @@ -690,22 +690,22 @@ Procedure RemoveExtraBlockFields(Val Block) ExtraArray.Add("parrent"); ExtraArray.Add("last_edited_by"); ExtraArray.Add("id"); - + For Each Field In ExtraArray Do - + If Not Block.Get(Field) = Undefined Then Block.Delete(Field); EndIf; - + EndDo; - + EndProcedure #Region TypeConversion Function ConvertValueByType(Val Type, Val Value) - - If Type = "title" Then + + If Type = "title" Then Return ConvertHeader(Value); ElsIf Type = "rich_text" Then Return ConvertText(Value); @@ -733,42 +733,42 @@ Function ConvertValueByType(Val Type, Val Value) Return ConvertEmail(Value); ElsIf Type = "phone_number" Then Return ConvertPhone(Value); - Else + Else Return Undefined; EndIf; - + EndFunction -Function ConvertHeader(Val Title) - +Function ConvertHeader(Val Title) + DataStructure = New Structure; TextStructure = New Structure; - DataArray = New Array; - + DataArray = New Array; + TextStructure.Insert("content", Title); - TextStructure.Insert("link" , Undefined); - + TextStructure.Insert("link" , Undefined); + DataStructure.Insert("type", "text"); DataStructure.Insert("text", TextStructure); - + DataArray.Add(DataStructure); Return New Structure("title", DataArray); - + EndFunction Function ConvertText(Val Text) - - TextArray = New Array; + + TextArray = New Array; TextStructure = New Structure; - + TextStructure.Insert("type", "text"); TextStructure.Insert("text", New Structure("content", Text)); - + TextArray.Add(TextStructure); - + Return New Structure("rich_text", TextArray); - + EndFunction Function ConvertNumber(Val Number) @@ -776,101 +776,101 @@ Function ConvertNumber(Val Number) EndFunction Function ConvertSelectionOption(Val Option) - + ChoiceStructure = New Structure; ChoiceStructure.Insert("select", New Structure("name", Option)); - + Return ChoiceStructure; - + EndFunction Function ConvertStatus(Val Status) - + StatusStructure = New Structure; StatusStructure.Insert("status", New Structure("name", Status)); - + Return StatusStructure; - + EndFunction Function ConvertMultipleChoice(Val OptionArray) - + ChoiceOptionArray = New Array; - + For Each Option In OptionArray Do ChoiceOptionArray.Add(New Structure("name", Option)); EndDo; - + Return New Structure("multi_select", ChoiceOptionArray); - + EndFunction Function ConvertDate(Val Date) - + DateStructure = New Structure; - - If Date = BegOfDay(Date) Then + + If Date = BegOfDay(Date) Then DateFormat = "DF=yyyy-MM-dd"; Else DateFormat = "ISO8601Datetime"; EndIf; - + Date = Format(Date, DateFormat); DateStructure.Insert("start", Date); - + Return New Structure("date", DateStructure); - + EndFunction -Function ConvertLink(Val Identifier) - +Function ConvertLink(Val Identifier) + LinkArray = New Array; LinkArray.Add(New Structure("id", Identifier)); - + Return New Structure("relation", LinkArray); - + EndFunction Function ConvertUsers(Val IDArray) - + If Not TypeOf(IDArray) = Type("Array") Then - ArrayID_ = New Array; + ArrayID_ = New Array; ArrayID_.Add(IDArray); - IDArray = ArrayID_; + IDArray = ArrayID_; EndIf; - + ArrayOfUsers = New Array; - + For Each Identifier In IDArray Do - + UserStructure = New Structure; UserStructure.Insert("object", "user"); - UserStructure.Insert("id" , Identifier); + UserStructure.Insert("id" , Identifier); ArrayOfUsers.Add(UserStructure); - + EndDo; - + Return New Structure("people", ArrayOfUsers); - + EndFunction Function ConvertFiles(Val FileMapping) - + ArrayOfFiles = New Array; - + For Each File In FileMapping Do - + FileStructure = New Structure; - FileStructure.Insert("type" , "external"); - FileStructure.Insert("name" , File.Key); + FileStructure.Insert("type" , "external"); + FileStructure.Insert("name" , File.Key); FileStructure.Insert("external", New Structure("url", File.Value)); - + ArrayOfFiles.Add(FileStructure); - + EndDo; Return New Structure("files", ArrayOfFiles); - + EndFunction Function ConvertBoolean(Val Boolean) diff --git a/src/en/OInt/core/Modules/OPI_Slack.os b/src/en/OInt/core/Modules/OPI_Slack.os index a327db66ca..d960da41c2 100644 --- a/src/en/OInt/core/Modules/OPI_Slack.os +++ b/src/en/OInt/core/Modules/OPI_Slack.os @@ -43,57 +43,57 @@ // Get bot information // Gets basic information about the bot -// +// // Parameters: // Token - String - Bot token - token -// +// // Returns: -// Map Of KeyAndValue - Serialized JSON response from Slack +// Map Of KeyAndValue - Serialized JSON response from Slack Function GetBotInformation(Val Token) Export - - URL = "https://slack.com/api/auth.test"; + + URL = "https://slack.com/api/auth.test"; Headers = GetAuthorizationHeader(Token); - + Response = OPI_Tools.Get(URL, , Headers); - + Return Response; EndFunction // Get workspace list // Gets a list of workspaces where the bot is connected -// +// // Parameters: // Token - String - Bot token - token // Cursor - String - Pointer from the previous request, if the result rows > 100 - cursor -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function GetWorkspaceList(Val Token, Val Cursor = "") Export - - URL = "https://slack.com/api/auth.teams.list"; + + URL = "https://slack.com/api/auth.teams.list"; Response = GeneralDataRetrieval(Token, URL, Cursor); - + Return Response; EndFunction // Get user list // Gets a list of users in the workspace -// +// // Parameters: // Token - String - Bot token - token // Cursor - String - Pointer from the previous request, if the result rows > 100 - cursor -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function GetUserList(Val Token, Val Cursor = "") Export - - URL = "https://slack.com/api/users.list"; + + URL = "https://slack.com/api/users.list"; Response = GeneralDataRetrieval(Token, URL, Cursor); - + Return Response; - + EndFunction #EndRegion @@ -102,68 +102,68 @@ EndFunction // Send message // Sends a message at a selected hour -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel // Text - String - Message text - text -// SendingDate - Date - Sending date for delayed message - date +// SendingDate - Date - Sending date for delayed message - date // Blocks - Array of Structure - Array of block descriptions - blocks - JSON array of block descriptions -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function SendMessage(Val Token, Val Channel, Val Text = "", Val SendingDate = "", Val Blocks = "") Export - + String_ = "String"; - HasDate = ValueIsFilled(SendingDate); + HasDate = ValueIsFilled(SendingDate); Headers = GetAuthorizationHeader(Token); - + If ValueIsFilled(Blocks) And TypeOf(Blocks) = Type(String_) Then OPI_TypeConversion.GetCollection(Blocks); - + If TypeOf(Blocks) = Type("Array") Then - + For N = 0 To Blocks.UBound() Do - OPI_TypeConversion.GetCollection(Blocks[N]); + OPI_TypeConversion.GetCollection(Blocks[N]); EndDo; - + EndIf; EndIf; - + Parameters = New Structure; OPI_Tools.AddField("channel", Channel, String_ , Parameters); - OPI_Tools.AddField("text" , Text, String_ , Parameters); - OPI_Tools.AddField("blocks" , Blocks, "Array" , Parameters); + OPI_Tools.AddField("text" , Text , String_ , Parameters); + OPI_Tools.AddField("blocks" , Blocks , "Array" , Parameters); If HasDate Then - + URL = "https://slack.com/api/chat.scheduleMessage"; - OPI_Tools.AddField("post_at", SendingDate, "Date", Parameters); - + OPI_Tools.AddField("post_at", SendingDate, "Date", Parameters); + Else - + URL = "https://slack.com/api/chat.postMessage"; - + EndIf; - + Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Send ephemeral message -// Sends a message that arrives in the channel but is visible +// Sends a message that arrives in the channel but is visible // only to a specific user -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel // Text - String - Message text - text -// User - String - User ID - user +// User - String - User ID - user // Blocks - Array of Structure - Array of block descriptions - blocks - JSON array of block descriptions -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function SendEphemeralMessage(Val Token @@ -171,168 +171,168 @@ Function SendEphemeralMessage(Val Token , Val Text = "" , Val User = "" , Val Blocks = "") Export - + String_ = "String"; - + If ValueIsFilled(Blocks) And Not TypeOf(Blocks) = Type(String_) Then OPI_TypeConversion.GetArray(Blocks); EndIf; - + Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; - OPI_Tools.AddField("channel", Channel , String_ , Parameters); - OPI_Tools.AddField("text" , Text , String_ , Parameters); - OPI_Tools.AddField("user" , User, String_ , Parameters); - OPI_Tools.AddField("blocks" , Blocks , "Collection", Parameters); - + OPI_Tools.AddField("channel", Channel , String_ , Parameters); + OPI_Tools.AddField("text" , Text , String_ , Parameters); + OPI_Tools.AddField("user" , User , String_ , Parameters); + OPI_Tools.AddField("blocks" , Blocks , "Collection", Parameters); + URL = "https://slack.com/api/chat.postEphemeral"; - + Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Edit message // Edits the content of an existing message -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel // Timestamp - String - Message timestamp - stamp // Text - String - New message text - text // BlockArray - Array of Structure - Array of block descriptions - blocks - JSON array of block descriptions -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function EditMessage(Val Token, Val Channel, Val Timestamp, Val Text = "", Val BlockArray = "") Export - + String_ = "String"; - URL = "https://slack.com/api/chat.update"; + URL = "https://slack.com/api/chat.update"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; - OPI_Tools.AddField("channel", Channel , String_ , Parameters); - OPI_Tools.AddField("text" , Text , String_ , Parameters); - OPI_Tools.AddField("ts" , Timestamp , String_ , Parameters); + OPI_Tools.AddField("channel", Channel , String_ , Parameters); + OPI_Tools.AddField("text" , Text , String_ , Parameters); + OPI_Tools.AddField("ts" , Timestamp , String_ , Parameters); OPI_Tools.AddField("blocks" , BlockArray, "Collection", Parameters); - + Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Delete message // Deletes a channel message by timestamp -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel // Timestamp - String - Timestamp or message ID - stamp // IsDelayed - Boolean - Indicator of deleting a delayed message - issheduled -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function DeleteMessage(Val Token, Val Channel, Val Timestamp, Val IsDelayed = False) Export - + OPI_TypeConversion.GetBoolean(IsDelayed); - + Headers = GetAuthorizationHeader(Token); - + If IsDelayed Then - URL = "https://slack.com/api/chat.deleteScheduledMessage"; - TimestampField = "scheduled_message_id"; + URL = "https://slack.com/api/chat.deleteScheduledMessage"; + TimestampField = "scheduled_message_id"; Else - URL = "https://slack.com/api/chat.delete"; + URL = "https://slack.com/api/chat.delete"; TimestampField = "ts"; EndIf; - + Parameters = New Structure; - OPI_Tools.AddField("channel" , Channel , "String", Parameters); + OPI_Tools.AddField("channel" , Channel , "String", Parameters); OPI_Tools.AddField(TimestampField, Timestamp, "String", Parameters); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction // Get list of delayed messages // Gets a list of delayed channel messages -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel // Cursor - String - Pointer from the previous request, if the result rows > 100 - cursor -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function GetDelayedMessageList(Val Token, Val Channel, Val Cursor = "") Export - - URL = "https://slack.com/api/chat.scheduledMessages.list"; + + URL = "https://slack.com/api/chat.scheduledMessages.list"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; OPI_Tools.AddField("channel", Channel , "String", Parameters); - OPI_Tools.AddField("cursor" , Cursor, "String", Parameters); - + OPI_Tools.AddField("cursor" , Cursor , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction // Get message link // Gets a permanent URL to the channel message -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel // Timestamp - String - Timestamp or message ID - stamp -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function GetMessageLink(Val Token, Val Channel, Val Timestamp) Export - - URL = "https://slack.com/api/chat.getPermalink"; + + URL = "https://slack.com/api/chat.getPermalink"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; - OPI_Tools.AddField("channel" , Channel , "String", Parameters); + OPI_Tools.AddField("channel" , Channel , "String", Parameters); OPI_Tools.AddField("message_ts", Timestamp, "String", Parameters); Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; EndFunction // Get list of message replies // Gets an array of messages that are replies to the specified -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel // Timestamp - String - Timestamp or message ID - stamp // Cursor - String - Pointer from the previous request, if the result rows > 100 - cursor -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function GetMessageReplyList(Val Token, Val Channel, Val Timestamp, Val Cursor = "") Export - + String_ = "String"; - URL = "https://slack.com/api/conversations.replies"; + URL = "https://slack.com/api/conversations.replies"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; - OPI_Tools.AddField("channel", Channel , String_, Parameters); - OPI_Tools.AddField("cursor" , Cursor , String_, Parameters); - OPI_Tools.AddField("ts" , Timestamp, String_, Parameters); - + OPI_Tools.AddField("channel", Channel , String_, Parameters); + OPI_Tools.AddField("cursor" , Cursor , String_, Parameters); + OPI_Tools.AddField("ts" , Timestamp, String_, Parameters); + Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; EndFunction @@ -343,108 +343,108 @@ EndFunction // Get channel list // Gets a list of available channels -// +// // Parameters: // Token - String - Bot token - token -// ExcludeArchived - Boolean - Indicator of excluding archived channels - notarchived +// ExcludeArchived - Boolean - Indicator of excluding archived channels - notarchived // Cursor - String - Pointer from the previous request, if the result rows > 100 - cursor -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function GetChannelList(Val Token, Val ExcludeArchived = False, Val Cursor = "") Export - - URL = "https://slack.com/api/conversations.list"; + + URL = "https://slack.com/api/conversations.list"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; OPI_Tools.AddField("exclude_archived", ExcludeArchived, "Boolean", Parameters); - OPI_Tools.AddField("cursor" , Cursor , "String", Parameters); + OPI_Tools.AddField("cursor" , Cursor , "String" , Parameters); Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; - + EndFunction // Get channel user list // Gets a list of users in the specified channel -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel // Cursor - String - Pointer from the previous request, if the result rows > 100 - cursor -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function GetChannelUserList(Val Token, Val Channel, Val Cursor = "") Export - - URL = "https://slack.com/api/conversations.members"; + + URL = "https://slack.com/api/conversations.members"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; OPI_Tools.AddField("channel", Channel , "String", Parameters); - OPI_Tools.AddField("cursor" , Cursor, "String", Parameters); + OPI_Tools.AddField("cursor" , Cursor , "String", Parameters); Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; EndFunction // Create channel // Creates a new channel -// +// // Parameters: // Token - String - Bot token - token // Name - String - Channel name - title // Private - Boolean - Create channel as private - private -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function CreateChannel(Val Token, Val Name, Val Private = False) Export - - URL = "https://slack.com/api/conversations.create"; + + URL = "https://slack.com/api/conversations.create"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; - OPI_Tools.AddField("name" , Name , "String", Parameters); + OPI_Tools.AddField("name" , Name , "String" , Parameters); OPI_Tools.AddField("is_private", Private, "Boolean", Parameters); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Archive channel // Archives an active channel -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function ArchiveChannel(Val Token, Val Channel) Export - - URL = "https://slack.com/api/conversations.archive"; + + URL = "https://slack.com/api/conversations.archive"; Response = DialogManagement(Token, Channel, URL); Return Response; - + EndFunction // Get channel // Gets information about the channel -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function GetChannel(Val Token, Val Channel) Export - - URL = "https://slack.com/api/conversations.info"; + + URL = "https://slack.com/api/conversations.info"; Response = DialogManagement(Token, Channel, URL, "GET"); Return Response; @@ -452,16 +452,16 @@ EndFunction // Get channel history // Gets information about channel events -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function GetChannelHistory(Val Token, Val Channel) Export - - URL = "https://slack.com/api/conversations.history"; + + URL = "https://slack.com/api/conversations.history"; Response = DialogManagement(Token, Channel, URL, "GET"); Return Response; @@ -469,69 +469,69 @@ EndFunction // Invite users to channel // Adds specified users to the channel -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel // ArrayOfUsers - Array Of String - User ID Array - users -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function InviteUsersToChannel(Val Token, Val Channel, Val ArrayOfUsers) Export - - URL = "https://slack.com/api/conversations.invite"; + + URL = "https://slack.com/api/conversations.invite"; Headers = GetAuthorizationHeader(Token); - + OPI_TypeConversion.GetCollection(ArrayOfUsers); ArrayOfUsers = StrConcat(ArrayOfUsers, ","); - + Parameters = New Structure; - OPI_Tools.AddField("channel", Channel , "String", Parameters); - OPI_Tools.AddField("users" , ArrayOfUsers, "String", Parameters); + OPI_Tools.AddField("channel", Channel , "String", Parameters); + OPI_Tools.AddField("users" , ArrayOfUsers, "String", Parameters); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction // Kick user from channel // Removes specified user from channel -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel // User - String - User ID - user -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function KickUserFromChannel(Val Token, Val Channel, Val User) Export - - URL = "https://slack.com/api/conversations.kick"; + + URL = "https://slack.com/api/conversations.kick"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; OPI_Tools.AddField("channel", Channel , "String", Parameters); - OPI_Tools.AddField("user" , User, "String", Parameters); + OPI_Tools.AddField("user" , User , "String", Parameters); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction // Join channel // Adds the current bot to the channel -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function JoinChannel(Val Token, Val Channel) Export - - URL = "https://slack.com/api/conversations.join"; + + URL = "https://slack.com/api/conversations.join"; Response = DialogManagement(Token, Channel, URL); Return Response; @@ -539,16 +539,16 @@ EndFunction // Leave channel // Removes the current bot from the channel -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function LeaveChannel(Val Token, Val Channel) Export - - URL = "https://slack.com/api/conversations.leave"; + + URL = "https://slack.com/api/conversations.leave"; Response = DialogManagement(Token, Channel, URL); Return Response; @@ -556,75 +556,75 @@ EndFunction // Set channel topic // Sets the channel topic -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel // Topic - String - Channel topic - theme -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function SetChannelTopic(Val Token, Val Channel, Val Topic) Export - - URL = "https://slack.com/api/conversations.setTopic"; + + URL = "https://slack.com/api/conversations.setTopic"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; OPI_Tools.AddField("channel", Channel , "String", Parameters); - OPI_Tools.AddField("topic" , Topic , "String", Parameters); + OPI_Tools.AddField("topic" , Topic , "String", Parameters); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction // Set channel purpose // Sets the channel purpose (description) -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel // Purpose - String - Channel purpose - purpose -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function SetChannelGoal(Val Token, Val Channel, Val Purpose) Export - - URL = "https://slack.com/api/conversations.setPurpose"; + + URL = "https://slack.com/api/conversations.setPurpose"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; OPI_Tools.AddField("channel", Channel , "String", Parameters); OPI_Tools.AddField("purpose", Purpose , "String", Parameters); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction // Rename channel // Changes the name of the channel -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel // Name - String - New channel name - title -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function RenameChannel(Val Token, Val Channel, Val Name) Export - - URL = "https://slack.com/api/conversations.rename"; + + URL = "https://slack.com/api/conversations.rename"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; OPI_Tools.AddField("channel", Channel , "String", Parameters); - OPI_Tools.AddField("name" , Name, "String", Parameters); + OPI_Tools.AddField("name" , Name , "String", Parameters); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction @@ -635,45 +635,45 @@ EndFunction // Open dialog // Opens a new dialog with one or more users -// +// // Parameters: // Token - String - Bot token - token // ArrayOfUsers - Array of String - User ID Array - users -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function OpenDialog(Val Token, Val ArrayOfUsers) Export - - URL = "https://slack.com/api/conversations.open"; + + URL = "https://slack.com/api/conversations.open"; Headers = GetAuthorizationHeader(Token); - + OPI_TypeConversion.GetCollection(ArrayOfUsers); ArrayOfUsers = StrConcat(ArrayOfUsers, ","); - + Parameters = New Structure; OPI_Tools.AddField("users", ArrayOfUsers, "String", Parameters); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction // Close dialog // Closes an existing dialog -// +// // Parameters: // Token - String - Bot token - token // Dialog - String - Dialog ID - conv -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function CloseDialog(Val Token, Val Dialog) Export - - URL = "https://slack.com/api/conversations.close"; + + URL = "https://slack.com/api/conversations.close"; Response = DialogManagement(Token, Dialog, URL); Return Response; - + EndFunction #EndRegion @@ -682,154 +682,154 @@ EndFunction // Get list of files // Gets a list of files of the bot or channel -// +// // Parameters: // Token - String - Bot token - token -// Channel - String - Channel for selection - channel +// Channel - String - Channel for selection - channel // PageNumber - Number, String - Page number - page -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function GetFilesList(Val Token, Val Channel = "", Val PageNumber = 1) Export - - URL = "https://slack.com/api/files.list"; + + URL = "https://slack.com/api/files.list"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; - OPI_Tools.AddField("channel", Channel , "String", Parameters); - OPI_Tools.AddField("page" , PageNumber, "String", Parameters); + OPI_Tools.AddField("channel", Channel , "String", Parameters); + OPI_Tools.AddField("page" , PageNumber, "String", Parameters); Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; - + EndFunction // Upload file // Uploads a file to Slack servers -// +// // Parameters: // Token - String - Bot token - token // File - String, BinaryData - File for upload - file // FileName - String - File name with extension - filename // Title - String - File name in Slack - title // Channel - String - Channel ID - channel -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function UploadFile(Val Token, Val File, Val FileName, Val Title, Val Channel = "") Export - + OPI_TypeConversion.GetBinaryData(File); OPI_TypeConversion.GetLine(FileName); OPI_TypeConversion.GetLine(Title); - - String_ = "String"; + + String_ = "String"; Upload_url = "upload_url"; - File_id = "file_id"; - URL = "https://slack.com/api/files.getUploadURLExternal"; - Headers = GetAuthorizationHeader(Token); - Size = File.Size(); - + File_id = "file_id"; + URL = "https://slack.com/api/files.getUploadURLExternal"; + Headers = GetAuthorizationHeader(Token); + Size = File.Size(); + Parameters = New Structure; OPI_Tools.AddField("filename", FileName, String_, Parameters); - OPI_Tools.AddField("length" , Size , String_, Parameters); + OPI_Tools.AddField("length" , Size , String_, Parameters); - Response = OPI_Tools.Get(URL, Parameters, Headers); - URL = Response[Upload_url]; + Response = OPI_Tools.Get(URL, Parameters, Headers); + URL = Response[Upload_url]; Identifier = Response[File_id]; - + If Not ValueIsFilled(URL) Or Not ValueIsFilled(Identifier) Then Return Response; EndIf; - + Files = New Map; Files.Insert(FileName, File); - - Response = OPI_Tools.PostMultipart(URL, , Files, , Headers); - URL = "https://slack.com/api/files.completeUploadExternal"; - SlackFile = New Structure("id, title", Identifier, Title); - + + Response = OPI_Tools.PostMultipart(URL, , Files, , Headers); + URL = "https://slack.com/api/files.completeUploadExternal"; + SlackFile = New Structure("id, title", Identifier, Title); + Parameters = New Structure; - OPI_Tools.AddField("filename" , FileName, String_, Parameters); - OPI_Tools.AddField("channel_id", Channel , String_, Parameters); - OPI_Tools.AddField("files" , SlackFile, "Array", Parameters); + OPI_Tools.AddField("filename" , FileName , String_, Parameters); + OPI_Tools.AddField("channel_id", Channel , String_, Parameters); + OPI_Tools.AddField("files" , SlackFile, "Array", Parameters); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Get file data // Gets information about the file -// +// // Parameters: // Token - String - Bot token - token // FileID - String - File identifier - fileid -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function GetFileData(Val Token, Val FileID) Export - - URL = "https://slack.com/api/files.info"; + + URL = "https://slack.com/api/files.info"; Response = FileManagement(Token, FileID, URL, "GET"); - + Return Response; - + EndFunction // Delete file // Deletes a file on Slack -// +// // Parameters: // Token - String - Bot token - token // FileID - String - File identifier - fileid -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function DeleteFile(Val Token, Val FileID) Export - - URL = "https://slack.com/api/files.delete"; + + URL = "https://slack.com/api/files.delete"; Response = FileManagement(Token, FileID, URL); - + Return Response; - + EndFunction // Make file public // Creates a public URL for the file. Requires user token -// +// // Parameters: // Token - String - User token - token // FileID - String - File identifier - fileid -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function MakeFilePublic(Val Token, Val FileID) Export - - URL = "https://slack.com/api/files.sharedPublicURL"; + + URL = "https://slack.com/api/files.sharedPublicURL"; Response = FileManagement(Token, FileID, URL); - + Return Response; - + EndFunction // Make file private // Removes the public URL from the file. Requires user token -// +// // Parameters: // Token - String - User token - token // FileID - String - File identifier - fileid -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function MakeFilePrivate(Val Token, Val FileID) Export - - URL = "https://slack.com/api/files.revokePublicURL"; + + URL = "https://slack.com/api/files.revokePublicURL"; Response = FileManagement(Token, FileID, URL); - + Return Response; - + EndFunction #EndRegion @@ -838,119 +838,119 @@ EndFunction // Get list of external files // Gets a list of external files of a user or channel -// +// // Parameters: // Token - String - Bot token - token -// Channel - String - Channel for selection - channel +// Channel - String - Channel for selection - channel // Cursor - String - Pointer from the previous request, if the result rows > 100 - cursor -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function GetExternalFileList(Val Token, Val Channel = "", Val Cursor = "") Export - - URL = "https://slack.com/api/files.remote.list"; + + URL = "https://slack.com/api/files.remote.list"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; OPI_Tools.AddField("channel", Channel , "String", Parameters); - OPI_Tools.AddField("cursor" , Cursor, "String", Parameters); + OPI_Tools.AddField("cursor" , Cursor , "String", Parameters); Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; - + EndFunction // Get external file // Gets information about the external file -// +// // Parameters: // Token - String - Bot token - token // FileID - String - File identifier - fileid -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function GetExternalFile(Val Token, Val FileID) Export - - URL = "https://slack.com/api/files.remote.info"; + + URL = "https://slack.com/api/files.remote.info"; Response = ExternalFileManagement(Token, FileID, URL); - + Return Response; - + EndFunction // Add external file // Adds a new external file -// +// // Parameters: // Token - String - Bot token - token // URL - String - URL to external file - url // Title - String - File title for Slack - title -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function AddExternalFile(Val Token, Val URL, Val Title) Export - + String_ = "String"; - URL = "https://slack.com/api/files.remote.add"; + URL = "https://slack.com/api/files.remote.add"; Headers = GetAuthorizationHeader(Token); - UID = String(New UUID()); - + UID = String(New UUID()); + Parameters = New Structure; - OPI_Tools.AddField("external_url", URL , String_, Parameters); - OPI_Tools.AddField("external_id" , UID , String_, Parameters); - OPI_Tools.AddField("title" , Title , String_, Parameters); + OPI_Tools.AddField("external_url", URL , String_, Parameters); + OPI_Tools.AddField("external_id" , UID , String_, Parameters); + OPI_Tools.AddField("title" , Title , String_, Parameters); Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; - + EndFunction // Send external file // Sends an external file to a list of channels -// +// // Parameters: // Token - String - Bot token - token // FileID - String - File identifier - fileid // ChannelArray - Array Of String - Array of channels for sending - channels -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function SendExternalFile(Val Token, Val FileID, Val ChannelArray) Export - - URL = "https://slack.com/api/files.remote.share"; + + URL = "https://slack.com/api/files.remote.share"; Headers = GetAuthorizationHeader(Token); - + OPI_TypeConversion.GetCollection(ChannelArray); ChannelArray = StrConcat(ChannelArray, ","); - + Parameters = New Structure; - OPI_Tools.AddField("file" , FileID , "String", Parameters); + OPI_Tools.AddField("file" , FileID , "String", Parameters); OPI_Tools.AddField("channels", ChannelArray , "String", Parameters); Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; - + EndFunction // Delete external file // Deletes an external file from Slack -// +// // Parameters: // Token - String - Bot token - token // FileID - String - File identifier - fileid -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function DeleteExternalFile(Val Token, Val FileID) Export - - URL = "https://slack.com/api/files.remote.remove"; + + URL = "https://slack.com/api/files.remote.remove"; Response = ExternalFileManagement(Token, FileID, URL); - + Return Response; - + EndFunction #EndRegion @@ -959,24 +959,24 @@ EndFunction // Generate image block // Generates a block with an image to add to the message block array -// +// // Parameters: // URL - String - Image URL - picture // AlternateText - String - Alternate text of the image - alt -// +// // Returns: // Map Of KeyAndValue - Image block Function GenerateImageBlock(Val URL, Val AlternateText = "") Export - + String_ = "String"; - + Block = New Map; - OPI_Tools.AddField("type" , "image" , String_, Block); - OPI_Tools.AddField("image_url", URL , String_, Block); + OPI_Tools.AddField("type" , "image" , String_, Block); + OPI_Tools.AddField("image_url", URL , String_, Block); OPI_Tools.AddField("alt_text" , AlternateText , String_, Block); - + Return Block; - + EndFunction #EndRegion @@ -988,43 +988,43 @@ EndFunction Function GetAuthorizationHeader(Val Token) OPI_TypeConversion.GetLine(Token); - + Headers = New Map; Headers.Insert("Authorization", "Bearer " + Token); Return Headers; - + EndFunction Function DialogManagement(Val Token, Val Channel, Val URL, Val RequestType = "POST") - - Headers = GetAuthorizationHeader(Token); + + Headers = GetAuthorizationHeader(Token); RequestType = Upper(RequestType); - + Parameters = New Structure; OPI_Tools.AddField("channel", Channel, "String", Parameters); If RequestType = "POST" Then - Response = OPI_Tools.Post(URL, Parameters, Headers); + Response = OPI_Tools.Post(URL, Parameters, Headers); Else - Response = OPI_Tools.Get(URL, Parameters, Headers); + Response = OPI_Tools.Get(URL, Parameters, Headers); EndIf; - + Return Response; - + EndFunction Function FileManagement(Val Token, Val FileID, Val URL, Val RequestType = "POST") - - Headers = GetAuthorizationHeader(Token); + + Headers = GetAuthorizationHeader(Token); RequestType = Upper(RequestType); - + Parameters = New Structure; OPI_Tools.AddField("file", FileID , "String", Parameters); If RequestType = "POST" Then - Response = OPI_Tools.Post(URL, Parameters, Headers); + Response = OPI_Tools.Post(URL, Parameters, Headers); Else - Response = OPI_Tools.Get(URL, Parameters, Headers); + Response = OPI_Tools.Get(URL, Parameters, Headers); EndIf; Return Response; @@ -1032,29 +1032,29 @@ Function FileManagement(Val Token, Val FileID, Val URL, Val RequestType = "POST" EndFunction Function GeneralDataRetrieval(Val Token, Val URL, Val Cursor) - + Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; OPI_Tools.AddField("cursor", Cursor, "String", Parameters); - + Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; - + EndFunction Function ExternalFileManagement(Val Token, Val FileID, Val URL) - + Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; OPI_Tools.AddField("file", FileID , "String", Parameters); Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; - + EndFunction #EndRegion diff --git a/src/en/OInt/core/Modules/OPI_Telegram.os b/src/en/OInt/core/Modules/OPI_Telegram.os index d931d5f64f..78067a6274 100644 --- a/src/en/OInt/core/Modules/OPI_Telegram.os +++ b/src/en/OInt/core/Modules/OPI_Telegram.os @@ -47,19 +47,19 @@ // Get bot information // Executes the /getMe request, returning basic bot information: name, id, ability to add the bot to groups, etc.. -// +// // Parameters: // Token - String - Bot token - token -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function GetBotInformation(Val Token) Export OPI_TypeConversion.GetLine(Token); - - URL = "api.telegram.org/bot" + Token + "/getMe"; + + URL = "api.telegram.org/bot" + Token + "/getMe"; Response = OPI_Tools.Get(URL); - + Return Response; EndFunction @@ -71,119 +71,119 @@ EndFunction // Token - String - Bot token - token // Timeout - String, Number - Waiting time for new events - timeout // Offset - String, Number - Offset in the list of received messages - offset -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function GetUpdates(Val Token, Val Timeout = 0, Val Offset = "") Export OPI_TypeConversion.GetLine(Token); - + URL = "api.telegram.org/bot" + Token + "/getUpdates"; - + Parameters = New Structure; OPI_Tools.AddField("timeout", Timeout , "String", Parameters); - OPI_Tools.AddField("offset" , Offset, "String", Parameters); - + OPI_Tools.AddField("offset" , Offset , "String", Parameters); + Response = OPI_Tools.Get(URL, Parameters); Return Response; EndFunction // Set Webhook -// Set webhook URL for bot event handling in webhook mode -// +// Set webhook URL for bot event handling in webhook mode +// // Parameters: // Token - String - Bot token - token // URL - String - Request handling address from Telegram (with https:) - url -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function SetWebhook(Val Token, Val URL) Export OPI_TypeConversion.GetLine(Token); - + Parameters = New Structure; OPI_Tools.AddField("url", URL, "String", Parameters); - URL = "api.telegram.org/bot" + Token + "/setWebHook"; + URL = "api.telegram.org/bot" + Token + "/setWebHook"; Response = OPI_Tools.Get(URL, Parameters); - + Return Response; EndFunction // Delete webhook // Deletes the bot event handler URL for webhook operation -// +// // Parameters: // Token - String - Bot token - token -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function DeleteWebhook(Val Token) Export OPI_TypeConversion.GetLine(Token); - - URL = "api.telegram.org/bot" + Token + "/deleteWebHook"; + + URL = "api.telegram.org/bot" + Token + "/deleteWebHook"; Response = OPI_Tools.Get(URL); - + Return Response; EndFunction // Download file // Download file from Telegram servers -// +// // Parameters: // Token - String - Token - token // FileID - String - File ID for downloading - fileid -// +// // Returns: // BinaryData - file's binary data Function DownloadFile(Val Token, Val FileID) Export Result = "result"; - - OPI_TypeConversion.GetLine(Token); - OPI_TypeConversion.GetLine(FileID); - + + OPI_TypeConversion.GetLine(Token); + OPI_TypeConversion.GetLine(FileID); + Parameters = New Structure("file_id", FileID); - URL = "api.telegram.org/bot" + Token + "/getFile"; + URL = "api.telegram.org/bot" + Token + "/getFile"; Response = OPI_Tools.Get(URL, Parameters); - + Path = Response[Result]["file_path"]; - + If Not ValueIsFilled(Path) Then Return Response; EndIf; - - URL = "api.telegram.org/file/bot" + Token + "/" + Path; + + URL = "api.telegram.org/file/bot" + Token + "/" + Path; Response = OPI_Tools.Get(URL, Parameters); - - Return Response; - + + Return Response; + EndFunction // Process Telegram Mini App data // Processes TMA data and determines its validity -// +// // Parameters: // DataString - String - Query from Telegram.WebApp.initData // Token - String - Bot token -// +// // Returns: // Map of String - Map of data with the result of verification in the passed field Function ProcessTMAData(Val DataString, Val Token) Export OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(DataString); - - DataString = DecodeString(DataString, StringEncodingMethod.URLencoding); + + DataString = DecodeString(DataString, StringEncodingMethod.URLencoding); DataStructure = OPI_Tools.RequestParametersToMap(DataString); - KeyString = "WebAppData"; - Hash = ""; - BinaryKey = GetBinaryDataFromString(KeyString); + KeyString = "WebAppData"; + Hash = ""; + BinaryKey = GetBinaryDataFromString(KeyString); Result = OPI_Cryptography.HMACSHA256(BinaryKey, GetBinaryDataFromString(Token)); @@ -193,8 +193,8 @@ Function ProcessTMAData(Val DataString, Val Token) Export For Each Data In DataStructure Do - NewLine = TValue.Add(); - NewLine.Key = Data.Key; + NewLine = TValue.Add(); + NewLine.Key = Data.Key; NewLine.Value = Data.Value; EndDo; @@ -202,12 +202,12 @@ Function ProcessTMAData(Val DataString, Val Token) Export TValue.Sort("Key"); ReturnMapping = New Map; - DCS = ""; + DCS = ""; For Each DataString In TValue Do If DataString.Key <> "hash" Then - DCS = DCS + DataString.Key + "=" + DataString.Value + Chars.LF; + DCS = DCS + DataString.Key + " =" + DataString.Value + Chars.LF; ReturnMapping.Insert(DataString.Key, DataString.Value); Else Hash = DataString.Value; @@ -215,12 +215,12 @@ Function ProcessTMAData(Val DataString, Val Token) Export EndDo; - DCS = Left(DCS, StrLen(DCS) - 1); + DCS = Left(DCS, StrLen(DCS) - 1); Signature = OPI_Cryptography.HMACSHA256(Result, GetBinaryDataFromString(DCS)); Final = GetHexStringFromBinaryData(Signature); - If Final = Upper(Hash) Then + If Final = Upper(Hash) Then Response = True; Else Response = False; @@ -238,7 +238,7 @@ EndFunction // Send text message // Sends a text message to a chat or channel -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID or ChatID*TopicID - chat @@ -246,7 +246,7 @@ EndFunction // Keyboard - String - See GenerateKeyboardFromArray - keyboard - Keyboard JSON or path to .json // Markup - String - Text processing type (HTML, Markdown, MarkdownV2) - parsemode // RepliedID - String, Number - Reply to message ID - reply -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function SendTextMessage(Val Token @@ -256,20 +256,20 @@ Function SendTextMessage(Val Token , Val Markup = "Markdown" , Val RepliedID = 0) Export - OPI_TypeConversion.GetLine(Token); + OPI_TypeConversion.GetLine(Token); OPI_Tools.ReplaceSpecialCharacters(Text, Markup); - + String_ = "String"; - + Parameters = New Structure; - OPI_Tools.AddField("parse_mode" , Markup , String_ , Parameters); - OPI_Tools.AddField("text" , Text , String_ , Parameters); - OPI_Tools.AddField("reply_markup" , Keyboard , "FileString", Parameters); - OPI_Tools.AddField("reply_to_message_id", RepliedID, String_ , Parameters); - + OPI_Tools.AddField("parse_mode" , Markup , String_ , Parameters); + OPI_Tools.AddField("text" , Text , String_ , Parameters); + OPI_Tools.AddField("reply_markup" , Keyboard , "FileString", Parameters); + OPI_Tools.AddField("reply_to_message_id", RepliedID, String_ , Parameters); + AddChatIdentifier(ChatID, Parameters); - - URL = "api.telegram.org/bot" + Token + "/sendMessage"; + + URL = "api.telegram.org/bot" + Token + "/sendMessage"; Response = OPI_Tools.Get(URL, Parameters); Return Response; @@ -278,7 +278,7 @@ EndFunction // Send image // Sends an image to a chat or channel -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID or ChatID*TopicID - chat @@ -286,7 +286,7 @@ EndFunction // Image - BinaryData,String - Image file - picture // Keyboard - String - See GenerateKeyboardFromArray - keyboard - Keyboard JSON or path to .json // Markup - String - Text processing type (HTML, Markdown, MarkdownV2) - parsemode -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function SendImage(Val Token @@ -302,7 +302,7 @@ EndFunction // Send video // Sends a video to a chat or channel -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID or ChatID*TopicID - chat @@ -310,7 +310,7 @@ EndFunction // Video - BinaryData,String - Video file - video // Keyboard - String - See GenerateKeyboardFromArray - keyboard - Keyboard JSON or path to .json // Markup - String - Text processing type (HTML, Markdown, MarkdownV2) - parsemode -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function SendVideo(Val Token @@ -326,7 +326,7 @@ EndFunction // Send audio // Sends an audio file to a chat or channel -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID or ChatID*TopicID - chat @@ -334,7 +334,7 @@ EndFunction // Audio - BinaryData,String - Audio file - audio // Keyboard - String - See GenerateKeyboardFromArray - keyboard - Keyboard JSON or path to .json // Markup - String - Text processing type (HTML, Markdown, MarkdownV2) - parsemode -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function SendAudio(Val Token @@ -350,7 +350,7 @@ EndFunction // Send document // Sends a document to a chat or channel -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID or ChatID*TopicID - chat @@ -359,7 +359,7 @@ EndFunction // Keyboard - String - See GenerateKeyboardFromArray - keyboard - Keyboard JSON or path to .json // Markup - String - Text processing type (HTML, Markdown, MarkdownV2) - parsemode // FileName - String - Custom displayed file name with extension, if necessary - filename -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function SendDocument(Val Token @@ -376,7 +376,7 @@ EndFunction // Send GIF // Sends a GIF to a chat or channel -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID or ChatID*TopicID - chat @@ -384,7 +384,7 @@ EndFunction // GIF - BinaryData,String - GIF file - gif // Keyboard - String - See GenerateKeyboardFromArray - keyboard - Keyboard JSON or path to .json // Markup - String - Text processing type (HTML, Markdown, MarkdownV2) - parsemode -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function SendGif(Val Token @@ -400,10 +400,10 @@ EndFunction // Send media group // Sends a set of files to a chat or channel. Media types: audio, document, photo, video -// +// // Note // Map: Key - File, Value - media type -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID or ChatID*TopicID - chat @@ -411,7 +411,7 @@ EndFunction // FileMapping - Map of String - File collection - media - File JSON or path to .json // Keyboard - String - See GenerateKeyboardFromArray - keyboard - Keyboard JSON or path to .json // Markup - String - Text processing type (HTML, Markdown, MarkdownV2) - parsemode -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function SendMediaGroup(Val Token @@ -420,30 +420,30 @@ Function SendMediaGroup(Val Token , Val FileMapping , Val Keyboard = "" , Val Markup = "Markdown") Export - + // FileMapping // Key - File, Value - Type // Types: audio, document, photo, video // Different types cannot be mixed! String_ = "String"; - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(ChatID); OPI_TypeConversion.GetCollection(FileMapping); - + OPI_Tools.ReplaceSpecialCharacters(Text, Markup); - URL = "api.telegram.org/bot" + Token + "/sendMediaGroup"; - Media = New Array; + URL = "api.telegram.org/bot" + Token + "/sendMediaGroup"; + Media = New Array; Parameters = New Structure; - + AddChatIdentifier(ChatID, Parameters); ConvertFilesToMedia(FileMapping, Text, Media); - - OPI_Tools.AddField("parse_mode" , Markup , String_ , Parameters); - OPI_Tools.AddField("caption" , Text , String_ , Parameters); - OPI_Tools.AddField("media" , Media , String_ , Parameters); + + OPI_Tools.AddField("parse_mode" , Markup , String_ , Parameters); + OPI_Tools.AddField("caption" , Text , String_ , Parameters); + OPI_Tools.AddField("media" , Media , String_ , Parameters); OPI_Tools.AddField("reply_markup", Keyboard, "FileString", Parameters); Response = OPI_Tools.PostMultipart(URL, Parameters, FileMapping, "mixed"); @@ -454,14 +454,14 @@ EndFunction // Send location // Sends location by geographic latitude and longitude to a chat or channel -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID or ChatID*TopicID - chat // Latitude - String, Number - Geographic latitude - lat // Longitude - String, Number - Geographic longitude - long // Keyboard - String - See GenerateKeyboardFromArray - keyboard - Keyboard JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function SendLocation(Val Token, Val ChatID, Val Latitude, Val Longitude, Val Keyboard = "") Export @@ -469,15 +469,15 @@ Function SendLocation(Val Token, Val ChatID, Val Latitude, Val Longitude, Val Ke String_ = "String"; OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(ChatID); - + URL = "api.telegram.org/bot" + Token + "/sendLocation"; - + Parameters = New Structure; - OPI_Tools.AddField("parse_mode" , "Markdown" , String_ , Parameters); - OPI_Tools.AddField("latitude" , Latitude , String_ , Parameters); - OPI_Tools.AddField("longitude" , Longitude , String_ , Parameters); - OPI_Tools.AddField("reply_markup", Keyboard , "FileString", Parameters); - + OPI_Tools.AddField("parse_mode" , "Markdown" , String_ , Parameters); + OPI_Tools.AddField("latitude" , Latitude , String_ , Parameters); + OPI_Tools.AddField("longitude" , Longitude , String_ , Parameters); + OPI_Tools.AddField("reply_markup", Keyboard , "FileString", Parameters); + AddChatIdentifier(ChatID, Parameters); Response = OPI_Tools.Get(URL, Parameters); @@ -488,7 +488,7 @@ EndFunction // Send contact // Sends a contact with name and phone number -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID or ChatID*TopicID - chat @@ -496,7 +496,7 @@ EndFunction // LastName - String - Contact last name - surname // Phone - String - Contact phone number - phone // Keyboard - String - See GenerateKeyboardFromArray - keyboard - Keyboard JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function SendContact(Val Token, Val ChatID, Val Name, Val LastName, Val Phone, Val Keyboard = "") Export @@ -504,16 +504,16 @@ Function SendContact(Val Token, Val ChatID, Val Name, Val LastName, Val Phone, V String_ = "String"; OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(ChatID); - + URL = "api.telegram.org/bot" + Token + "/sendContact"; Parameters = New Structure; - OPI_Tools.AddField("parse_mode" , "Markdown", String_ , Parameters); - OPI_Tools.AddField("first_name" , Name , String_ , Parameters); - OPI_Tools.AddField("last_name" , LastName , String_ , Parameters); - OPI_Tools.AddField("phone_number", Phone , String_ , Parameters); - OPI_Tools.AddField("reply_markup", Keyboard, "FileString", Parameters); - + OPI_Tools.AddField("parse_mode" , "Markdown", String_ , Parameters); + OPI_Tools.AddField("first_name" , Name , String_ , Parameters); + OPI_Tools.AddField("last_name" , LastName , String_ , Parameters); + OPI_Tools.AddField("phone_number", Phone , String_ , Parameters); + OPI_Tools.AddField("reply_markup", Keyboard , "FileString", Parameters); + AddChatIdentifier(ChatID, Parameters); Response = OPI_Tools.Get(URL, Parameters); @@ -524,14 +524,14 @@ EndFunction // Send poll // Sends a poll with answer options -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID or ChatID*TopicID - chat // Question - String - Poll question - question // AnswersArray - Array of String - Array of answer options - options // Anonymous - Boolean - Poll anonymity - anonymous -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function SendPoll(Val Token, Val ChatID, Val Question, Val AnswersArray, Val Anonymous = True) Export @@ -541,15 +541,15 @@ Function SendPoll(Val Token, Val ChatID, Val Question, Val AnswersArray, Val Ano OPI_TypeConversion.GetCollection(AnswersArray); OPI_TypeConversion.GetBoolean(Anonymous); - + URL = "api.telegram.org/bot" + Token + "/sendPoll"; Parameters = New Structure; - OPI_Tools.AddField("parse_mode", "Markdown" , "String" , Parameters); - OPI_Tools.AddField("question" , Question , "String" , Parameters); - OPI_Tools.AddField("options" , AnswersArray, "FileString", Parameters); - - Parameters.Insert("is_anonymous", ?(Anonymous, 1, 0)); + OPI_Tools.AddField("parse_mode", "Markdown" , "String" , Parameters); + OPI_Tools.AddField("question" , Question , "String" , Parameters); + OPI_Tools.AddField("options" , AnswersArray, "FileString", Parameters); + + Parameters.Insert("is_anonymous", ?(Anonymous, 1, 0)); AddChatIdentifier(ChatID, Parameters); Response = OPI_Tools.Get(URL, Parameters); @@ -560,13 +560,13 @@ EndFunction // Forward message // Forwards a message between chats or within a chat -// +// // Parameters: // Token - String - Bot token - token // OriginalID - String, Number - Original message ID - message // FromID - String, Number - Chat ID of the original message - from // ToID - String, Number - Target chat ID or ChatID*TopicID - to -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function ForwardMessage(Val Token, Val OriginalID, Val FromID, Val ToID) Export @@ -575,15 +575,15 @@ Function ForwardMessage(Val Token, Val OriginalID, Val FromID, Val ToID) Export OPI_TypeConversion.GetLine(OriginalID); OPI_TypeConversion.GetLine(FromID); OPI_TypeConversion.GetLine(ToID); - + URL = "api.telegram.org/bot" + Token + "/forwardMessage"; - + Parameters = New Structure; - OPI_Tools.AddField("from_chat_id", FromID , "String", Parameters); - OPI_Tools.AddField("message_id" , OriginalID, "String", Parameters); + OPI_Tools.AddField("from_chat_id", FromID , "String", Parameters); + OPI_Tools.AddField("message_id" , OriginalID, "String", Parameters); AddChatIdentifier(ToID, Parameters); - + Response = OPI_Tools.Get(URL, Parameters); Return Response; @@ -592,12 +592,12 @@ EndFunction // Generate keyboard from array of buttons // Generates a simple JSON keyboard from an array of buttons for a message or bottom panel -// +// // Parameters: -// ButtonArray - Array of String - Array of buttons - buttons +// ButtonArray - Array of String - Array of buttons - buttons // UnderMessage - Boolean - Keyboard under the message or on the bottom panel - under // OneByOne - Boolean - True > buttons are displayed in a column, False > in a row - column -// +// // Returns: // String - Keyboard JSON Function FormKeyboardFromButtonArray(Val ButtonArray @@ -607,7 +607,7 @@ Function FormKeyboardFromButtonArray(Val ButtonArray OPI_TypeConversion.GetBoolean(UnderMessage); OPI_TypeConversion.GetBoolean(OneByOne); OPI_TypeConversion.GetCollection(ButtonArray); - + If OneByOne Then Strings = CreateTallKeyboard(ButtonArray); Else @@ -615,7 +615,7 @@ Function FormKeyboardFromButtonArray(Val ButtonArray EndIf; If UnderMessage Then - ParameterStructure = New Structure("inline_keyboard,rows", Strings, 1); + ParameterStructure = New Structure("inline_keyboard,rows" , Strings, 1); Else ParameterStructure = New Structure("keyboard,resize_keyboard", Strings, True); EndIf; @@ -632,25 +632,25 @@ EndFunction // Ban // Bans a user in the selected chat -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID or ChatID*TopicID - chat // UserID - String, Number - Target user ID - user -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function Ban(Val Token, Val ChatID, Val UserID) Export String_ = "String"; OPI_TypeConversion.GetLine(Token); - + URL = "api.telegram.org/bot" + Token + "/banChatMember"; Parameters = New Structure; OPI_Tools.AddField("parse_mode", "Markdown" , String_, Parameters); - OPI_Tools.AddField("chat_id" , ChatID , String_, Parameters); - OPI_Tools.AddField("user_id" , UserID, String_, Parameters); + OPI_Tools.AddField("chat_id" , ChatID , String_, Parameters); + OPI_Tools.AddField("user_id" , UserID , String_, Parameters); Response = OPI_Tools.Get(URL, Parameters); @@ -660,26 +660,26 @@ EndFunction // Unban // Unbans a previously banned user -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID or ChatID*TopicID - chat // UserID - String, Number - Target user ID - user -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function Unban(Val Token, Val ChatID, Val UserID) Export String_ = "String"; OPI_TypeConversion.GetLine(Token); - + URL = "api.telegram.org/bot" + Token + "/unbanChatMember"; - Parameters = New Structure; - OPI_Tools.AddField("parse_mode" , "Markdown" , String_ , Parameters); - OPI_Tools.AddField("chat_id" , ChatID , String_ , Parameters); - OPI_Tools.AddField("user_id" , UserID, String_ , Parameters); - OPI_Tools.AddField("only_if_banned", False , "Boolean", Parameters); + Parameters = New Structure; + OPI_Tools.AddField("parse_mode" , "Markdown" , String_ , Parameters); + OPI_Tools.AddField("chat_id" , ChatID , String_ , Parameters); + OPI_Tools.AddField("user_id" , UserID , String_ , Parameters); + OPI_Tools.AddField("only_if_banned", False , "Boolean", Parameters); Response = OPI_Tools.Get(URL, Parameters); @@ -689,14 +689,14 @@ EndFunction // Create invitation link // Creates a link for joining a closed chat -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID or ChatID*TopicID - chat // Title - String - Invitation title - title // ExpirationDate - Date - Link expiration date (permanent if not specified) - expire // UserLimit - Number - User limit (infinite if not specified) - limit -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function CreateInvitationLink(Val Token @@ -707,16 +707,16 @@ Function CreateInvitationLink(Val Token String_ = "String"; OPI_TypeConversion.GetLine(Token); - + URL = "api.telegram.org/bot" + Token + "/createChatInviteLink"; - + Parameters = New Structure; - OPI_Tools.AddField("parse_mode" , "Markdown" , String_ , Parameters); - OPI_Tools.AddField("chat_id" , ChatID , String_ , Parameters); - OPI_Tools.AddField("name" , Title , String_ , Parameters); - OPI_Tools.AddField("member_limit" , UserLimit, String_ , Parameters); - OPI_Tools.AddField("expire_date" , ExpirationDate , "Date" , Parameters); - + OPI_Tools.AddField("parse_mode" , "Markdown" , String_ , Parameters); + OPI_Tools.AddField("chat_id" , ChatID , String_ , Parameters); + OPI_Tools.AddField("name" , Title , String_ , Parameters); + OPI_Tools.AddField("member_limit" , UserLimit , String_ , Parameters); + OPI_Tools.AddField("expire_date" , ExpirationDate , "Date" , Parameters); + Response = OPI_Tools.Get(URL, Parameters); Return Response; @@ -725,26 +725,26 @@ EndFunction // Pin message // Pins a message in the chat header -// +// // Parameters: // Token - String - Token - token // ChatID - String, Number - Target chat ID - chat // MessageID - String, Number - Target message ID - message -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function PinMessage(Val Token, Val ChatID, Val MessageID) Export - + String_ = "String"; OPI_TypeConversion.GetLine(Token); - + URL = "api.telegram.org/bot" + Token + "/pinChatMessage"; - + Parameters = New Structure; - OPI_Tools.AddField("parse_mode" , "Markdown" , String_ , Parameters); - OPI_Tools.AddField("chat_id" , ChatID , String_ , Parameters); - OPI_Tools.AddField("message_id" , MessageID, String_ , Parameters); - OPI_Tools.AddField("disable_notification", False , "Boolean", Parameters); + OPI_Tools.AddField("parse_mode" , "Markdown" , String_ , Parameters); + OPI_Tools.AddField("chat_id" , ChatID , String_ , Parameters); + OPI_Tools.AddField("message_id" , MessageID , String_ , Parameters); + OPI_Tools.AddField("disable_notification", False , "Boolean", Parameters); Response = OPI_Tools.Get(URL, Parameters); @@ -754,25 +754,25 @@ EndFunction // Unpin message // Unpins a message in the chat header -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID - chat // MessageID - String, Number - Target message ID - message -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function UnpinMessage(Val Token, Val ChatID, Val MessageID) Export - + String_ = "String"; OPI_TypeConversion.GetLine(Token); - + URL = "api.telegram.org/bot" + Token + "/unpinChatMessage"; - + Parameters = New Structure; OPI_Tools.AddField("parse_mode", "Markdown" , String_, Parameters); - OPI_Tools.AddField("chat_id" , ChatID , String_, Parameters); - OPI_Tools.AddField("message_id", MessageID, String_, Parameters); + OPI_Tools.AddField("chat_id" , ChatID , String_, Parameters); + OPI_Tools.AddField("message_id", MessageID , String_, Parameters); Response = OPI_Tools.Get(URL, Parameters); @@ -782,22 +782,22 @@ EndFunction // Get participant count // Gets the total number of chat participants -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID - chat -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function GetParticipantCount(Val Token, Val ChatID) Export OPI_TypeConversion.GetLine(Token); - + URL = "api.telegram.org/bot" + Token + "/getChatMemberCount"; - + Parameters = New Structure; OPI_Tools.AddField("parse_mode", "Markdown" , "String", Parameters); - OPI_Tools.AddField("chat_id" , ChatID , "String", Parameters); + OPI_Tools.AddField("chat_id" , ChatID , "String", Parameters); Response = OPI_Tools.Get(URL, Parameters); @@ -807,24 +807,24 @@ EndFunction // Delete message // Delete message from chat or channel -// +// // Parameters: // Token - String - Token - token // ChatID - String, Number - Target chat ID - chat // MessageID - String, Number - ID of message to delete - message -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function DeleteMessage(Val Token, Val ChatID, Val MessageID) Export - + OPI_TypeConversion.GetLine(Token); - + URL = "api.telegram.org/bot" + Token + "/deleteMessage"; - + Parameters = New Structure; OPI_Tools.AddField("message_id", MessageID, "String", Parameters); - OPI_Tools.AddField("chat_id" , ChatID , "String", Parameters); - + OPI_Tools.AddField("chat_id" , ChatID , "String", Parameters); + Response = OPI_Tools.Get(URL, Parameters); Return Response; @@ -836,206 +836,206 @@ EndFunction // Get avatar icon list // Gets the mapping of Emoji IDs for setting as forum theme icons -// +// // Parameters: // Token - String - Token - token -// +// // Returns: // Map Of KeyAndValue - Key > ID, Value > Emoji Function GetAvatarIconList(Val Token) Export - + OPI_TypeConversion.GetLine(Token); - - Result = "result"; - URL = "api.telegram.org/bot" + Token + "/getForumTopicIconStickers"; - Response = OPI_Tools.Get(URL); - Icons = Response[Result]; - + + Result = "result"; + URL = "api.telegram.org/bot" + Token + "/getForumTopicIconStickers"; + Response = OPI_Tools.Get(URL); + Icons = Response[Result]; + If Not ValueIsFilled(Icons) Then Return Response; - EndIf; - + EndIf; + Collection = New Map; - + For Each Icon In Icons Do Collection.Insert(Icon["custom_emoji_id"], Icon["emoji"]); EndDo; - + Return Collection; EndFunction // Create forum thread // Creates a new thread in the group with theme functionality enabled -// +// // Parameters: // Token - String - Token - token // ChatID - String, Number - Thread creation chat ID - forum // Title - String - Thread title - title // IconID - String - See GetAvatarIconList - icon -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function CreateForumThread(Val Token, Val ChatID, Val Title, Val IconID = "") Export - + Return ForumTopicManagement(Token, ChatID, Title, IconID); - + EndFunction // Edit forum thread // Creates a new thread in the group with theme functionality enabled -// +// // Parameters: // Token - String - Token - token // ChatID - String, Number - Thread creation chat ID - forum // ThreadID - String, Number - Thread ID - topic // Title - String - New title - title // IconID - String - See GetAvatarIconList - icon -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function EditForumTopic(Val Token , Val ChatID , Val ThreadID , Val Title = Undefined - , Val IconID = Undefined) Export - + , Val IconID = Undefined) Export + Return ForumTopicManagement(Token, ChatID, Title, IconID, ThreadID); EndFunction // Close forum thread // Closes the thread for new messages -// +// // Parameters: // Token - String - Token - token // ChatID - String, Number - Thread chat ID - forum // ThreadID - String, Number - Thread ID - topic -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function CloseForumThread(Val Token, Val ChatID, Val ThreadID = "") Export - - Return ManageForumThreadState(Token, ChatID, 2, ThreadID); - + + Return ManageForumThreadState(Token, ChatID, 2, ThreadID); + EndFunction // Open forum thread // Reopens a previously closed forum thread -// +// // Parameters: // Token - String - Token - token // ChatID - String, Number - Thread chat ID - forum // ThreadID - String, Number - Thread ID - topic -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function OpenForumThread(Val Token, Val ChatID, Val ThreadID = "") Export - - Return ManageForumThreadState(Token, ChatID, 1, ThreadID); - + + Return ManageForumThreadState(Token, ChatID, 1, ThreadID); + EndFunction // Delete forum thread // Deletes a forum thread -// +// // Parameters: // Token - String - Token - token // ChatID - String, Number - Thread chat ID - forum // ThreadID - String, Number - Thread ID - topic -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function DeleteForumTopic(Val Token, Val ChatID, Val ThreadID) Export - - Return ManageForumThreadState(Token, ChatID, 3, ThreadID); - + + Return ManageForumThreadState(Token, ChatID, 3, ThreadID); + EndFunction // Hide main forum thread // Hides the main forum thread -// +// // Parameters: // Token - String - Token - token // ChatID - String, Number - Thread chat ID - forum -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function HideMainForumTopic(Val Token, Val ChatID) Export - + Return ManageMainTopicVisibility(Token, ChatID, True); - + EndFunction // Show main forum thread // Shows a previously hidden main forum thread -// +// // Parameters: // Token - String - Token - token // ChatID - String, Number - Thread chat ID - forum -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function ShowMainForumTopic(Val Token, Val ChatID) Export - + Return ManageMainTopicVisibility(Token, ChatID, False); - + EndFunction // Edit main forum thread name // Edits the name of the main forum thread -// +// // Parameters: // Token - String - Token - token // ChatID - String, Number - Thread chat ID - forum // Title - String - New main thread name - title -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function EditMainForumTopicName(Val Token, Val ChatID, Val Title) Export - + OPI_TypeConversion.GetLine(Token); - + URL = "api.telegram.org/bot" + Token + "/editGeneralForumTopic"; - + Parameters = New Structure; OPI_Tools.AddField("chat_id", ChatID , "String", Parameters); - OPI_Tools.AddField("name" , Title, "String", Parameters); - + OPI_Tools.AddField("name" , Title , "String", Parameters); + Response = OPI_Tools.Get(URL, Parameters); - + Return Response; EndFunction // Clear thread's pinned messages list // Clears the list of pinned messages in the forum thread -// +// // Parameters: // Token - String - Token - token // ChatID - String, Number - Thread chat ID - forum // ThreadID - String, Number - Thread ID. Main if not filled - topic -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function ClearThreadPinnedMessagesList(Val Token, Val ChatID, Val ThreadID = "") Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(ChatID); OPI_TypeConversion.GetLine(ThreadID); - + Parameters = New Structure; - OPI_Tools.AddField("chat_id" , ChatID, "String", Parameters); + OPI_Tools.AddField("chat_id" , ChatID , "String", Parameters); OPI_Tools.AddField("message_thread_id", ThreadID, "String", Parameters); - + If ValueIsFilled(ThreadID) Then Method = "/unpinAllForumTopicMessages"; Else Method = "/unpinAllGeneralForumTopicMessages"; EndIf; - - URL = "api.telegram.org/bot" + Token + Method; + + URL = "api.telegram.org/bot" + Token + Method; Response = OPI_Tools.Get(URL, Parameters); - + Return Response; EndFunction @@ -1061,27 +1061,27 @@ Function SendFile(Val Token OPI_TypeConversion.GetLine(Text); OPI_Tools.ReplaceSpecialCharacters(Text, Markup); - + If Not ValueIsFilled(FileName) Then FileName = ConvertFileData(File, View, ""); Else OPI_TypeConversion.GetBinaryData(File); EndIf; - + FileName = View + "|" + FileName; - + Parameters = New Structure; - OPI_Tools.AddField("parse_mode" , Markup , "String" , Parameters); - OPI_Tools.AddField("caption" , Text , "String" , Parameters); + OPI_Tools.AddField("parse_mode" , Markup , "String" , Parameters); + OPI_Tools.AddField("caption" , Text , "String" , Parameters); OPI_Tools.AddField("reply_markup", Keyboard, "FileString", Parameters); - + AddChatIdentifier(ChatID, Parameters); FileMapping = New Map; FileMapping.Insert(FileName, File); - Method = DetermineSendMethod(View); - URL = "api.telegram.org/bot" + Token + Method; + Method = DetermineSendMethod(View); + URL = "api.telegram.org/bot" + Token + Method; Response = OPI_Tools.PostMultipart(URL, Parameters, FileMapping, "mixed"); Return Response; @@ -1090,56 +1090,56 @@ EndFunction Function ForumTopicManagement(Val Token , Val ChatID - , Val Title = Undefined - , Val IconID = Undefined + , Val Title = Undefined + , Val IconID = Undefined , Val ThreadID = "") - + String_ = "String"; OPI_TypeConversion.GetLine(Token); - + Parameters = New Structure; - OPI_Tools.AddField("name" , Title, String_, Parameters); - OPI_Tools.AddField("chat_id" , ChatID , String_, Parameters); - OPI_Tools.AddField("icon_custom_emoji_id", IconID , String_, Parameters); - OPI_Tools.AddField("message_thread_id" , ThreadID , String_, Parameters); - + OPI_Tools.AddField("name" , Title , String_, Parameters); + OPI_Tools.AddField("chat_id" , ChatID , String_, Parameters); + OPI_Tools.AddField("icon_custom_emoji_id", IconID , String_, Parameters); + OPI_Tools.AddField("message_thread_id" , ThreadID , String_, Parameters); + If ValueIsFilled(ThreadID) Then - Method = "/editForumTopic"; - Else - Method = "/createForumTopic"; + Method = "/editForumTopic"; + Else + Method = "/createForumTopic"; EndIf; - + Response = OPI_Tools.Get("api.telegram.org/bot" + Token + Method, Parameters); - + Return Response; EndFunction -Function ManageForumThreadState(Val Token, Val ChatID, Val Status, Val ThreadID = "") - +Function ManageForumThreadState(Val Token, Val ChatID, Val Status, Val ThreadID = "") + OPI_TypeConversion.GetLine(Token); - + If ValueIsFilled(ThreadID) Then Forum = "Forum"; Else Forum = "GeneralForum"; EndIf; - + Method = DetermineForumManagementMethod(Status, Forum); - + Parameters = New Structure; - OPI_Tools.AddField("chat_id" , ChatID, "String", Parameters); + OPI_Tools.AddField("chat_id" , ChatID , "String", Parameters); OPI_Tools.AddField("message_thread_id", ThreadID, "String", Parameters); - - URL = "api.telegram.org/bot" + Token + Method; + + URL = "api.telegram.org/bot" + Token + Method; Response = OPI_Tools.Get(URL, Parameters); Return Response; - + EndFunction Function ManageMainTopicVisibility(Val Token, Val ChatID, Val Hide) - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetBoolean(Hide); @@ -1148,71 +1148,71 @@ Function ManageMainTopicVisibility(Val Token, Val ChatID, Val Hide) Else Method = "/unhideGeneralForumTopic"; EndIf; - + Parameters = New Structure; OPI_Tools.AddField("chat_id", ChatID, "String", Parameters); - - URL = "api.telegram.org/bot" + Token + Method; + + URL = "api.telegram.org/bot" + Token + Method; Response = OPI_Tools.Get(URL, Parameters); - + Return Response; -EndFunction +EndFunction -Function DetermineForumManagementMethod(Val Status, Val Forum) - - Open = 1; - Close = 2; +Function DetermineForumManagementMethod(Val Status, Val Forum) + + Open = 1; + Close = 2; Delete = 3; - - If Status = Open Then - Method = "/reopen" + Forum + "Topic"; + + If Status = Open Then + Method = "/reopen" + Forum + "Topic"; ElsIf Status = Close Then - Method = "/close" + Forum + "Topic"; + Method = "/close" + Forum + "Topic"; ElsIf Status = Delete Then - Method = "/deleteForumTopic"; - Else + Method = "/deleteForumTopic"; + Else Raise "Incorrect forum management status"; EndIf; - + Return Method; EndFunction Function CreateTallKeyboard(Val ButtonArray) - + Strings = New Array; - + For Each Button In ButtonArray Do Buttons = New Array; - Button = OPI_Tools.NumberToString(Button); + Button = OPI_Tools.NumberToString(Button); Buttons.Add(New Structure("text,callback_data", Button, Button)); Strings.Add(Buttons); EndDo; Return Strings; - + EndFunction Function CreateLongKeyboard(Val ButtonArray) - + Strings = New Array; Buttons = New Array; - + For Each Button In ButtonArray Do Button = OPI_Tools.NumberToString(Button); Buttons.Add(New Structure("text,callback_data", Button, Button)); EndDo; - + Strings.Add(Buttons); - + Return Strings; EndFunction Function DetermineSendMethod(Val View) - - If View = "photo" Then + + If View = "photo" Then Method = "/sendPhoto"; ElsIf View = "video" Then Method = "/sendVideo"; @@ -1225,48 +1225,48 @@ Function DetermineSendMethod(Val View) EndIf; Return Method; - + EndFunction Function ConvertFileData(File, View, Counter) - + FileName = ""; - + If TypeOf(File) = Type("String") And View = "document" Then - + CurrentFile = New File(File); - FileName = CurrentFile.Name; - + FileName = CurrentFile.Name; + EndIf; - + If Not ValueIsFilled(FileName) Then FileName = View + String(Counter); - - If View = "animation" Then - FileName = FileName + ".gif"; + + If View = "animation" Then + FileName = FileName + ".gif"; EndIf; - + EndIf; - + OPI_TypeConversion.GetBinaryData(File); - + Return FileName; - + EndFunction Procedure ConvertFilesToMedia(FileMapping, Text, Media) - + OPI_TypeConversion.GetCollection(FileMapping); OPI_TypeConversion.GetLine(Text); - + If TypeOf(FileMapping) <> Type("Map") Then Raise("Failed to Retrieve Information from JSON media!"); Return; EndIf; - + TempMap = New Map; Counter = 0; - + For Each CurrentFile In FileMapping Do CurrentData = CurrentFile.Key; @@ -1290,25 +1290,25 @@ Procedure ConvertFilesToMedia(FileMapping, Text, Media) EndDo; - Media = OPI_Tools.JSONString(Media); - FileMapping = TempMap; - + Media = OPI_Tools.JSONString(Media); + FileMapping = TempMap; + EndProcedure Procedure AddChatIdentifier(Val ChatID, Parameters) - - ChatID = OPI_Tools.NumberToString(ChatID); + + ChatID = OPI_Tools.NumberToString(ChatID); ChatArray = StrSplit(ChatID, "*", False); - + If ChatArray.Count() > 1 Then - - ChatID = ChatArray[0]; + + ChatID = ChatArray[0]; ThreadID = ChatArray[1]; - + Parameters.Insert("message_thread_id", ThreadID); - + EndIf; - + Parameters.Insert("chat_id", ChatID); EndProcedure diff --git a/src/en/OInt/core/Modules/OPI_Twitter.os b/src/en/OInt/core/Modules/OPI_Twitter.os index 04afd178f8..0dfb42b8cf 100644 --- a/src/en/OInt/core/Modules/OPI_Twitter.os +++ b/src/en/OInt/core/Modules/OPI_Twitter.os @@ -48,83 +48,83 @@ // Get authorization link // Forms a link for authorization via the browser -// +// // Parameters: // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // String - URL for browser transition Function GetAuthorizationLink(Parameters = "") Export - + Parameters_ = GetStandardParameters(Parameters); - + URLParameters = New Structure; - - URLParameters.Insert("response_type" , "code"); - URLParameters.Insert("client_id" , Parameters_["client_id"]); - URLParameters.Insert("redirect_uri" , Parameters_["redirect_uri"]); - URLParameters.Insert("scope" , Parameters_["scope"]); - URLParameters.Insert("state" , "state"); - URLParameters.Insert("code_challenge" , "challenge"); + + URLParameters.Insert("response_type" , "code"); + URLParameters.Insert("client_id" , Parameters_["client_id"]); + URLParameters.Insert("redirect_uri" , Parameters_["redirect_uri"]); + URLParameters.Insert("scope" , Parameters_["scope"]); + URLParameters.Insert("state" , "state"); + URLParameters.Insert("code_challenge" , "challenge"); URLParameters.Insert("code_challenge_method", "plain"); - + URLParameters = OPI_Tools.RequestParametersToString(URLParameters); - Link = "https://twitter.com/i/oauth2/authorize" + URLParameters; - + Link = "https://twitter.com/i/oauth2/authorize" + URLParameters; + Return Link; - + EndFunction // Get token // Gets the token by the code received when authorizing using the link from GetAuthorizationLink -// +// // Parameters: // Code - String - Code obtained from authorization See GetAuthorizationLink - code // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Twitter Function GetToken(Val Code, Val Parameters = "") Export OPI_TypeConversion.GetLine(Code); - + Parameters_ = GetStandardParameters(Parameters); RequestParameters = New Structure; - RequestParameters.Insert("code" , Code); - RequestParameters.Insert("grant_type" , "authorization_code"); - RequestParameters.Insert("client_id" , Parameters_["client_id"]); + RequestParameters.Insert("code" , Code); + RequestParameters.Insert("grant_type" , "authorization_code"); + RequestParameters.Insert("client_id" , Parameters_["client_id"]); RequestParameters.Insert("redirect_uri" , Parameters_["redirect_uri"]); RequestParameters.Insert("code_verifier", "challenge"); - + Response = OPI_Tools.Post("https://api.twitter.com/2/oauth2/token" , RequestParameters, , False); - + Return Response; - + EndFunction -// Refresh token +// Refresh token // Updates the v2 token using the refresh_token -// +// // Parameters: // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Twitter Function RefreshToken(Val Parameters = "") Export - + Parameters_ = GetStandardParameters(Parameters); - Refresh = "refresh_token"; - + Refresh = "refresh_token"; + RequestParameters = New Structure; - RequestParameters.Insert(Refresh , Parameters_[Refresh]); + RequestParameters.Insert(Refresh , Parameters_[Refresh]); RequestParameters.Insert("grant_type" , Refresh); - RequestParameters.Insert("client_id" , Parameters_["client_id"]); - + RequestParameters.Insert("client_id" , Parameters_["client_id"]); + Response = OPI_Tools.Post("https://api.twitter.com/2/oauth2/token" , RequestParameters, , False); - + Return Response; EndFunction @@ -133,23 +133,23 @@ EndFunction // Method for insertion into an http service, the address of which is specified in redirect_uri // Calls the token acquisition method, as for obtaining a token from the code received // on redirect_uri after authorization via the browser is only 30 seconds -// +// // Parameters: // Request - HTTPServiceRequest - Request coming to the http service -// +// // Returns: // HTTPResponse, Arbitrary, BinaryData - Result of reading the JSON response from the server Function HandleIncomingRequestAfterAuthorization(Request) Export - - Code = Request.RequestParameters["code"]; + + Code = Request.RequestParameters["code"]; TokenResponse = GetToken(Code); - + // BSLLS:CommentedCode-off // Preferred token storage // Constants.TwitterRefresh.Set(ResponseToken["refresh_token"]); // Constants.TwitterToken.Set(ResponseToken["access_token"]); // BSLLS:CommentedCode-on - + Return TokenResponse; EndFunction @@ -160,189 +160,189 @@ EndFunction // !NOCLI // Create custom tweet -// +// // Parameters: // Text - String - Tweet text // MediaArray - Array of String, BinaryData - Array of binary data or file paths // PollOptionsArray - Array of String - Array of poll options, if necessary // PollDuration - String, Number - Poll duration if necessary (poll without duration is not created) // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Twitter Function CreateCustomTweet(Val Text = "" , Val MediaArray = "" , Val PollOptionsArray = "" , Val PollDuration = "" - , Val Parameters = "") Export - + , Val Parameters = "") Export + OPI_TypeConversion.GetLine(Text); OPI_TypeConversion.GetLine(PollDuration); - + If ValueIsFilled(MediaArray) Then OPI_TypeConversion.GetCollection(MediaArray); EndIf; - + If ValueIsFilled(PollOptionsArray) Then OPI_TypeConversion.GetCollection(PollOptionsArray); EndIf; - + Parameters_ = GetStandardParameters(Parameters); - URL = "https://api.twitter.com/2/tweets"; - Array = "Array"; - Fields = New Map; - + URL = "https://api.twitter.com/2/tweets"; + Array = "Array"; + Fields = New Map; + If ValueIsFilled(Text) Then Fields.Insert("text", Text); EndIf; - + If TypeOf(PollOptionsArray) = Type(Array) And ValueIsFilled(PollDuration) Then - + PollDuration = Number(PollDuration); - + If PollOptionsArray.Count() > 0 Then - + OptionStructure = New Structure("options,duration_minutes", PollOptionsArray, PollDuration); Fields.Insert("poll", OptionStructure); - + EndIf; - + EndIf; - + If TypeOf(MediaArray) = Type(Array) Then If MediaArray.Count() > 0 Then Fields.Insert("media", New Structure("media_ids", MediaArray)); EndIf; EndIf; - + Authorization = CreateAuthorizationHeaderV2(Parameters_); - Response = OPI_Tools.Post(URL, Fields, Authorization); + Response = OPI_Tools.Post(URL, Fields, Authorization); Return Response; - + EndFunction // Create text tweet // Creates a tweet without attachments -// +// // Parameters: // Text - String - Tweet text - text // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Twitter Function CreateTextTweet(Val Text, Val Parameters = "") Export - Return CreateCustomTweet(Text, , , , Parameters); + Return CreateCustomTweet(Text, , , , Parameters); EndFunction // Create image tweet // Creates a tweet with an image attachment -// +// // Parameters: // Text - String - Tweet text - text // ImageArray - Array of String, BinaryData - Image files array - pictures // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Twitter Function CreateImageTweet(Val Text, Val ImageArray, Val Parameters = "") Export - + MediaArray = UploadAttachmentsArray(ImageArray, "photo", Parameters); - Return CreateCustomTweet(Text, MediaArray, , , Parameters); - + Return CreateCustomTweet(Text, MediaArray, , , Parameters); + EndFunction // Create gif tweet // Creates a tweet with a gif attachment -// +// // Parameters: // Text - String - Tweet text - text // GifsArray - Array of String, BinaryData - Gif files array - gifs // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Twitter Function CreateGifTweet(Val Text, Val GifsArray, Val Parameters = "") Export - + MediaArray = UploadAttachmentsArray(GifsArray, "animated_gif", Parameters); - Return CreateCustomTweet(Text, MediaArray, , , Parameters); - + Return CreateCustomTweet(Text, MediaArray, , , Parameters); + EndFunction // Create video tweet // Creates a tweet with a video attachment -// +// // Parameters: // Text - String - Tweet text - text // VideosArray - Array of String, BinaryData - Video files array - videos // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Twitter Function CreateVideoTweet(Val Text, Val VideosArray, Val Parameters = "") Export - + MediaArray = UploadAttachmentsArray(VideosArray, "video", Parameters); Return CreateCustomTweet(Text, MediaArray, , , Parameters); - + EndFunction // Create poll tweet // Creates a tweet with a poll -// +// // Parameters: // Text - String - Tweet text - text // OptionArray - Array of String - Poll options array - options // Duration - String, Number - Poll duration - duration // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Twitter Function CreatePollTweet(Val Text, Val OptionArray, Val Duration, Val Parameters = "") Export - - Return CreateCustomTweet(Text, , OptionArray, Duration, Parameters); - + + Return CreateCustomTweet(Text, , OptionArray, Duration, Parameters); + EndFunction // Upload attachments array !NOCLI // Uploads files to the server and returns their IDs -// +// // Parameters: // ArrayOfFiles - Array of String, BinaryData - Files array // AttachmentsType - String - Attachments type // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Array Of String - Media ID array Function UploadAttachmentsArray(Val ArrayOfFiles, Val AttachmentsType, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(AttachmentsType); OPI_TypeConversion.GetCollection(ArrayOfFiles); - - MediaArray = New Array; + + MediaArray = New Array; Parameters_ = GetStandardParameters(Parameters); - MIS = "media_id_string"; - + MIS = "media_id_string"; + If ValueIsFilled(ArrayOfFiles) Then - + For Each SendingFile In ArrayOfFiles Do - + OPI_TypeConversion.GetBinaryData(SendingFile); - + Response = UploadMediaFile(SendingFile, AttachmentsType, Parameters_); - MediaID = Response[MIS]; - + MediaID = Response[MIS]; + If Not ValueIsFilled(MediaID) Then Return Response; EndIf; - + MediaArray.Add(MediaID); - + EndDo; - + EndIf; - + Return MediaArray; - + EndFunction #EndRegion @@ -351,195 +351,195 @@ EndFunction #Region Private -Function UploadMediaFile(Val File, Val Type, Val Parameters) - +Function UploadMediaFile(Val File, Val Type, Val Parameters) + OPI_TypeConversion.GetBinaryData(File); - - RequestType = "POST"; + + RequestType = "POST"; Parameters_ = GetStandardParameters(Parameters); - URL = "https://upload.twitter.com/1.1/media/upload.json"; - - If Type = "photo" Then - + URL = "https://upload.twitter.com/1.1/media/upload.json"; + + If Type = "photo" Then + Fields = New Structure; - Fields.Insert("media_data" , Base64String(File)); + Fields.Insert("media_data" , Base64String(File)); Fields.Insert("media_category", Type); - - Authorization = CreateAuthorizationHeaderV1(Parameters_, Fields, RequestType, URL); - Response = OPI_Tools.Post(URL, Fields, Authorization, False); - + + Authorization = CreateAuthorizationHeaderV1(Parameters_, Fields, RequestType, URL); + Response = OPI_Tools.Post(URL, Fields, Authorization, False); + Else - + Response = UploadMediaInParts(File, Type, RequestType, URL, Parameters_); - + EndIf; - + Return Response; - + EndFunction Function UploadMediaInParts(Val File, Val Type, Val RequestType, Val URL, Parameters) - - Unit = 1024; - Count = 4; + + Unit = 1024; + Count = 4; MediaKey = "media_key"; - MIS = "media_id_string"; - Command = "command"; - Size = File.Size(); - + MIS = "media_id_string"; + Command = "command"; + Size = File.Size(); + MIMETypeMapping = New Map; - MIMETypeMapping.Insert("photo" , "image/jpeg"); - MIMETypeMapping.Insert("video" , "video/mp4"); + MIMETypeMapping.Insert("photo" , "image/jpeg"); + MIMETypeMapping.Insert("video" , "video/mp4"); MIMETypeMapping.Insert("animated_gif", "image/gif"); - - ChunkSize = Count * Unit * Unit; + + ChunkSize = Count * Unit * Unit; ArrayReading = SplitBinaryData(File, ChunkSize); - + Fields = New Structure; - Fields.Insert(Command , "INIT"); - Fields.Insert("total_bytes" , OPI_Tools.NumberToString(Size)); - Fields.Insert("media_type" , MIMETypeMapping.Get(Type)); + Fields.Insert(Command , "INIT"); + Fields.Insert("total_bytes" , OPI_Tools.NumberToString(Size)); + Fields.Insert("media_type" , MIMETypeMapping.Get(Type)); Fields.Insert("media_category" , Type); - + Authorization = CreateAuthorizationHeaderV1(Parameters, Fields, RequestType, URL); InitializationResponse = OPI_Tools.Post(URL, Fields, Authorization, False); - InitializationKey = InitializationResponse[MediaKey]; - InitializationID = InitializationResponse[MIS]; - + InitializationKey = InitializationResponse[MediaKey]; + InitializationID = InitializationResponse[MIS]; + If Not ValueIsFilled(InitializationKey) Or Not ValueIsFilled(InitializationID) Then - Return InitializationResponse; + Return InitializationResponse; EndIf; - + Counter = 0; - + For Each Part In ArrayReading Do - + Fields = New Structure; - Fields.Insert(Command , "APPEND"); - Fields.Insert("media_key" , InitializationKey); + Fields.Insert(Command , "APPEND"); + Fields.Insert("media_key" , InitializationKey); Fields.Insert("segment_index" , OPI_Tools.NumberToString(Counter)); - Fields.Insert("media" , Part); + Fields.Insert("media" , Part); Authorization = CreateAuthorizationHeaderV1(Parameters, New Structure, RequestType, URL); - + OPI_Tools.PostMultipart(URL, Fields, , , Authorization); - + Counter = Counter + 1; - + EndDo; - + Fields = New Structure; - Fields.Insert(Command , "FINALIZE"); + Fields.Insert(Command , "FINALIZE"); Fields.Insert("media_id", InitializationID); - + ProcessingStatus = GetProcessingStatus(Parameters, Fields, URL); - + If Not TypeOf(ProcessingStatus) = Type("String") Then Return ProcessingStatus; EndIf; - + Response = WaitForProcessingCompletion(ProcessingStatus, InitializationID, URL, Parameters); - + Return Response; - + EndFunction Function WaitForProcessingCompletion(Val ProcessingStatus, Val InitializationID, Val URL, Val Parameters) - + ProcessingInfo = "processing_info"; - Command = "command"; - Fields = New Structure; - - Fields.Insert(Command , "STATUS"); + Command = "command"; + Fields = New Structure; + + Fields.Insert(Command , "STATUS"); Fields.Insert("media_id", InitializationID); WHile String(ProcessingStatus) = "pending" Or String(ProcessingStatus) = "in_progress" Do - - Authorization = CreateAuthorizationHeaderV1(Parameters, Fields, "GET", URL); - Response = OPI_Tools.Get(URL, Fields, Authorization); - Information = Response[ProcessingInfo]; + + Authorization = CreateAuthorizationHeaderV1(Parameters, Fields, "GET", URL); + Response = OPI_Tools.Get(URL, Fields, Authorization); + Information = Response[ProcessingInfo]; If Not ValueIsFilled(Information) Then Return Response; EndIf; - + ProcessingStatus = Information["state"]; - + If Not ValueIsFilled(ProcessingStatus) Then Return Response; EndIf; - + EndDo; - + If ProcessingStatus = "failed" Then Raise "Twitter could not process the video you uploaded"; EndIf; - + Return Response; - + EndFunction Function GetStandardParameters(Val Parameters = "") - + // The definition of the data required for the work is collected here. // For Twitter, this is quite a significant set, which is due to the presence of 2 APIs at once, // which, at the same time, are not created for different tasks, but are simply versions of each other. // The current version of the API is v2 and it requires obtaining temporary tokens. Despite the fact, // that Twitter insists on using this latest version, they somehow managed not to transfer - // file upload mechanism and some others from the old version - v1.1. Therefore, something needs to be done + // file upload mechanism and some others from the old version - v1.1. Therefore, something needs to be done // on version 1.1, and something on 2: up to the point that they removed the ability to post tweets from v1.1, // but only through it you can add a picture to the tweet. At the same time, their authentication methods and tokens are different - + // The world gigacorporation of Elon Musk, by the way, a reminder ;) - - // P.S The following is often referred to as the "Twitter Developer settings page" - this + + // P.S The following is often referred to as the "Twitter Developer settings page" - this // https://developer.twitter.com/en/portal/dashboard and chosing of project from list (key icon) - - Parameters_ = New Map; + + Parameters_ = New Map; Permissions = "tweet.read tweet.write tweet.moderate.write users.read " + "follows.read follows.write offline.access space.read mute.read " + "mute.write like.read like.write list.read list.write block.read " - + "block.write bookmark.read bookmark.write"; - + + "block.write bookmark.read bookmark.write"; + // Data for API v2 - + // redirect_uri - URL of your http service (or other request handler) for authorization // scope - a set of permissions for the received key. Can be any, but offline.access is mandatory // client_id - From OAuth 2.0 Client ID and Client Secret settings page of Twitter Developer // client_secret - From OAuth 2.0 Client ID and Client Secret settings page of Twitter Developer // access_token - GetAuthorizationLink() -> Browser -> code will come to redirect_uri -> GetToken(code) // refresh_token - Comes together with access_token and is used to refresh it (access_token lifetime - 2 hr) - // The update is done using the UpdateToken method with new access_token and refresh_token. - // For the next update, you need to use a new refresh_token, so hardcode - // won't work (access_token won't work either) - + // The update is done using the UpdateToken method with new access_token and refresh_token. + // For the next update, you need to use a new refresh_token, so hardcode + // won't work (access_token won't work either) + // |--> RefreshToken() ->|access_token --> 2 hrs. lifetime // | |refresh_token --| // |--------[after 2 hrs.]-------------------| - + // Data for API v1.1 - - // oauth_token - From Authentication Tokens -> Access Token and Secret settings page of Twitter Developer + + // oauth_token - From Authentication Tokens -> Access Token and Secret settings page of Twitter Developer // oauth_token_secret - From Authentication Tokens -> Access Token and Secret settings page of Twitter Developer // oauth_consumer_key - From Consumer Keys -> Access Token and Secret settings page of Twitter Developer // oauth_consumer_secret - From Consumer Keys -> Access Token and Secret settings page of Twitter Developer - + // These tokens do not need to be updated - - Parameters_.Insert("redirect_uri" , ""); - Parameters_.Insert("scope" , Permissions); - Parameters_.Insert("client_id" , ""); - Parameters_.Insert("client_secret" , ""); - Parameters_.Insert("access_token" , ""); // Should be something like Constants.TwitterToken.Get() - Parameters_.Insert("refresh_token" , ""); // Should be something like Constants.TwitterRefresh.Get() - Parameters_.Insert("oauth_token" , ""); - Parameters_.Insert("oauth_token_secret" , ""); - Parameters_.Insert("oauth_consumer_key" , ""); + + Parameters_.Insert("redirect_uri" , ""); + Parameters_.Insert("scope" , Permissions); + Parameters_.Insert("client_id" , ""); + Parameters_.Insert("client_secret" , ""); + Parameters_.Insert("access_token" , ""); // Should be something like Constants.TwitterToken.Get() + Parameters_.Insert("refresh_token" , ""); // Should be something like Constants.TwitterRefresh.Get() + Parameters_.Insert("oauth_token" , ""); + Parameters_.Insert("oauth_token_secret" , ""); + Parameters_.Insert("oauth_consumer_key" , ""); Parameters_.Insert("oauth_consumer_secret", ""); - + OPI_TypeConversion.GetCollection(Parameters); - + If TypeOf(Parameters) = Type("Structure") Or TypeOf(Parameters) = Type("Map") Then For Each PassedParameter In Parameters Do Parameters_.Insert(PassedParameter.Key, OPI_Tools.NumberToString(PassedParameter.Value)); @@ -551,137 +551,137 @@ Function GetStandardParameters(Val Parameters = "") EndFunction Function CreateAuthorizationHeaderV1(Val Parameters, Val Fields, Val RequestType, Val URL) - - CurrentDate = OPI_Tools.GetCurrentDate(); + + CurrentDate = OPI_Tools.GetCurrentDate(); AuthorizationHeader = ""; - HashingMethod = "HMAC-SHA1"; - APIVersion = "1.0"; - SignatureString = ""; - Signature = ""; + HashingMethod = "HMAC-SHA1"; + APIVersion = "1.0"; + SignatureString = ""; + Signature = ""; OCK = "oauth_consumer_key"; OTK = "oauth_token"; - CurrentUNIXDate = OPI_Tools.UNIXTime(CurrentDate); - CurrentUNIXDate = OPI_Tools.NumberToString(CurrentUNIXDate); - ParametersTable = New ValueTable; + CurrentUNIXDate = OPI_Tools.UNIXTime(CurrentDate); + CurrentUNIXDate = OPI_Tools.NumberToString(CurrentUNIXDate); + ParametersTable = New ValueTable; ParametersTable.Columns.Add("Key"); ParametersTable.Columns.Add("Value"); - - For Each Field In Fields Do - - NewLine = ParametersTable.Add(); - NewLine.Key = Field.Key; + + For Each Field In Fields Do + + NewLine = ParametersTable.Add(); + NewLine.Key = Field.Key; NewLine.Value = Field.Value; - + EndDo; - - NewLine = ParametersTable.Add(); - NewLine.Key = OCK; + + NewLine = ParametersTable.Add(); + NewLine.Key = OCK; NewLine.Value = Parameters[OCK]; - - NewLine = ParametersTable.Add(); - NewLine.Key = OTK; + + NewLine = ParametersTable.Add(); + NewLine.Key = OTK; NewLine.Value = Parameters[OTK]; - - NewLine = ParametersTable.Add(); - NewLine.Key = "oauth_version"; + + NewLine = ParametersTable.Add(); + NewLine.Key = "oauth_version"; NewLine.Value = APIVersion; - - NewLine = ParametersTable.Add(); - NewLine.Key = "oauth_signature_method"; + + NewLine = ParametersTable.Add(); + NewLine.Key = "oauth_signature_method"; NewLine.Value = HashingMethod; - NewLine = ParametersTable.Add(); - NewLine.Key = "oauth_timestamp"; + NewLine = ParametersTable.Add(); + NewLine.Key = "oauth_timestamp"; NewLine.Value = CurrentUNIXDate; - NewLine = ParametersTable.Add(); - NewLine.Key = "oauth_nonce"; + NewLine = ParametersTable.Add(); + NewLine.Key = "oauth_nonce"; NewLine.Value = CurrentUNIXDate; For Each TableRow In ParametersTable Do - - TableRow.Key = EncodeString(TableRow.Key, StringEncodingMethod.URLencoding); + + TableRow.Key = EncodeString(TableRow.Key, StringEncodingMethod.URLencoding); TableRow.Value = EncodeString(TableRow.Value, StringEncodingMethod.URLencoding); - + EndDo; - + ParametersTable.Sort("Key"); - + For Each TableRow In ParametersTable Do - - SignatureString = SignatureString - + TableRow.Key - + "=" + + SignatureString = SignatureString + + TableRow.Key + + " =" + TableRow.Value + "&"; - + EndDo; - + SignatureString = Left(SignatureString, StrLen(SignatureString) - 1); - SignatureString = Upper(RequestType) - + "&" - + EncodeString(URL, StringEncodingMethod.URLencoding) + SignatureString = Upper(RequestType) + + "&" + + EncodeString(URL , StringEncodingMethod.URLencoding) + "&" + EncodeString(SignatureString, StringEncodingMethod.URLencoding); - + Signature = EncodeString(Parameters["oauth_consumer_secret"], StringEncodingMethod.URLencoding) - + "&" + + "&" + EncodeString(Parameters["oauth_token_secret"], StringEncodingMethod.URLencoding); - + Signature = OPI_Cryptography.HMAC(GetBinaryDataFromString(Signature) , GetBinaryDataFromString(SignatureString) , HashFunction.SHA1 , 64); - + Signature = EncodeString(Base64String(Signature), StringEncodingMethod.URLencoding); - + Delimiter = ""","; - AuthorizationHeader = AuthorizationHeader + AuthorizationHeader = AuthorizationHeader + "OAuth " - + "oauth_consumer_key=""" + Parameters[OCK] + Delimiter - + "oauth_token=""" + Parameters[OTK] + Delimiter + + "oauth_consumer_key =""" + Parameters[OCK] + Delimiter + + "oauth_token =""" + Parameters[OTK] + Delimiter + "oauth_signature_method=""" + HashingMethod + Delimiter - + "oauth_timestamp=""" + CurrentUNIXDate + Delimiter - + "oauth_nonce=""" + CurrentUNIXDate + Delimiter - + "oauth_version=""" + APIVersion + Delimiter - + "oauth_signature=""" + Signature; - + + "oauth_timestamp =""" + CurrentUNIXDate + Delimiter + + "oauth_nonce =""" + CurrentUNIXDate + Delimiter + + "oauth_version =""" + APIVersion + Delimiter + + "oauth_signature =""" + Signature; + HeaderMapping = New Map; HeaderMapping.Insert("authorization", AuthorizationHeader); - + Return HeaderMapping; - + EndFunction Function CreateAuthorizationHeaderV2(Val Parameters) - + ReturnMapping = New Map; ReturnMapping.Insert("Authorization", "Bearer " + Parameters["access_token"]); - + Return ReturnMapping; - + EndFunction Function GetProcessingStatus(Val Parameters, Val Fields, Val URL) - ProcessingInfo = "processing_info"; + ProcessingInfo = "processing_info"; Authorization = CreateAuthorizationHeaderV1(Parameters, Fields, "POST", URL); - - Response = OPI_Tools.Post(URL, Fields, Authorization, False); + + Response = OPI_Tools.Post(URL, Fields, Authorization, False); Information = Response[ProcessingInfo]; - + If Not ValueIsFilled(Information) Then Return Response; EndIf; - + ProcessingStatus = Information["state"]; - + If Not ValueIsFilled(ProcessingStatus) Then Return Response; Else Return ProcessingStatus; - EndIf; - + EndIf; + EndFunction #EndRegion diff --git a/src/en/OInt/core/Modules/OPI_VK.os b/src/en/OInt/core/Modules/OPI_VK.os index 174d6b6743..de06a8cd58 100644 --- a/src/en/OInt/core/Modules/OPI_VK.os +++ b/src/en/OInt/core/Modules/OPI_VK.os @@ -22,7 +22,7 @@ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. +// SOFTWARE. // https://github.com/Bayselonarrend/OpenIntegrations // If you don't know where to start, you should find the GetStandardParameters method() @@ -51,37 +51,37 @@ // Create token retrieval link // Getting a link for interactive token retrieval (access_token), which is necessary // for further actions -// +// // Parameters: // app_id - String, Number - app_id from application settings - app -// +// // Returns: -// String - URL to go to in the browser +// String - URL to go to in the browser Function CreateTokenRetrievalLink(Val App_id) Export - + OPI_TypeConversion.GetLine(App_id); - + // access_token will need to be taken from the parameter in the browser address bar Return "https://oauth.vk.com/authorize?client_id=" + App_id + "&scope=offline,wall,groups,photos,stats,stories,ads,market,video" + "&v=5.131&response_type=token&redirect_uri=https://api.vk.com/blank.html"; - + EndFunction - + #EndRegion #Region CommunityManagment // Create post // Creates a post with images -// +// // Parameters: // Text - String - Post text - text -// ImageArray - Array of String, BinaryData - Array of images - pictures +// ImageArray - Array of String, BinaryData - Array of images - pictures // Advertisement - Boolean - Sign ""This is an ad"" - ad // LinkUnderPost - String - Link (URL) under the post - url // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function CreatePost(Val Text @@ -89,49 +89,49 @@ Function CreatePost(Val Text , Val Advertisement = False , Val LinkUnderPost = "" , Val Parameters = "") Export - + OPI_TypeConversion.GetCollection(ImageArray); - - Parameters_ = GetStandardParameters(Parameters); - AttachmentsArray = New Array; - + + Parameters_ = GetStandardParameters(Parameters); + AttachmentsArray = New Array; + For Each PostImage In ImageArray Do - + Parameters_ = GetStandardParameters(Parameters); ResponseMap = GetImageMap(PostImage, Parameters_, "Post"); - - OwnerId = ResponseMap.Get("owner_id"); + + OwnerId = ResponseMap.Get("owner_id"); ObjectId = ResponseMap.Get("id"); - + If Not ValueIsFilled(OwnerId) Or Not ValueIsFilled(ObjectId) Then Return ResponseMap; EndIf; - - OwnerId = OPI_Tools.NumberToString(OwnerId); + + OwnerId = OPI_Tools.NumberToString(OwnerId); ObjectId = OPI_Tools.NumberToString(ObjectId); - - PhotoID = "photo" + OwnerId + "_" + ObjectId; + + PhotoID = "photo" + OwnerId + "_" + ObjectId; AttachmentsArray.Add(PhotoID); - + EndDo; Response = CreateCompositePost(Text, AttachmentsArray, Advertisement, LinkUnderPost, Parameters); - + Return Response; - + EndFunction // Create composite post // Creates a post based on an array of object identifiers (images, videos, etc..) -// +// // Parameters: // Text - String - Post text - text -// Objects - Array of String - Array of identifiers like photo123_123 - objects +// Objects - Array of String - Array of identifiers like photo123_123 - objects // Advertisement - Boolean - Sign ""This is an ad"" - ad // LinkUnderPost - String - Link (URL) under the post - url // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function CreateCompositePost(Val Text @@ -139,24 +139,24 @@ Function CreateCompositePost(Val Text , Val Advertisement = False , Val LinkUnderPost = "" , Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Text); - OPI_TypeConversion.GetLine(LinkUnderPost); + OPI_TypeConversion.GetLine(LinkUnderPost); OPI_TypeConversion.GetBoolean(Advertisement); - - Parameters = GetStandardParameters(Parameters); - AttachmentsString = StrConcat(Objects, ","); + + Parameters = GetStandardParameters(Parameters); + AttachmentsString = StrConcat(Objects, ","); AttachmentsString = AttachmentsString + LinkUnderPost; - - Parameters.Insert("message" , Text); - Parameters.Insert("attachments" , AttachmentsString); - Parameters.Insert("mark_as_ads" , ?(Advertisement, 1, 0)); + + Parameters.Insert("message" , Text); + Parameters.Insert("attachments" , AttachmentsString); + Parameters.Insert("mark_as_ads" , ?(Advertisement, 1, 0)); Parameters.Insert("close_comments" , ?(Advertisement, 1, 0)); Response = OPI_Tools.Get("api.vk.com/method/wall.post", Parameters); - + Return Response; - + EndFunction // Delete post @@ -165,20 +165,20 @@ EndFunction // Parameters: // PostID - String, Number - Post ID - post // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function DeletePost(Val PostID, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(PostID); - - Parameters_ = GetStandardParameters(Parameters); + + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("post_id", PostID); - + Response = OPI_Tools.Get("api.vk.com/method/wall.delete", Parameters_); - + Return Response; - + EndFunction // Create poll @@ -189,72 +189,72 @@ EndFunction // AnswersArray - Array of String - Array of answer options - options // Image - String, BinaryData - Poll image - picture // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function CreatePoll(Val Question, Val AnswersArray, Val Image = "", Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Question); OPI_TypeConversion.GetCollection(AnswersArray); - + Parameters_ = GetStandardParameters(Parameters); - Response_ = "response"; + Response_ = "response"; If ValueIsFilled(Image) Then - + Response = UploadPhotoToServer(Image, Parameters_, "Poll"); - + Photo = Response.Get(Response_); - + If ValueIsFilled(Photo) Then - + PhotoID = Photo["id"]; - + If Not ValueIsFilled(PhotoID) Then Return Response; EndIf; - + Else Return Response; EndIf; - + EndIf; - + Parameters_.Insert("is_anonymous", 1); Parameters_.Insert("is_multiple" , 0); - + Answers = StrConcat(AnswersArray, ""","""); - Answers = "[""" + Answers + """]"; - + Answers = "[""" + Answers + """]"; + Parameters_.Insert("add_answers", Answers); - Parameters_.Insert("photo_id" , OPI_Tools.NumberToString(PhotoID)); - Parameters_.Insert("question" , Question); - - Poll = OPI_Tools.Get("api.vk.com/method/polls.create", Parameters_); + Parameters_.Insert("photo_id" , OPI_Tools.NumberToString(PhotoID)); + Parameters_.Insert("question" , Question); + + Poll = OPI_Tools.Get("api.vk.com/method/polls.create", Parameters_); PollMap = Poll.Get(Response_); - + If Not ValueIsFilled(PollMap) Then Return Poll; EndIf; - - OwnerId = PollMap.Get("owner_id"); + + OwnerId = PollMap.Get("owner_id"); ObjectId = PollMap.Get("id"); - + If Not ValueIsFilled(OwnerId) Or Not ValueIsFilled(ObjectId) Then Return Poll; EndIf; - + PollID = "poll" + OPI_Tools.NumberToString(OwnerId) - + "_" + + "_" + OPI_Tools.NumberToString(ObjectId); - + Parameters_.Insert("attachments", PollID); - + Response = OPI_Tools.Get("api.vk.com/method/wall.post", Parameters_); - + Return Response; - + EndFunction // Create album @@ -264,24 +264,24 @@ EndFunction // Name - String - Album name - title // Description - String - Album description - description // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function CreateAlbum(Val Name, Val Description = "", Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Name); OPI_TypeConversion.GetLine(Description); - + Parameters_ = GetStandardParameters(Parameters); - - Parameters_.Insert("title" , Name); - Parameters_.Insert("description" , Description); + + Parameters_.Insert("title" , Name); + Parameters_.Insert("description" , Description); Parameters_.Insert("upload_by_admins_only", 1); - + Response = OPI_Tools.Get("api.vk.com/method/photos.createAlbum", Parameters_); - + Return Response; - + EndFunction // Delete album @@ -290,20 +290,20 @@ EndFunction // Parameters: // AlbumID - String, Number - Album ID - album // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function DeleteAlbum(Val AlbumID, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(AlbumID); - - Parameters_ = GetStandardParameters(Parameters); + + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("album_id", OPI_Tools.NumberToString(AlbumID)); - + Response = OPI_Tools.Get("api.vk.com/method/photos.deleteAlbum", Parameters_); - + Return Response; - + EndFunction // Create story @@ -313,187 +313,187 @@ EndFunction // Image - String, BinaryData - Story background - picture // URL - String - URL for button under the story - url // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function CreateStory(Val Image, Val URL = "", Val Parameters = "") Export - + OPI_TypeConversion.GetLine(URL); - + Parameters_ = GetStandardParameters(Parameters); - Parameters_.Insert("link_text" , "more"); - Parameters_.Insert("link_url" , URL); + Parameters_.Insert("link_text" , "more"); + Parameters_.Insert("link_url" , URL); Parameters_.Insert("add_to_news", "1"); - - Response = UploadPhotoToServer(Image, Parameters_, "Story"); + + Response = UploadPhotoToServer(Image, Parameters_, "Story"); Return Response; - + EndFunction // Save image to album // Saves an image to the community album // // Parameters: -// AlbumID - String, Number - Album ID - album +// AlbumID - String, Number - Album ID - album // Image - BinaryData,String - Image file - picture // Description - String - Image description - description // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function SaveImageToAlbum(Val AlbumID, Val Image, Val Description = "", Val Parameters = "") Export - + OPI_TypeConversion.GetLine(AlbumID); OPI_TypeConversion.GetLine(Description); - + Parameters_ = GetStandardParameters(Parameters); - + Parameters_.Insert("album_id", AlbumID); Parameters_.Insert("caption" , Description); - + Return UploadPhotoToServer(Image, Parameters_, "Album"); - + EndFunction // Delete image // Deletes an image from the album // // Parameters: -// ImageID - String, Number - Image ID - pictureid +// ImageID - String, Number - Image ID - pictureid // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function DeleteImage(Val ImageID, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(ImageID); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("photo_id", ImageID); - + Response = OPI_Tools.Get("api.vk.com/method/photos.delete", Parameters_); - + Return Response; - + EndFunction // Upload video to server // Uploads video to the group for further use -// +// // Parameters: // Video - String, BinaryData - Video file - file // Name - String - Video name - title // Description - String - Video description - description // Album - String - Album ID, if necessary - album // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: -// Map Of KeyAndValue - Serialized JSON response from VK +// Map Of KeyAndValue - Serialized JSON response from VK Function UploadVideoToServer(Val Video , Val Name , Val Description = "" , Val Album = "" , Val Parameters = "") Export - - String_ = "String"; + + String_ = "String"; Parameters = GetStandardParameters(Parameters); - - OPI_Tools.AddField("name" , Name, String_, Parameters); + + OPI_Tools.AddField("name" , Name , String_, Parameters); OPI_Tools.AddField("description", Description , String_, Parameters); - OPI_Tools.AddField("album_id" , Album , String_, Parameters); - + OPI_Tools.AddField("album_id" , Album , String_, Parameters); + Response = OPI_Tools.Get("api.vk.com/method/video.save", Parameters); - + Result = Response["response"]; - + If Not ValueIsFilled(Result) Then Return Response; EndIf; - + URL = Result["upload_url"]; - + If Not ValueIsFilled(URL) Then Return Response; EndIf; - + FileMapping = New Map; OPI_Tools.AddField("video_file.mp4", Video, "BinaryData", FileMapping); - + DataSize = FileMapping["video_file.mp4"].Size(); DataSize = OPI_Tools.NumberToString(DataSize); - + Response = OPI_Tools.PostMultipart(URL, , FileMapping, "video/mp4"); - + Return Response; - + EndFunction // Upload photo to server // Uploads photo to server for further use -// +// // Parameters: // Image - String, BinaryData - Image file - file // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json // View - String - Upload type (Post, Product, Story, Poll, Other) - type -// +// // Returns: -// Map Of KeyAndValue - Serialized JSON response from VK +// Map Of KeyAndValue - Serialized JSON response from VK Function UploadPhotoToServer(Val Image, Val Parameters = "", Val View = "Post") Export - + Parameters = GetStandardParameters(Parameters); - Method = DetermineImageUploadMethod(View); - Files = New Map; - + Method = DetermineImageUploadMethod(View); + Files = New Map; + Response_ = "response"; - URL = "api.vk.com/method/"; - Upload = URL + Method["Upload"]; - Save = URL + Method["Save"]; - + URL = "api.vk.com/method/"; + Upload = URL + Method["Upload"]; + Save = URL + Method["Save"]; + If TypeOf(Image) = Type("String") Then - ImageKey = StrReplace(Image, ".", "___"); + ImageKey = StrReplace(Image, ".", "___"); OPI_TypeConversion.GetBinaryData(Image); Else - ImageKey = "image___jpeg"; + ImageKey = "image___jpeg"; EndIf; - + Files.Insert(ImageKey, Image); - + For N = 1 To 5 Do - - Response = OPI_Tools.Get(Upload, Parameters); - Result = Response[Response_]; - + + Response = OPI_Tools.Get(Upload, Parameters); + Result = Response[Response_]; + If ValueIsFilled(Result) Then - + URL = Result["upload_url"]; - + If Not ValueIsFilled(URL) Then Return Response; EndIf; - + Else Return Response; EndIf; - + Parameters.Insert("upload_url", URL); Response = OPI_Tools.PostMultipart(URL, Parameters, Files); - + If TypeOf(Response) = Type("Map") Then Break; EndIf; - + EndDo; - + If TypeOf(Response) <> Type("Map") Then Return GetStringFromBinaryData(Response); EndIf; FillPhotoUploadParameters(Method, Response, Parameters); - + Response = OPI_Tools.Get(Save, Parameters); - + Return Response; - + EndFunction #EndRegion @@ -507,22 +507,22 @@ EndFunction // Name - String - Discussion name - title // FirstMessageText - String - Text of the first message - text // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function CreateDiscussion(Val Name, Val FirstMessageText, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Name); OPI_TypeConversion.GetLine(FirstMessageText); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("title", Name); Parameters_.Insert("text" , FirstMessageText); - + Response = OPI_Tools.Get("api.vk.com/method/board.addTopic", Parameters_); - + Return Response; - + EndFunction // Close discussion @@ -532,20 +532,20 @@ EndFunction // DiscussionID - String, Number - Discussion ID - topic // DeleteCompletely - Boolean - Delete completely (True) or close - remove // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function CloseDiscussion(Val DiscussionID, Val DeleteCompletely = False, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(DiscussionID); OPI_TypeConversion.GetBoolean(DeleteCompletely); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("topic_id", DiscussionID); - - Method = ?(DeleteCompletely, "deleteTopic", "closeTopic"); + + Method = ?(DeleteCompletely, "deleteTopic", "closeTopic"); Response = OPI_Tools.Get("api.vk.com/method/board." + Method, Parameters_); - + Return Response; EndFunction @@ -556,18 +556,18 @@ EndFunction // Parameters: // DiscussionID - String, Number - Discussion ID - topic // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function OpenDiscussion(Val DiscussionID, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(DiscussionID); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("topic_id", DiscussionID); - + Response = OPI_Tools.Get("api.vk.com/method/board.openTopic", Parameters_); - + Return Response; EndFunction @@ -579,20 +579,20 @@ EndFunction // DiscussionID - String, Number - Discussion ID - topic // Text - String - Message text - text // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function WriteInDiscussion(Val DiscussionID, Val Text, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(DiscussionID); OPI_TypeConversion.GetLine(Text); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("topic_id", DiscussionID); Parameters_.Insert("message" , Text); - + Response = OPI_Tools.Get("api.vk.com/method/board.createComment", Parameters_); - + Return Response; EndFunction @@ -608,26 +608,26 @@ EndFunction // PostID - String, Number - Post ID - post // WallID - String, Number - ID of the wall where the post is located - wall // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function LikePost(Val PostID, Val WallID = "", Val Parameters = "") Export - + OPI_TypeConversion.GetLine(PostID); OPI_TypeConversion.GetLine(WallID); - + Parameters_ = GetStandardParameters(Parameters); - WallID = ?(ValueIsFilled(WallID), WallID, Parameters_["owner_id"]); - VKObject = "wall" + WallID + "_" + OPI_Tools.NumberToString(PostID); - - Parameters_.Insert("type" , "post"); - Parameters_.Insert("object" , VKObject); - Parameters_.Insert("item_id" , OPI_Tools.NumberToString(PostID)); - Parameters_.Insert("owner_id" , OPI_Tools.NumberToString(WallID)); + WallID = ?(ValueIsFilled(WallID), WallID, Parameters_["owner_id"]); + VKObject = "wall" + WallID + "_" + OPI_Tools.NumberToString(PostID); + + Parameters_.Insert("type" , "post"); + Parameters_.Insert("object" , VKObject); + Parameters_.Insert("item_id" , OPI_Tools.NumberToString(PostID)); + Parameters_.Insert("owner_id" , OPI_Tools.NumberToString(WallID)); Parameters_.Insert("from_group" , 0); - + Response = OPI_Tools.Get("api.vk.com/method/likes.add", Parameters_); - + Return Response; EndFunction @@ -641,7 +641,7 @@ EndFunction // TargetWall - String, Number - ID of the target wall or group - to // Advertising - Boolean - Sign of an advertising post - ad // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function MakeRepost(Val PostID @@ -649,25 +649,25 @@ Function MakeRepost(Val PostID , Val TargetWall = "" , Val Advertising = False , Val Parameters = "") Export - + Parameters_ = GetStandardParameters(Parameters); - GroupId = Parameters_["group_id"]; - + GroupId = Parameters_["group_id"]; + OPI_TypeConversion.GetLine(GroupId); OPI_TypeConversion.GetLine(PostID); OPI_TypeConversion.GetLine(WallID); OPI_TypeConversion.GetLine(TargetWall); OPI_TypeConversion.GetBoolean(Advertising); - - Source = ?(ValueIsFilled(WallID), WallID, GroupId); + + Source = ?(ValueIsFilled(WallID), WallID, GroupId); Receiver = ?(ValueIsFilled(TargetWall), TargetWall, GroupId); - Parameters_.Insert("object" , "wall" + Source + "_" + OPI_Tools.NumberToString(PostID)); - Parameters_.Insert("group_id" , StrReplace(Receiver, "-", "")); - Parameters_.Insert("mark_as_ads" , ?(Advertising, 1, 0)); - + Parameters_.Insert("object" , "wall" + Source + "_" + OPI_Tools.NumberToString(PostID)); + Parameters_.Insert("group_id" , StrReplace(Receiver, "-", "")); + Parameters_.Insert("mark_as_ads" , ?(Advertising , 1 , 0)); + Response = OPI_Tools.Get("api.vk.com/method/wall.repost", Parameters_); - + Return Response; EndFunction @@ -681,7 +681,7 @@ EndFunction // Communitytoken - String - Community chat bot token, which can be obtained in the settings - ct // Keyboard - String - JSON keyboard. See FormKeyboard - keyboard // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function WriteMessage(Val Text @@ -689,27 +689,27 @@ Function WriteMessage(Val Text , Val Communitytoken , Val Keyboard = "" , Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Text); OPI_TypeConversion.GetLine(UserID); OPI_TypeConversion.GetLine(Communitytoken); OPI_TypeConversion.GetLine(Keyboard); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("access_token", Communitytoken); - - Parameters_.Insert("user_id" , UserID); - Parameters_.Insert("peer_id" , UserID); - Parameters_.Insert("parse_mode" , "Markdown"); - Parameters_.Insert("random_id" , 0); - Parameters_.Insert("message" , Text); - + + Parameters_.Insert("user_id" , UserID); + Parameters_.Insert("peer_id" , UserID); + Parameters_.Insert("parse_mode" , "Markdown"); + Parameters_.Insert("random_id" , 0); + Parameters_.Insert("message" , Text); + If ValueIsFilled(Keyboard) Then Parameters_.Insert("keyboard", Keyboard); EndIf; - + Response = OPI_Tools.Get("api.vk.com/method/messages.send", Parameters_); - + Return Response; EndFunction @@ -722,28 +722,28 @@ EndFunction // WallID - String, Number - ID of the wall where the post is located - wall // Text - String - Comment text - text // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function WriteComment(Val PostID, Val WallID, Val Text, Val Parameters = "") Export Parameters_ = GetStandardParameters(Parameters); - GroupId = Parameters_["group_id"]; - + GroupId = Parameters_["group_id"]; + OPI_TypeConversion.GetLine(GroupId); OPI_TypeConversion.GetLine(PostID); OPI_TypeConversion.GetLine(WallID); OPI_TypeConversion.GetLine(Text); - - Parameters_.Insert("owner_id" , WallID); + + Parameters_.Insert("owner_id" , WallID); Parameters_.Insert("from_group" , GroupId); - Parameters_.Insert("post_id" , PostID); - Parameters_.Insert("message" , Text); - + Parameters_.Insert("post_id" , PostID); + Parameters_.Insert("message" , Text); + Parameters_.Delete("group_id"); - + Response = OPI_Tools.Get("api.vk.com/method/wall.createComment", Parameters_); - + Return Response; EndFunction @@ -754,35 +754,35 @@ EndFunction // Parameters: // URL - String - URL for shortening - url // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: -// String - Shortened URL +// String - Shortened URL Function ShortenLink(Val URL, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(URL); - - Response_ = "response"; + + Response_ = "response"; Parameters_ = New Structure; - Parameters_ = GetStandardParameters(Parameters); + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("url", URL); - + Response = OPI_Tools.Get("https://api.vk.com/method/utils.getShortLink", Parameters_); - Result = Response[Response_]; - + Result = Response[Response_]; + If ValueIsFilled(Result) Then - + URL = Result["short_url"]; - + If ValueIsFilled(URL) Then Return URL; Else Return Response; EndIf; - + Else Return Response; EndIf; - + EndFunction #EndRegion @@ -796,27 +796,27 @@ EndFunction // StartDate - Date - Start date of the period - datefrom // EndDate - Date - End date of the period - dateto // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function GetStatistics(Val StartDate, Val EndDate, Val Parameters = "") Export - + OPI_TypeConversion.GetDate(StartDate); OPI_TypeConversion.GetDate(EndDate); - + Parameters_ = GetStandardParameters(Parameters); - + StartDate = OPI_Tools.UNIXTime(StartDate); - EndDate = OPI_Tools.UNIXTime(EndDate); - + EndDate = OPI_Tools.UNIXTime(EndDate); + Parameters_.Insert("timestamp_from", StartDate); - Parameters_.Insert("timestamp_to" , EndDate); - Parameters_.Insert("stats_groups" , "visitors, reach, activity"); - + Parameters_.Insert("timestamp_to" , EndDate); + Parameters_.Insert("stats_groups" , "visitors, reach, activity"); + Response = OPI_Tools.Get("api.vk.com/method/stats.get", Parameters_); - + Return Response; - + EndFunction // Get post statistics @@ -825,47 +825,47 @@ EndFunction // Parameters: // PostIDsArray - Array of String,Number - Array of post IDs - posts // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Array of Arbitrary - Array of post statistics data Function GetPostStatistics(Val PostIDsArray, Val Parameters = "") Export - + OPI_TypeConversion.GetCollection(PostIDsArray); - - Parameters_ = GetStandardParameters(Parameters); + + Parameters_ = GetStandardParameters(Parameters); AnswersArray = New Array; - SetsArray = New Array; + SetsArray = New Array; MaximumPosts = 30; - Response_ = "response"; - + Response_ = "response"; + For Each Post In PostIDsArray Do - + SetsArray.Add(OPI_Tools.NumberToString(Post)); - + If SetsArray.Count() = MaximumPosts Then - + NumbersString = StrConcat(SetsArray, ","); Parameters_.Insert("post_ids", NumbersString); - - Statistics = OPI_Tools.Get("api.vk.com/method/stats.getPostReach", Parameters_); + + Statistics = OPI_Tools.Get("api.vk.com/method/stats.getPostReach", Parameters_); StatisticsArray = Statistics[Response_]; - + For Each StatisticsItem In StatisticsArray Do AnswersArray.Add(StatisticsItem); EndDo; - + SetsArray = New Array; - + EndIf; - + EndDo; - + NumbersString = StrConcat(SetsArray, ","); Parameters_.Insert("post_ids", NumbersString); - - Statistics = OPI_Tools.Get("api.vk.com/method/stats.getPostReach", Parameters_); + + Statistics = OPI_Tools.Get("api.vk.com/method/stats.getPostReach", Parameters_); StatisticsArray = Statistics[Response_]; - + If TypeOf(StatisticsArray) = Type("Array") Then For Each StatisticsItem In StatisticsArray Do AnswersArray.Add(StatisticsItem); @@ -873,9 +873,9 @@ Function GetPostStatistics(Val PostIDsArray, Val Parameters = "") Export EndIf; Return AnswersArray; - + EndFunction - + #EndRegion #Region AdAccountManagement @@ -887,43 +887,43 @@ EndFunction // AccountID - String, Number - Advertising account ID - cabinet // Name - String - Campaign name - title // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function CreateAdvertisingCampaign(Val AccountID, Val Name, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(AccountID); OPI_TypeConversion.GetLine(Name); - + CurrentDate = OPI_Tools.GetCurrentDate(); - EndDate = AddMonth(CurrentDate, 24); - - Parameters_ = GetStandardParameters(Parameters); + EndDate = AddMonth(CurrentDate, 24); + + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("account_id", AccountID); - + StructuresArray = New Array; - StartDate = OPI_Tools.UNIXTime(CurrentDate); - EndDate = OPI_Tools.UNIXTime(EndDate); - + StartDate = OPI_Tools.UNIXTime(CurrentDate); + EndDate = OPI_Tools.UNIXTime(EndDate); + CampaignStructure = New Structure; - CampaignStructure.Insert("type" , "promoted_posts"); - CampaignStructure.Insert("name" , Name); - CampaignStructure.Insert("day_limit" , 0); - CampaignStructure.Insert("all_limit" , 0); + CampaignStructure.Insert("type" , "promoted_posts"); + CampaignStructure.Insert("name" , Name); + CampaignStructure.Insert("day_limit" , 0); + CampaignStructure.Insert("all_limit" , 0); CampaignStructure.Insert("start_time" , StartDate); - CampaignStructure.Insert("stop_time" , EndDate); - CampaignStructure.Insert("status" , 1); - + CampaignStructure.Insert("stop_time" , EndDate); + CampaignStructure.Insert("status" , 1); + StructuresArray.Add(CampaignStructure); - + JSONDate = OPI_Tools.JSONString(StructuresArray); - + Parameters_.Insert("data", JSONDate); - + Response = OPI_Tools.Get("api.vk.com/method/ads.createCampaigns", Parameters_); - + Return Response; - + EndFunction // Create advertising post @@ -936,7 +936,7 @@ EndFunction // PostID - String, Number - ID of the post used for advertising - post // AccountID - String, Number - Advertising account ID - cabinet // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function CreateAd(Val CampaignNumber @@ -945,49 +945,49 @@ Function CreateAd(Val CampaignNumber , Val PostID , Val AccountID , Val Parameters = "") Export - - Parameters_ = GetStandardParameters(Parameters); - GroupId = Parameters_["group_id"]; - + + Parameters_ = GetStandardParameters(Parameters); + GroupId = Parameters_["group_id"]; + OPI_TypeConversion.GetLine(GroupId); OPI_TypeConversion.GetLine(CampaignNumber); OPI_TypeConversion.GetLine(DailyLimit); OPI_TypeConversion.GetLine(CategoryNumber); OPI_TypeConversion.GetLine(PostID); OPI_TypeConversion.GetLine(AccountID); - + Link = "https://vk.com/wall-" + GroupId + "_" + PostID; - - StructuresArray = New Array; + + StructuresArray = New Array; CampaignStructure = New Structure; - CampaignStructure.Insert("campaign_id" , CampaignNumber); - CampaignStructure.Insert("ad_format" , 9); - CampaignStructure.Insert("conversion_event_id" , 1); - CampaignStructure.Insert("autobidding" , 1); - CampaignStructure.Insert("cost_type" , 3); - CampaignStructure.Insert("goal_type" , 2); - CampaignStructure.Insert("ad_platform" , "all"); - CampaignStructure.Insert("publisher_platforms" , "vk"); + CampaignStructure.Insert("campaign_id" , CampaignNumber); + CampaignStructure.Insert("ad_format" , 9); + CampaignStructure.Insert("conversion_event_id" , 1); + CampaignStructure.Insert("autobidding" , 1); + CampaignStructure.Insert("cost_type" , 3); + CampaignStructure.Insert("goal_type" , 2); + CampaignStructure.Insert("ad_platform" , "all"); + CampaignStructure.Insert("publisher_platforms" , "vk"); CampaignStructure.Insert("publisher_platforms_auto" , "1"); - CampaignStructure.Insert("day_limit" , DailyLimit); - CampaignStructure.Insert("all_limit" , "0"); - CampaignStructure.Insert("category1_id" , CategoryNumber); - CampaignStructure.Insert("age_restriction" , 0); - CampaignStructure.Insert("status" , 1); - CampaignStructure.Insert("name" , "Ad"); - CampaignStructure.Insert("link_url" , Link); - + CampaignStructure.Insert("day_limit" , DailyLimit); + CampaignStructure.Insert("all_limit" , "0"); + CampaignStructure.Insert("category1_id" , CategoryNumber); + CampaignStructure.Insert("age_restriction" , 0); + CampaignStructure.Insert("status" , 1); + CampaignStructure.Insert("name" , "Ad"); + CampaignStructure.Insert("link_url" , Link); + StructuresArray.Add(CampaignStructure); - + OPI_TypeConversion.GetLine(StructuresArray, True); - - Parameters_.Insert("data" , StructuresArray); + + Parameters_.Insert("data" , StructuresArray); Parameters_.Insert("account_id" , AccountID); - + Response = OPI_Tools.Get("api.vk.com/method/ads.createAds", Parameters_); - + Return Response; - + EndFunction // Pause advertising post @@ -995,36 +995,36 @@ EndFunction // // Parameters: // AccountID - String, Number - Advertising account ID - cabinet -// AdID - String, Number - Ad ID - adv +// AdID - String, Number - Ad ID - adv // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function PauseAdvertising(Val AccountID, Val AdID, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(AccountID); OPI_TypeConversion.GetLine(AdID); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("account_id", AccountID); - - StructuresArray = New Array; + + StructuresArray = New Array; CampaignStructure = New Structure; - - CampaignStructure.Insert("ad_id" , AdID); + + CampaignStructure.Insert("ad_id" , AdID); CampaignStructure.Insert("status" , 0); - + StructuresArray.Add(CampaignStructure); - + OPI_TypeConversion.GetLine(StructuresArray, True); - + Parameters_.Insert("data", StructuresArray); - + Response = OPI_Tools.Get("api.vk.com/method/ads.updateAds", Parameters_); - + Return Response; - + EndFunction // Get a list of advertising categories @@ -1032,14 +1032,14 @@ EndFunction // // Parameters: // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function GetAdvertisingCategoryList(Val Parameters = "") Export - + Parameters_ = GetStandardParameters(Parameters); - Response = OPI_Tools.Get("api.vk.com/method/ads.getCategories", Parameters_); - + Response = OPI_Tools.Get("api.vk.com/method/ads.getCategories", Parameters_); + Return Response; EndFunction @@ -1053,52 +1053,52 @@ EndFunction // // Parameters: // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of String - Key - ID, Value - Name Function GetProductCategoryList(Val Parameters = "") Export - - Response_ = "response"; + + Response_ = "response"; Parameters_ = GetStandardParameters(Parameters); - Response = OPI_Tools.Get("api.vk.com/method/market.getCategories", Parameters_); - Result = Response[Response_]; - + Response = OPI_Tools.Get("api.vk.com/method/market.getCategories", Parameters_); + Result = Response[Response_]; + If ValueIsFilled(Result) Then - + Count = Result["count"]; - + If Not ValueIsFilled(Count) Then Return Response; EndIf; - + Else Return Response; EndIf; - + Parameters_.Insert("count", Count); - Response = OPI_Tools.Get("api.vk.com/method/market.getCategories", Parameters_); - Result = Response[Response_]; - + Response = OPI_Tools.Get("api.vk.com/method/market.getCategories", Parameters_); + Result = Response[Response_]; + If ValueIsFilled(Result) Then - + Categories = Result["items"]; - + If Not ValueIsFilled(Categories) Then Return Response; EndIf; - + Else Return Response; EndIf; - + CategoryMap = New Map; - - For Each Category In Categories Do + + For Each Category In Categories Do CategoryMap.Insert(Category["id"], Category["name"]); EndDo; - + Return CategoryMap; - + EndFunction // Get product list @@ -1107,60 +1107,60 @@ EndFunction // Parameters: // Selection - String, Number - Selection ID, if filtering is needed - sel // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Array of product maps Function GetProductList(Val Selection = "", Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Selection); - + Parameters_ = GetStandardParameters(Parameters); - Parameters_.Insert("count" , 200); - Parameters_.Insert("extended" , 1); + Parameters_.Insert("count" , 200); + Parameters_.Insert("extended" , 1); Parameters_.Insert("with_disabled", 1); - + If ValueIsFilled(Selection) Then - Parameters_.Insert("album_id", Selection); + Parameters_.Insert("album_id", Selection); EndIf; - + ProductsArray = New Array; GetProductListRecursively(ProductsArray, Parameters_); - + Return ProductsArray; - + EndFunction // Get products by ID // Gets information about products by array of IDs // // Parameters: -// Products - String, Array of String - Array of product IDs - items +// Products - String, Array of String - Array of product IDs - items // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function GetProductsByID(Val Products, Val Parameters = "") Export - + OPI_TypeConversion.GetCollection(Products); - - Parameters_ = GetStandardParameters(Parameters); + + Parameters_ = GetStandardParameters(Parameters); ProductsString = ""; - Owner = "owner_id"; - - For Each Product In Products Do + Owner = "owner_id"; + + For Each Product In Products Do CurrentProduct = Parameters_[Owner] + "_" + Product; CurrentProduct = OPI_Tools.NumberToString(CurrentProduct); ProductsString = ProductsString + CurrentProduct + ","; EndDo; - + ProductsString = Left(ProductsString, StrLen(ProductsString) - 1); Parameters_.Insert("item_ids", ProductsString); Parameters_.Insert("extended", 1); - + Response = OPI_Tools.Get("api.vk.com/method/market.getById", Parameters_); - + Return Response; - + EndFunction // Add product @@ -1170,13 +1170,13 @@ EndFunction // ProductDescription - Map Of KeyAndValue - See GetProductDescription - product - JSON description of the product or path // Selection - String - Selection ID for placing the product, if needed - sel // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK -Function AddProduct(Val ProductDescription, Val Selection = "", Val Parameters = "") Export - - Return ProductManagement(ProductDescription, , Selection, Parameters); - +Function AddProduct(Val ProductDescription, Val Selection = "", Val Parameters = "") Export + + Return ProductManagement(ProductDescription, , Selection, Parameters); + EndFunction // Edit product @@ -1185,15 +1185,15 @@ EndFunction // Parameters: // Product - Number, String - Identifier of the product being edited - item // ProductDescription - Map Of KeyAndValue - See GetProductDescription - product - JSON description of the product or path -// Selection - String - Identifier of the new selection, if needed - sel +// Selection - String - Identifier of the new selection, if needed - sel // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function EditProduct(Val Product, Val ProductDescription, Val Selection = "", Val Parameters = "") Export - - Return ProductManagement(ProductDescription, Product, Selection, Parameters); - + + Return ProductManagement(ProductDescription, Product, Selection, Parameters); + EndFunction // Delete product @@ -1202,20 +1202,20 @@ EndFunction // Parameters: // Product - String, Number - Product ID - item // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function DeleteProduct(Val Product, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Product); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("item_id", Product); - + Response = OPI_Tools.Get("api.vk.com/method/market.delete", Parameters_); - + Return Response; - + EndFunction // Group products @@ -1225,37 +1225,37 @@ EndFunction // ProductsArray - Array Of String - Array of product IDs - items // ExistingGroup - String - ID of the existing group, if needed - sellgroup // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function GroupProducts(Val ProductsArray, Val ExistingGroup = "", Val Parameters = "") Export - + OPI_TypeConversion.GetLine(ExistingGroup); OPI_TypeConversion.GetCollection(ProductsArray); - - Parameters_ = GetStandardParameters(Parameters); + + Parameters_ = GetStandardParameters(Parameters); ArrayOfProducts_ = New Array; - + For Each Product In ProductsArray Do ArrayOfProducts_.Add(OPI_Tools.NumberToString(Product)); EndDo; - + Products = StrConcat(ArrayOfProducts_, ","); - + Parameters_.Insert("item_ids", Products); - + If ValueIsFilled(ExistingGroup) Then Parameters_.Insert("item_group_id", ExistingGroup); EndIf; - + Response = OPI_Tools.Get("api.vk.com/method/market.groupItems", Parameters_); - + Return Response; EndFunction // Get product description. !NOCLI -// +// // Returns: // Map Of KeyAndValue - Empty product description: // *Name - String - Product name @@ -1275,27 +1275,27 @@ EndFunction // *SKU - String - SKU // *AvailableBalance - Number - Balance. -1 - unlimited Function GetProductDescription() Export - + Product = New Map(); - Product.Insert("Name" , "New product"); // Product name - Product.Insert("Description" , "Product description"); // Product description - Product.Insert("Category" , "20173"); // See GetProductCategoryList() - Product.Insert("Price" , 1); // Price. - Product.Insert("OldPrice" , Undefined); // For reflection change price - Product.Insert("MainPhoto" , Undefined); // BD or path to main. photo - Product.Insert("URL" , Undefined); // Link to page store + Product.Insert("Name" , "New product"); // Product name + Product.Insert("Description" , "Product description"); // Product description + Product.Insert("Category" , "20173"); // See GetProductCategoryList() + Product.Insert("Price" , 1); // Price. + Product.Insert("OldPrice" , Undefined); // For reflection change price + Product.Insert("MainPhoto" , Undefined); // BD or path to main. photo + Product.Insert("URL" , Undefined); // Link to page store Product.Insert("AdditionalPhotos" , New Array); // Array paths or BD for add. photo - Product.Insert("PropertyValues" , New Array); // Values properties (variants). Maximum 2 - Product.Insert("MainInGroup" , False); // Make main in of its group - Product.Insert("Width" , Undefined); // In millimeters - Product.Insert("Height" , Undefined); // In millimeters - Product.Insert("Depth" , Undefined); // In millimeters - Product.Insert("Weight" , Undefined); // In grams - Product.Insert("SKU" , Undefined); // SKU + Product.Insert("PropertyValues" , New Array); // Values properties (variants). Maximum 2 + Product.Insert("MainInGroup" , False); // Make main in of its group + Product.Insert("Width" , Undefined); // In millimeters + Product.Insert("Height" , Undefined); // In millimeters + Product.Insert("Depth" , Undefined); // In millimeters + Product.Insert("Weight" , Undefined); // In grams + Product.Insert("SKU" , Undefined); // SKU Product.Insert("AvailableBalance" , 1); - + Return Product; - + EndFunction #EndRegion @@ -1307,19 +1307,19 @@ EndFunction // // Parameters: // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Array of selection maps Function GetSelectionList(Val Parameters = "") Export - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("count", 100); - + ArrayOfAlbums = New Array; GetAlbumListRecursively(ArrayOfAlbums, Parameters_); - + Return ArrayOfAlbums; - + EndFunction // Get selections by ID @@ -1328,29 +1328,29 @@ EndFunction // Parameters: // Selections - String, Array of String - Selection IDs - sels // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function GetSelectionsByID(Val Selections, Val Parameters = "") Export - + OPI_TypeConversion.GetCollection(Selections); - - Parameters_ = GetStandardParameters(Parameters); - Selections_ = New Array; + + Parameters_ = GetStandardParameters(Parameters); + Selections_ = New Array; SelectionsString = ""; - + For Each Selection In Selections Do - Selections_.Add(OPI_Tools.NumberToString(Selection)); - EndDo; - + Selections_.Add(OPI_Tools.NumberToString(Selection)); + EndDo; + SelectionsString = StrConcat(Selections_, ","); - + Parameters_.Insert("album_ids", SelectionsString); - + Response = OPI_Tools.Get("api.vk.com/method/market.getAlbumById", Parameters_); - + Return Response; - + EndFunction // Create product selection @@ -1362,7 +1362,7 @@ EndFunction // Main - Boolean - Main - main // Hidden - Boolean - Hidden - hidden // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function CreateProductCollection(Val Name @@ -1370,9 +1370,9 @@ Function CreateProductCollection(Val Name , Val Main = False , Val Hidden = False , Val Parameters = "") Export - + Return SelectionManagement(Name, Image, , Main, Hidden, Parameters); - + EndFunction // Edit product selection @@ -1385,7 +1385,7 @@ EndFunction // Main - Boolean - Main - main // Hidden - Boolean - Hidden - hidden // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function EditProductCollection(Val Name @@ -1394,9 +1394,9 @@ Function EditProductCollection(Val Name , Val Main = False , Val Hidden = False , Val Parameters = "") Export - + Return SelectionManagement(Name, Image, Selection, Main, Hidden, Parameters); - + EndFunction // Add product to selection @@ -1406,56 +1406,56 @@ EndFunction // ProductsArray - Array of string, number - Array of products or product - items // Selection - String - Selection ID - sel // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function AddProductToCollection(Val ProductsArray, Val Selection, Val Parameters = "") Export - + OPI_TypeConversion.GetCollection(ProductsArray); OPI_TypeConversion.GetLine(Selection); - - Parameters_ = GetStandardParameters(Parameters); + + Parameters_ = GetStandardParameters(Parameters); ArrayOfProducts_ = New Array; - + For Each Product In ProductsArray Do - ArrayOfProducts_.Add(OPI_Tools.NumberToString(Product)); - EndDo; - + ArrayOfProducts_.Add(OPI_Tools.NumberToString(Product)); + EndDo; + ProductList = StrConcat(ArrayOfProducts_, ","); - + Parameters_.Insert("item_ids" , ProductList); Parameters_.Insert("album_ids", Selection); - + Response = OPI_Tools.Get("api.vk.com/method/market.addToAlbum", Parameters_); - + Return Response; - + EndFunction // Remove product from selection // Removes a previously added product from the selection -// +// // Parameters: // Product - String - Product ID - item // Selection - String - Selection ID - sel // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function RemoveProductFromSelection(Val Product, Val Selection, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Product); OPI_TypeConversion.GetLine(Selection); Parameters_ = GetStandardParameters(Parameters); - - Parameters_.Insert("item_id" , Product); + + Parameters_.Insert("item_id" , Product); Parameters_.Insert("album_ids", Selection); - + Response = OPI_Tools.Get("api.vk.com/method/market.removeFromAlbum", Parameters_); - + Return Response; - + EndFunction // Delete selection @@ -1464,20 +1464,20 @@ EndFunction // Parameters: // Selection - String - Selection ID - sel // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function DeleteSelection(Val Selection, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Selection); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("album_id", Selection); - + Response = OPI_Tools.Get("api.vk.com/method/market.deleteAlbum", Parameters_); - + Return Response; - + EndFunction #EndRegion @@ -1486,167 +1486,167 @@ EndFunction // Get property list // Gets the list of properties of group products -// +// // Parameters: // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: -// Map Of KeyAndValue - Serialized JSON response from VK +// Map Of KeyAndValue - Serialized JSON response from VK Function GetPropertyList(Val Parameters = "") Export - - Response_ = "response"; + + Response_ = "response"; Parameters_ = GetStandardParameters(Parameters); - - Response = OPI_Tools.Get("api.vk.com/method/market.getProperties", Parameters_); + + Response = OPI_Tools.Get("api.vk.com/method/market.getProperties", Parameters_); Properties = Response[Response_]["items"]; - + Return Properties; - + EndFunction // Create product property // Creates a new property for use in products -// +// // Parameters: // Name - String - Property name - title // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: -// Map Of KeyAndValue - Serialized JSON response from VK +// Map Of KeyAndValue - Serialized JSON response from VK Function CreateProductProperty(Val Name, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Name); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("title", Name); - - Response = OPI_Tools.Get("api.vk.com/method/market.addProperty", Parameters_); - + + Response = OPI_Tools.Get("api.vk.com/method/market.addProperty", Parameters_); + Return Response; EndFunction // Edit product property // Edits the existing product property -// +// // Parameters: // Name - String - New name - title // Property - String, Number - Property ID - prop // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: -// Map Of KeyAndValue - Serialized JSON response from VK +// Map Of KeyAndValue - Serialized JSON response from VK Function EditProductProperty(Val Name, Val Property, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Name); OPI_TypeConversion.GetLine(Property); - + Parameters_ = GetStandardParameters(Parameters); - Parameters_.Insert("title" , Name); + Parameters_.Insert("title" , Name); Parameters_.Insert("property_id", Property); - Parameters_.Insert("type" , "text"); - - Response = OPI_Tools.Get("api.vk.com/method/market.editProperty", Parameters_); - + Parameters_.Insert("type" , "text"); + + Response = OPI_Tools.Get("api.vk.com/method/market.editProperty", Parameters_); + Return Response; EndFunction // Delete product property // Deletes the existing product property -// +// // Parameters: // Property - String, Number - Property ID - prop // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: -// Map Of KeyAndValue - Serialized JSON response from VK +// Map Of KeyAndValue - Serialized JSON response from VK Function DeleteProductProperty(Val Property, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Property); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("property_id", Property); - + Response = OPI_Tools.Get("api.vk.com/method/market.deleteProperty", Parameters_); - + Return Response; - + EndFunction // Add product property variant // Adds a variant for an existing property -// +// // Parameters: // Value - String - Property value - value // Property - String, Number - Property ID where the variant is added - prop // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: -// Map Of KeyAndValue - Serialized JSON response from VK +// Map Of KeyAndValue - Serialized JSON response from VK Function AddProductPropertyVariant(Val Value, Val Property, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Property); OPI_TypeConversion.GetLine(Value); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("property_id", Property); - Parameters_.Insert("title" , Value); - + Parameters_.Insert("title" , Value); + Response = OPI_Tools.Get("api.vk.com/method/market.addPropertyVariant", Parameters_); - + Return Response; - + EndFunction // Edit product property variant // Edits the value of an existing product property variant -// +// // Parameters: // Value - String - New property value - value // Property - String, Number - Property ID - prop // Option - String, Number - Variant ID - option // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: -// Map Of KeyAndValue - Serialized JSON response from VK +// Map Of KeyAndValue - Serialized JSON response from VK Function EditProductPropertyVariant(Val Value, Val Property, Val Option, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Value); OPI_TypeConversion.GetLine(Property); OPI_TypeConversion.GetLine(Option); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("property_id", Property); Parameters_.Insert("variant_id" , Option); - Parameters_.Insert("title" , Value); - + Parameters_.Insert("title" , Value); + Response = OPI_Tools.Get("api.vk.com/method/market.editPropertyVariant", Parameters_); - + Return Response; - + EndFunction // Delete product property variant // Deletes the previously created product property variant -// +// // Parameters: // Option - String, Number - Variant ID - option // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: -// Map Of KeyAndValue - Serialized JSON response from VK +// Map Of KeyAndValue - Serialized JSON response from VK Function DeleteProductPropertyVariant(Val Option, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Option); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("variant_id", Option); - + Response = OPI_Tools.Get("api.vk.com/method/market.deletePropertyVariant", Parameters_); - + Return Response; - + EndFunction #EndRegion @@ -1655,22 +1655,22 @@ EndFunction // Get order list // Returns the community's order list -// +// // Parameters: // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: -// Map Of KeyAndValue - Serialized JSON response from VK +// Map Of KeyAndValue - Serialized JSON response from VK Function GetOrderList(Val Parameters = "") Export - + Parameters = GetStandardParameters(Parameters); Parameters.Insert("count", 50); - + ArrayOfOrders = New Array; GetOrderListRecursively(ArrayOfOrders, Parameters); - + Return ArrayOfOrders; - + EndFunction #EndRegion @@ -1679,40 +1679,40 @@ EndFunction // Create keyboard // Forms a keyboard from an array of buttons -// +// // Parameters: // ButtonArray - Array of String - Array of button titles - buttons -// +// // Returns: // String - Keyboard JSON Function FormKeyboard(Val ButtonArray) Export - - OPI_TypeConversion.GetCollection(ButtonArray); - - Keyboard = New Structure; + + OPI_TypeConversion.GetCollection(ButtonArray); + + Keyboard = New Structure; KeyboardArray = New Array; - ArrayBlock = New Array; - + ArrayBlock = New Array; + For Each Action In ButtonArray Do - - Button = New Structure; - Expression = New Structure; - + + Button = New Structure; + Expression = New Structure; + Expression.Insert("type" , "text"); Expression.Insert("label", Action); - + Button.Insert("action", Expression); ArrayBlock.Add(Button); - + EndDo; - + KeyboardArray.Add(ArrayBlock); - - Keyboard.Insert("buttons" , KeyboardArray); + + Keyboard.Insert("buttons" , KeyboardArray); Keyboard.Insert("one_time", False); - + Return OPI_Tools.JSONString(Keyboard); - + EndFunction #EndRegion @@ -1722,29 +1722,29 @@ EndFunction #Region Private Function GetStandardParameters(Val Parameters = "") - + // Here is a collection of data definitions for working with the VK API // You can override them by passing them as a parameter // Matching fields will be overwritten with the parameter of the function - + Parameters_ = New Structure; - + // access_token - can be obtained in the browser via the URL from the CreateTokenRetrievalLink function() // from_group - actions will be performed on behalf of the group // owner_id - group ID with "-" at the beginning. Can be found in the settings of the VK group or in its URL if not set // set your // app_id - application ID that needs to be created in the profile on the developer page // group_id - owner_id, but without "-" - + Parameters_.Insert("access_token" , ""); - Parameters_.Insert("from_group" , "1"); - Parameters_.Insert("owner_id" , ""); - Parameters_.Insert("v" , "5.131"); - Parameters_.Insert("app_id" , ""); - Parameters_.Insert("group_id" , ""); - + Parameters_.Insert("from_group" , "1"); + Parameters_.Insert("owner_id" , ""); + Parameters_.Insert("v" , "5.131"); + Parameters_.Insert("app_id" , ""); + Parameters_.Insert("group_id" , ""); + OPI_TypeConversion.GetCollection(Parameters); - + If TypeOf(Parameters) = Type("Structure") Or TypeOf(Parameters) = Type("Map") Then For Each PassedParameter In Parameters Do Parameters_.Insert(PassedParameter.Key, OPI_Tools.NumberToString(PassedParameter.Value)); @@ -1756,32 +1756,32 @@ Function GetStandardParameters(Val Parameters = "") EndFunction Function GetImageID(Val Image, Val Parameters, Val View) - - Response_ = "response"; + + Response_ = "response"; Response = UploadPhotoToServer(Image, Parameters, View); - Result = Response[Response_]; + Result = Response[Response_]; If ValueIsFilled(Result) Then PhotoID = Result["photo_id"]; - + If Not ValueIsFilled(PhotoID) Then - Return Response; + Return Response; EndIf; - + Else Return Response; EndIf; - + PhotoID = OPI_Tools.NumberToString(PhotoID); Return PhotoID; - + EndFunction Function GetImageMap(Val Image, Val Parameters, Val View) - - Response = UploadPhotoToServer(Image, Parameters, View); + + Response = UploadPhotoToServer(Image, Parameters, View); ResponseArray = Response.Get("response"); - + If Not ValueIsFilled(ResponseArray) Or Not TypeOf(ResponseArray) = Type("Array") Then Return Response; Else @@ -1791,407 +1791,407 @@ Function GetImageMap(Val Image, Val Parameters, Val View) ResponseMap = ResponseArray[0]; EndIf; EndIf; - + Return ResponseMap; - + EndFunction Function GetSelectionArray(Val Selections, Val Parameters = "") - - Response_ = "response"; + + Response_ = "response"; Selections = GetSelectionsByID(Selections, Parameters); - Result = Selections[Response_]; - + Result = Selections[Response_]; + If ValueIsFilled(Result) Then - + SelectionArray = Result["items"]; - + If Not ValueIsFilled(SelectionArray) Then - Return Selections; + Return Selections; EndIf; - + Else Return Selections; EndIf; - + Return SelectionArray; - + EndFunction Function DetermineImageUploadMethod(Val View) - + MethodMap = New Map; - Upload = "Upload"; - Save = "Save"; - Way = "Way"; - Photo = "Photo"; - + Upload = "Upload"; + Save = "Save"; + Way = "Way"; + Photo = "Photo"; + If View = "Post" Then - + MethodMap.Insert(Upload , "photos.getWallUploadServer"); - MethodMap.Insert(Save, "photos.saveWallPhoto"); - MethodMap.Insert(Photo , "photo"); - MethodMap.Insert(Way , 1); - + MethodMap.Insert(Save , "photos.saveWallPhoto"); + MethodMap.Insert(Photo , "photo"); + MethodMap.Insert(Way , 1); + ElsIf View = "Product" Then - + MethodMap.Insert(Upload , "market.getProductPhotoUploadServer"); - MethodMap.Insert(Save, "market.saveProductPhoto"); - MethodMap.Insert(Way , 2); - + MethodMap.Insert(Save , "market.saveProductPhoto"); + MethodMap.Insert(Way , 2); + ElsIf View = "Story" Then - + MethodMap.Insert(Upload , "stories.getPhotoUploadServer"); - MethodMap.Insert(Save, "stories.save"); - MethodMap.Insert(Way , 3); - + MethodMap.Insert(Save , "stories.save"); + MethodMap.Insert(Way , 3); + ElsIf View = "Poll" Then - + MethodMap.Insert(Upload , "polls.getPhotoUploadServer"); - MethodMap.Insert(Save, "polls.savePhoto"); - MethodMap.Insert(Photo , "photo"); - MethodMap.Insert(Way , 1); - + MethodMap.Insert(Save , "polls.savePhoto"); + MethodMap.Insert(Photo , "photo"); + MethodMap.Insert(Way , 1); + Else - + MethodMap.Insert(Upload , "photos.getUploadServer"); - MethodMap.Insert(Save, "photos.save"); - MethodMap.Insert(Photo , "photos_list"); - MethodMap.Insert(Way , 1); - + MethodMap.Insert(Save , "photos.save"); + MethodMap.Insert(Photo , "photos_list"); + MethodMap.Insert(Way , 1); + EndIf; - + Return MethodMap; - + EndFunction Function GetProductParameterMapping() - + Fields = New Map(); - Fields.Insert("Name" , "name"); - Fields.Insert("Description" , "description"); - Fields.Insert("Category" , "category_id"); - Fields.Insert("Price" , "price"); - Fields.Insert("OldPrice" , "old_price"); - Fields.Insert("URL" , "url"); - Fields.Insert("MainInGroup" , "is_main_variant"); - Fields.Insert("Width" , "dimension_width"); - Fields.Insert("Height" , "dimension_height"); - Fields.Insert("Depth" , "dimension_length"); - Fields.Insert("Weight" , "weight"); - Fields.Insert("SKU" , "sku"); + Fields.Insert("Name" , "name"); + Fields.Insert("Description" , "description"); + Fields.Insert("Category" , "category_id"); + Fields.Insert("Price" , "price"); + Fields.Insert("OldPrice" , "old_price"); + Fields.Insert("URL" , "url"); + Fields.Insert("MainInGroup" , "is_main_variant"); + Fields.Insert("Width" , "dimension_width"); + Fields.Insert("Height" , "dimension_height"); + Fields.Insert("Depth" , "dimension_length"); + Fields.Insert("Weight" , "weight"); + Fields.Insert("SKU" , "sku"); Fields.Insert("AvailableBalance" , "stock_amount"); - + Return Fields; EndFunction Function ProductManagement(Val ProductDescription, Val ProductID = "", Val Selection = "", Val Parameters = "") - + OPI_TypeConversion.GetLine(ProductID); OPI_TypeConversion.GetLine(Selection); OPI_TypeConversion.GetCollection(ProductDescription); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("v", "5.199"); - + Response_ = "response"; - + FillProductRequestFields(ProductDescription, Parameters_); - - If ValueIsFilled(ProductID) Then + + If ValueIsFilled(ProductID) Then Parameters_.Insert("item_id", ProductID); - Method = "edit"; - Else + Method = "edit"; + Else Method = "add"; EndIf; - + Response = OPI_Tools.Get("api.vk.com/method/market." + Method, Parameters_); - Result = Response[Response_]; - - If Not ValueIsFilled(ProductID) And ValueIsFilled(Result) Then - + Result = Response[Response_]; + + If Not ValueIsFilled(ProductID) And ValueIsFilled(Result) Then + ProductID = Result["market_item_id"]; - + If Not ValueIsFilled(ProductID) Then - Return Response; + Return Response; EndIf; - + Else Return Response; EndIf; - + If ValueIsFilled(Selection) And ValueIsFilled(ProductID) Then AddProductToCollection(ProductID, Selection, Parameters_); EndIf; - + Return Response; EndFunction Function SelectionManagement(Val Name - , Val Image = "" + , Val Image = "" , Val SelectionID = "" - , Val Main = False - , Val Hidden = False - , Val Parameters = "") - + , Val Main = False + , Val Hidden = False + , Val Parameters = "") + OPI_TypeConversion.GetLine(Name); OPI_TypeConversion.GetLine(SelectionID); OPI_TypeConversion.GetBoolean(Main); OPI_TypeConversion.GetBoolean(Hidden); - - Parameters_ = GetStandardParameters(Parameters); - Response = AddImageParameter(Image, SelectionID, Parameters_); - + + Parameters_ = GetStandardParameters(Parameters); + Response = AddImageParameter(Image, SelectionID, Parameters_); + If ValueIsFilled(Response) Then Return Response; EndIf; - - Parameters_.Insert("title" , Name); - Parameters_.Insert("main_album" , ?(Main, 1, 0)); - Parameters_.Insert("is_hidden" , ?(Hidden, 1, 0)); - - If ValueIsFilled(SelectionID) Then + + Parameters_.Insert("title" , Name); + Parameters_.Insert("main_album" , ?(Main , 1, 0)); + Parameters_.Insert("is_hidden" , ?(Hidden, 1, 0)); + + If ValueIsFilled(SelectionID) Then Parameters_.Insert("album_id", SelectionID); - Method = "editAlbum"; - Else + Method = "editAlbum"; + Else Method = "addAlbum"; EndIf; - + Response = OPI_Tools.Get("api.vk.com/method/market." + Method, Parameters_); - + Return Response; EndFunction Function AddImageParameter(Val Image, Val SelectionID, Parameters) - + PhotoID_ = "photo_id"; - + If ValueIsFilled(Image) Then - + PhotoID = GetImageID(Image, Parameters, "Product"); - + If Not TypeOf(PhotoID) = Type("String") Then - Return PhotoID; + Return PhotoID; EndIf; - + Parameters.Insert(PhotoID_, PhotoID); - + Else - + If ValueIsFilled(SelectionID) Then - + Selections = GetSelectionArray(SelectionID, Parameters); - + If Not TypeOf(Selections) = Type("Array") Then - Return Selections; + Return Selections; EndIf; - - If Not Selections.Count() = 0 Then + + If Not Selections.Count() = 0 Then PhotoID = Selections[0]["photo"]["id"]; OPI_TypeConversion.GetLine(PhotoID); Parameters.Insert(PhotoID_, PhotoID); EndIf; - + EndIf; - + EndIf; - + Return ""; - + EndFunction Procedure FillPhotoUploadParameters(Val Method, Val Response, Parameters) - - Response_ = "response"; - Way = Method["Way"]; + + Response_ = "response"; + Way = Method["Way"]; StandardMethod = 1; - NewMethod = 2; + NewMethod = 2; If Way = StandardMethod Then - - Hash = "hash"; - Serv = "server"; - Aid = "aid"; + + Hash = "hash"; + Serv = "server"; + Aid = "aid"; Photo = Method["Photo"]; - - Parameters.Insert(Hash, Response[Hash]); + + Parameters.Insert(Hash , Response[Hash]); Parameters.Insert(Photo, Response[Photo]); - + PhotoServer = Response.Get(Serv); - + If ValueIsFilled(PhotoServer) Then PhotoServer = OPI_Tools.NumberToString(PhotoServer); - Parameters.Insert(Serv, PhotoServer); + Parameters.Insert(Serv, PhotoServer); EndIf; - + Identifier = Response.Get(Aid); - + If ValueIsFilled(Identifier) Then Identifier = OPI_Tools.NumberToString(Identifier); - Parameters.Insert(Aid , Identifier); + Parameters.Insert(Aid , Identifier); EndIf; - + ElsIf Way = NewMethod Then - + ResponseString = OPI_Tools.JSONString(Response); Parameters.Insert("upload_response", ResponseString); - + Else - + Parameters.Insert("upload_results", Response[Response_]["upload_result"]); - + EndIf; EndProcedure Procedure FillProductRequestFields(Val ProductDescription, Parameters) - - Response_ = "response"; - MainPhoto = ProductDescription["MainPhoto"]; + + Response_ = "response"; + MainPhoto = ProductDescription["MainPhoto"]; AdditionalPhoto = ProductDescription["AdditionalPhotos"]; - Properties = ProductDescription["PropertyValues"]; - + Properties = ProductDescription["PropertyValues"]; + If ValueIsFilled(MainPhoto) Then - + Response = UploadPhotoToServer(MainPhoto, Parameters, "Product"); - Result = Response[Response_]; - + Result = Response[Response_]; + If ValueIsFilled(Result) Then PhotoID = Result["photo_id"]; - + If Not ValueIsFilled(PhotoID) Then - Return; + Return; EndIf; - + Else Return; EndIf; - + PhotoID = OPI_Tools.NumberToString(PhotoID); - Parameters.Insert("main_photo_id", PhotoID); - + Parameters.Insert("main_photo_id", PhotoID); + EndIf; - - If TypeOf(Properties) = Type("Array") Then - + + If TypeOf(Properties) = Type("Array") Then + Properties_ = New Array; - + For Each Property In Properties Do - Properties_.Add(OPI_Tools.NumberToString(Property)); + Properties_.Add(OPI_Tools.NumberToString(Property)); EndDo; - - Properties = StrConcat(Properties_, ","); - + + Properties = StrConcat(Properties_, ","); + EndIf; - + If ValueIsFilled(Properties) Then - Parameters.Insert("variant_ids", OPI_Tools.NumberToString(Properties)); + Parameters.Insert("variant_ids", OPI_Tools.NumberToString(Properties)); EndIf; - + AddAdditionalProductPhotos(AdditionalPhoto, Parameters); - + For Each Field In GetProductParameterMapping() Do - + Value = ProductDescription[Field.Key]; - + If Value <> Undefined Then Parameters.Insert(Field.Value, ProductDescription[Field.Key]); EndIf; - + EndDo; EndProcedure Procedure AddAdditionalProductPhotos(Val PhotoArray, Parameters) - + If TypeOf(PhotoArray) = Type("Array") Then If PhotoArray.Count() > 0 Then - + PhotoString = ""; - + For Each Photo In PhotoArray Do - + PhotoID = GetImageID(Photo, Parameters, "Product"); - + If Not TypeOf(PhotoID) = Type("String") Then - Return; + Return; EndIf; - PhotoString = PhotoString + PhotoID + ","; - + PhotoString = PhotoString + PhotoID + ","; + EndDo; - + PhotoString = Left(PhotoString, StrLen(PhotoString) - 1); Parameters.Insert("photo_ids", PhotoString); EndIf; EndIf; - + EndProcedure Procedure GetProductListRecursively(ProductsArray, Parameters, Shift = 0) - - Response_ = "response"; + + Response_ = "response"; MaxInRequest = 200; - Response = OPI_Tools.Get("api.vk.com/method/market.get", Parameters); - Products = Response[Response_]["items"]; - + Response = OPI_Tools.Get("api.vk.com/method/market.get", Parameters); + Products = Response[Response_]["items"]; + If Products.Count() = 0 Then Return; - EndIf; - + EndIf; + For Each Product In Products Do ProductsArray.Add(Product); EndDo; - + Shift = Shift + MaxInRequest; Parameters.Insert("offset", Shift); GetProductListRecursively(ProductsArray, Parameters, Shift); - + EndProcedure Procedure GetAlbumListRecursively(ArrayOfAlbums, Parameters, Shift = 0) - - Response_ = "response"; + + Response_ = "response"; MaxInRequest = 100; - Response = OPI_Tools.Get("api.vk.com/method/market.getAlbums", Parameters); - Albums = Response[Response_]["items"]; - + Response = OPI_Tools.Get("api.vk.com/method/market.getAlbums", Parameters); + Albums = Response[Response_]["items"]; + If Albums.Count() = 0 Then Return; - EndIf; - + EndIf; + For Each Album In Albums Do ArrayOfAlbums.Add(Album); EndDo; - + Shift = Shift + MaxInRequest; Parameters.Insert("offset", Shift); GetAlbumListRecursively(ArrayOfAlbums, Parameters, Shift); - + EndProcedure Procedure GetOrderListRecursively(ArrayOfOrders, Parameters, Shift = 0) - - Response_ = "response"; + + Response_ = "response"; MaxInRequest = 50; - Response = OPI_Tools.Get("api.vk.com/method/market.getGroupOrders", Parameters); - Orders = Response[Response_]["items"]; - + Response = OPI_Tools.Get("api.vk.com/method/market.getGroupOrders", Parameters); + Orders = Response[Response_]["items"]; + If Orders.Count() = 0 Then Return; - EndIf; - + EndIf; + For Each Order In Orders Do ArrayOfOrders.Add(Order); EndDo; - + Shift = Shift + MaxInRequest; Parameters.Insert("offset", Shift); GetOrderListRecursively(ArrayOfOrders, Parameters, Shift); - + EndProcedure #EndRegion diff --git a/src/en/OInt/core/Modules/OPI_Viber.os b/src/en/OInt/core/Modules/OPI_Viber.os index dfc8cc2888..412f6a1c76 100644 --- a/src/en/OInt/core/Modules/OPI_Viber.os +++ b/src/en/OInt/core/Modules/OPI_Viber.os @@ -23,7 +23,7 @@ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. - + // https://github.com/Bayselonarrend/OpenIntegrations // BSLLS:LatinAndCyrillicSymbolInWord-off @@ -46,55 +46,55 @@ // which will return 200 and a genuine SSL certificate. If there is a certificate and the database is published // on the server - you can use an HTTP service. Information about new messages will also be sent there // Viber periodically knocks on the Webhook address, so if it is inactive, everything will stop working -// +// // Parameters: // Token - String - Viber Token - token // URL - String - URL for setting up Webhook - url -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Viber Function SetWebhook(Val Token, Val URL) Export - + Parameters = New Structure; - OPI_Tools.AddField("url" , URL , "String", Parameters); + OPI_Tools.AddField("url" , URL , "String", Parameters); OPI_Tools.AddField("auth_token" , Token, "String", Parameters); - + Return OPI_Tools.Post("https://chatapi.viber.com/pa/set_webhook", Parameters); - + EndFunction // Get channel information // Here you can get the channel's user IDs. Bot IDs need to be obtained from the Webhook arrivals // The user ID from channel information is not suitable for sending messages through the bot - they are different -// +// // Parameters: // Token - String - Token - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Viber Function GetChannelInformation(Val Token) Export - - URL = "https://chatapi.viber.com/pa/get_account_info"; + + URL = "https://chatapi.viber.com/pa/get_account_info"; Return OPI_Tools.Get(URL, , TokenInHeaders(Token)); - + EndFunction // Get user data // Gets user information by ID -// +// // Parameters: // Token - String - Token - token // UserID - String, Number - Viber User ID - user -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Viber Function GetUserData(Val Token, Val UserID) Export - + URL = "https://chatapi.viber.com/pa/get_user_details"; - + Parameters = New Structure; OPI_Tools.AddField("id", UserID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters, TokenInHeaders(Token)); Return Response; @@ -103,22 +103,22 @@ EndFunction // Get online users // Gets the status of a user or multiple users by ID -// +// // Parameters: // Token - String - Viber Token - token // UserIDs - String,Number,Array of String,Number - Viber User(s) ID - users -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Viber Function GetOnlineUsers(Val Token, Val UserIDs) Export - + URL = "https://chatapi.viber.com/pa/get_online"; - + Parameters = New Structure; OPI_Tools.AddField("ids", UserIDs, "Collection", Parameters); - + Response = OPI_Tools.Post(URL, Parameters, TokenInHeaders(Token)); - + Return Response; EndFunction @@ -129,14 +129,14 @@ EndFunction // Send text message // Sends a text message to a chat or channel -// +// // Parameters: // Token - String - Token - token // Text - String - Message text - text // UserID - String, Number - User ID. For channel > administrator, for bot > recipient - user // SendingToChannel - Boolean - Sending to channel or bot chat - ischannel // Keyboard - Structure Of String - See CreateKeyboardFromArrayButton - keyboard -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Viber Function SendTextMessage(Val Token @@ -144,40 +144,40 @@ Function SendTextMessage(Val Token , Val UserID , Val SendingToChannel , Val Keyboard = "") Export - - Return SendMessage(Token, "text", UserID, SendingToChannel, , Text, Keyboard); - + + Return SendMessage(Token, "text", UserID, SendingToChannel, , Text, Keyboard); + EndFunction // Send image // Sends an image to a chat or channel -// +// // Parameters: // Token - String - Token - token // URL - String - Image URL - picture // UserID - String, Number - User ID. For channel > administrator, for bot > recipient - user // SendingToChannel - boolean - Sending to channel or bot chat - ischannel // Description - String - Image annotation - description -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Viber Function SendImage(Val Token, Val URL, Val UserID, Val SendingToChannel, Val Description = "") Export - + Return SendMessage(Token, "picture", UserID, SendingToChannel, URL, Description); - + EndFunction // SendFile // Sends a file (document) to a chat or channel -// +// // Parameters: // Token - String - Token - token -// URL - String - File URL - file -// UserID - String, Number - User ID. For channel > administrator, for bot > recipient - user +// URL - String - File URL - file +// UserID - String, Number - User ID. For channel > administrator, for bot > recipient - user // SendingToChannel - Boolean - Sending to channel or bot chat - ischannel // Extension - String - File extension - ext // Size - Number - File size. If not filled in > determined automatically by downloading the file - size -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Viber Function SendFile(Val Token @@ -186,36 +186,36 @@ Function SendFile(Val Token , Val SendingToChannel , Val Extension , Val Size = "") Export - + If Not ValueIsFilled(Size) Then - + Response = OPI_Tools.Get(URL); - Size = Response.Size(); - + Size = Response.Size(); + EndIf; - - String_ = "String"; + + String_ = "String"; Extension = StrReplace(Extension, ".", ""); - + Parameters = New Structure; - OPI_Tools.AddField("URL" , URL , String_, Parameters); - OPI_Tools.AddField("Size" , Size , String_, Parameters); + OPI_Tools.AddField("URL" , URL , String_, Parameters); + OPI_Tools.AddField("Size" , Size , String_, Parameters); OPI_Tools.AddField("Extension", Extension, String_, Parameters); - + Return SendMessage(Token, "file", UserID, SendingToChannel, Parameters); - + EndFunction // Send contact // Sends a contact with a phone number to a chat or channel -// +// // Parameters: // Token - String - Token - token // ContactName - String - Contact name - name // PhoneNumber - String - Phone number - phone -// UserID - String, Number - User ID. For channel > administrator, for bot > recipient - user +// UserID - String, Number - User ID. For channel > administrator, for bot > recipient - user // SendingToChannel - Boolean - Sending to channel or bot chat - ischannel -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Viber Function SendContact(Val Token @@ -223,91 +223,91 @@ Function SendContact(Val Token , Val PhoneNumber , Val UserID , Val SendingToChannel) Export - + Parameters = New Structure; - OPI_Tools.AddField("name" , ContactName , "String", Parameters); - OPI_Tools.AddField("phone_number", PhoneNumber, "String", Parameters); - - Return SendMessage(Token, "contact", UserID, SendingToChannel, Parameters); - + OPI_Tools.AddField("name" , ContactName , "String", Parameters); + OPI_Tools.AddField("phone_number", PhoneNumber , "String", Parameters); + + Return SendMessage(Token, "contact", UserID, SendingToChannel, Parameters); + EndFunction // Send location // Sends geographic coordinates to a chat or channel -// +// // Parameters: // Token - String - Token - token // Latitude - String, Number - Geographic latitude - lat // Longitude - String, Number - Geographic longitude - long -// UserID - String, Number - User ID. For channel > administrator, for bot > recipient - user +// UserID - String, Number - User ID. For channel > administrator, for bot > recipient - user // SendingToChannel - Boolean - Sending to channel or bot chat - ischannel -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Viber Function SendLocation(Val Token, Val Latitude, Val Longitude, Val UserID, Val SendingToChannel) Export - + Parameters = New Structure; OPI_Tools.AddField("lat", Latitude , "String", Parameters); OPI_Tools.AddField("lon", Longitude, "String", Parameters); - + Return SendMessage(Token, "location", UserID, SendingToChannel, Parameters); - + EndFunction // Send link // Sends a URL with a preview to a chat or channel -// +// // Parameters: // Token - String - Token - token // URL - String - SentLink - url -// UserID - String, Number - User ID. For channel > administrator, for bot > recipient - user +// UserID - String, Number - User ID. For channel > administrator, for bot > recipient - user // SendingToChannel - Boolean - Sending to channel or bot chat - ischannel -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Viber Function SendLink(Val Token, Val URL, Val UserID, Val SendingToChannel) Export - + Return SendMessage(Token, "url", UserID, SendingToChannel, URL); - + EndFunction // Create a keyboard from an array of buttons // Returns a keyboard structure for messages -// +// // Parameters: // ButtonArray - Array of String - Array of buttons - buttons // ButtonColor - String - HEX color of buttons with # at the beginning - color -// +// // Returns: // Structure - Create a keyboard from an array of buttons: -// * Buttons - Array of Structure - Array of formed buttons -// * Type - String - KeyboardType +// * Buttons - Array of Structure - Array of formed buttons +// * Type - String - KeyboardType Function CreateKeyboardFromArrayButton(Val ButtonArray, Val ButtonColor = "#2db9b9") Export - + OPI_TypeConversion.GetLine(ButtonColor); OPI_TypeConversion.GetCollection(ButtonArray); - + ArrayOfButtonStructures = New Array; - KeyboardStructure = New Structure; - + KeyboardStructure = New Structure; + For Each ButtonText In ButtonArray Do - + ButtonStructure = New Structure; ButtonStructure.Insert("ActionType", "reply"); ButtonStructure.Insert("ActionBody", ButtonText); - ButtonStructure.Insert("Text" , ButtonText); - ButtonStructure.Insert("BgColor" , ButtonColor); - ButtonStructure.Insert("Coloumns" , 3); - + ButtonStructure.Insert("Text" , ButtonText); + ButtonStructure.Insert("BgColor" , ButtonColor); + ButtonStructure.Insert("Coloumns" , 3); + ArrayOfButtonStructures.Add(ButtonStructure); - + EndDo; - + KeyboardStructure.Insert("Buttons", ArrayOfButtonStructures); - KeyboardStructure.Insert("Type" , "keyboard"); - + KeyboardStructure.Insert("Type" , "keyboard"); + Return KeyboardStructure; - + EndFunction #EndRegion @@ -317,7 +317,7 @@ EndFunction #Region Private // Send message. -// +// // Parameters: // Token - String - Token // Type - String - TypeOfSentMessage @@ -328,8 +328,8 @@ EndFunction // * Size - Number, String - File size in case of sending // * Extension - String - File extension in case of sending // Text - String - Message text -// Keyboard - Structure Of String - Keyboard, if needed, see CreateKeyboardFromArrayButton -// +// Keyboard - Structure Of String - Keyboard, if needed, see CreateKeyboardFromArrayButton +// // Returns: // Arbitrary, HTTPResponse - Send message Function SendMessage(Val Token @@ -339,81 +339,81 @@ Function SendMessage(Val Token , Val Value = "" , Val Text = "" , Val Keyboard = "") - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Type); OPI_TypeConversion.GetLine(UserID); OPI_TypeConversion.GetLine(Text); OPI_TypeConversion.GetBoolean(IsChannel); OPI_TypeConversion.GetCollection(Keyboard); - + ParametersStructure = ReturnStandardParameters(); - ParametersStructure.Insert("type", Type); - + ParametersStructure.Insert("type", Type); + If (Type = "text" Or Type = "picture") And ValueIsFilled(Text) Then ParametersStructure.Insert("text", Text); EndIf; - + If TypeOf(Keyboard) = Type("Structure") Then ParametersStructure.Insert("keyboard", Keyboard); EndIf; - + If ValueIsFilled(Value) Then - - If Type = "file" Then - ParametersStructure.Insert("media" , Value["URL"]); - ParametersStructure.Insert("size" , Value["Size"]); + + If Type = "file" Then + ParametersStructure.Insert("media" , Value["URL"]); + ParametersStructure.Insert("size" , Value["Size"]); ParametersStructure.Insert("file_name", "File." + Value["Extension"]); ElsIf Type = "contact" Then - ParametersStructure.Insert("contact" , Value); + ParametersStructure.Insert("contact" , Value); ElsIf Type = "location" Then ParametersStructure.Insert("location" , Value); Else - ParametersStructure.Insert("media" , Value); + ParametersStructure.Insert("media" , Value); EndIf; - + EndIf; - + If IsChannel Then - ParametersStructure.Insert("from", UserID); + ParametersStructure.Insert("from" , UserID); URL = "https://chatapi.viber.com/pa/post"; - Else + Else ParametersStructure.Insert("receiver", UserID); URL = "https://chatapi.viber.com/pa/send_message"; EndIf; - + Response = OPI_Tools.Post(URL, ParametersStructure, TokenInHeaders(Token)); - + Try Return OPI_Tools.JsonToStructure(Response.ПолучитьТелоКакДвоичныеДанные()); Except Return Response; EndTry; - + EndFunction -Function ReturnStandardParameters() - +Function ReturnStandardParameters() + SenderStructure = New Structure; - SenderStructure.Insert("name" , "Bot"); + SenderStructure.Insert("name" , "Bot"); SenderStructure.Insert("avatar", ""); - + ParametersStructure = New Structure; - ParametersStructure.Insert("sender", SenderStructure); + ParametersStructure.Insert("sender" , SenderStructure); ParametersStructure.Insert("min_api_version", 1); - + Return ParametersStructure; - + EndFunction Function TokenInHeaders(Val Token) - + OPI_TypeConversion.GetLine(Token); - + HeadersStructure = New Map; HeadersStructure.Insert("X-Viber-Auth-Token", Token); Return HeadersStructure; - + EndFunction #EndRegion diff --git a/src/en/OInt/core/Modules/OPI_YandexDisk.os b/src/en/OInt/core/Modules/OPI_YandexDisk.os index e580be788b..e431b66a6c 100644 --- a/src/en/OInt/core/Modules/OPI_YandexDisk.os +++ b/src/en/OInt/core/Modules/OPI_YandexDisk.os @@ -37,7 +37,7 @@ //@skip-check wrong-string-literal-content // Uncomment if OneScript is executed -#Use "../../tools" +#Use "../../tools" #Region Public @@ -45,217 +45,217 @@ // Get disk information // Gets information about the current disk -// +// // Parameters: // Token - String - Token - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function GetDiskInformation(Val Token) Export - + OPI_TypeConversion.GetLine(Token); - - Headers = AuthorizationHeader(Token); + + Headers = AuthorizationHeader(Token); Response = OPI_Tools.Get("https://cloud-api.yandex.net/v1/disk", , Headers); - + Return Response; - + EndFunction // Create folder // Creates a directory on the disk -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the created folder - path -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function CreateFolder(Val Token, Val Path) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Path); - + Headers = AuthorizationHeader(Token); - URL = "https://cloud-api.yandex.net/v1/disk/resources"; - Href = "href"; - + URL = "https://cloud-api.yandex.net/v1/disk/resources"; + Href = "href"; + Parameters = New Structure; Parameters.Insert("path", Path); - - Parameters = OPI_Tools.RequestParametersToString(Parameters); - Response = OPI_Tools.Put(URL + Parameters, , Headers, False); - - ResponseURL = Response[Href]; - + + Parameters = OPI_Tools.RequestParametersToString(Parameters); + Response = OPI_Tools.Put(URL + Parameters, , Headers, False); + + ResponseURL = Response[Href]; + If Not ValueIsFilled(ResponseURL) Then - Return Response; + Return Response; EndIf; - + Response = OPI_Tools.Get(ResponseURL, , Headers); - + Return Response; EndFunction // Get object // Gets information about a disk object at the specified path -// +// // Parameters: // Token - String - Token - token // Path - String - Path to folder or file - path -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function GetObject(Val Token, Val Path) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Path); - - Headers = AuthorizationHeader(Token); + + Headers = AuthorizationHeader(Token); Parameters = New Structure; Parameters.Insert("path", Path); - + Response = OPI_Tools.Get("https://cloud-api.yandex.net/v1/disk/resources", Parameters, Headers); - + Return Response; EndFunction // Delete object // Deletes an object at the specified path -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the folder or file to be deleted - path // ToCart - Boolean - To cart - can -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function DeleteObject(Val Token, Val Path, Val ToCart = True) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Path); OPI_TypeConversion.GetBoolean(ToCart); - + Headers = AuthorizationHeader(Token); - + Parameters = New Structure; - Parameters.Insert("path" , Path); + Parameters.Insert("path" , Path); Parameters.Insert("permanently", Not ToCart); - + Response = OPI_Tools.Delete("https://cloud-api.yandex.net/v1/disk/resources", Parameters, Headers); - + Return Response; EndFunction // Create object copy // Creates a copy of the object at the specified path and path to the original -// +// // Parameters: // Token - String - Token - token // Original - String - Path to the original file or directory - from // Path - String - Destination path for the copy - to // Overwrite - Boolean - Overwrite if a file with the same name already exists - rewrite -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function CreateObjectCopy(Val Token, Val Original, Val Path, Val Overwrite = False) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Original); OPI_TypeConversion.GetLine(Path); OPI_TypeConversion.GetBoolean(Overwrite); - + Headers = AuthorizationHeader(Token); - URL = "https://cloud-api.yandex.net/v1/disk/resources/copy"; - Href = "href"; - + URL = "https://cloud-api.yandex.net/v1/disk/resources/copy"; + Href = "href"; + Parameters = New Structure; - Parameters.Insert("from" , Original); - Parameters.Insert("path" , Path); + Parameters.Insert("from" , Original); + Parameters.Insert("path" , Path); Parameters.Insert("overwrite" , Overwrite); - - Parameters = OPI_Tools.RequestParametersToString(Parameters); - Response = OPI_Tools.Post(URL + Parameters, , Headers, False); - - ResponseURL = Response[Href]; - + + Parameters = OPI_Tools.RequestParametersToString(Parameters); + Response = OPI_Tools.Post(URL + Parameters, , Headers, False); + + ResponseURL = Response[Href]; + If Not ValueIsFilled(ResponseURL) Then - Return Response; + Return Response; EndIf; - + Response = OPI_Tools.Get(ResponseURL, , Headers); - + Return Response; - + EndFunction // Get download link // Gets a download link for the file -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the file for downloading - path -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function GetDownloadLink(Val Token, Val Path) Export OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Path); - + Headers = AuthorizationHeader(Token); - + Parameters = New Structure; Parameters.Insert("path", Path); - + Response = OPI_Tools.Get("https://cloud-api.yandex.net/v1/disk/resources/download", Parameters, Headers); - + Return Response; - + EndFunction // Download file // Downloads a file at the specified path -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the file for downloading - path -// SavePath - String - File save path - out -// +// SavePath - String - File save path - out +// // Returns: // BinaryData,String - Binary data or file path when SavePath parameter is specified Function DownloadFile(Val Token, Val Path, Val SavePath = "") Export - + OPI_TypeConversion.GetLine(SavePath); Response = GetDownloadLink(Token, Path); - URL = Response["href"]; - + URL = Response["href"]; + If Not ValueIsFilled(URL) Then Return Response; EndIf; - + Response = OPI_Tools.Get(URL, , , SavePath); - + Return Response; - + EndFunction // Get list of files // Gets a list of files with or without filtering by type -// List of available types: audio, backup, book, compressed, data, development, -// diskimage, document, encoded, executable, flash, font, +// List of available types: audio, backup, book, compressed, data, development, +// diskimage, document, encoded, executable, flash, font, // mage, settings, spreadsheet, text, unknown, video, web -// +// // Parameters: // Token - String - Token - token // Count - Number, String - Number of returned objects - amount // OffsetFromStart - Number - Offset for getting objects not from the beginning of the list - offset // FilterByType - String - Filter by file type - type // SortByDate - Boolean - True > sort by date, False > alphabetically - datesort -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function GetFilesList(Val Token @@ -263,50 +263,50 @@ Function GetFilesList(Val Token , Val OffsetFromStart = 0 , Val FilterByType = "" , Val SortByDate = False) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Count); OPI_TypeConversion.GetLine(OffsetFromStart); OPI_TypeConversion.GetLine(FilterByType); OPI_TypeConversion.GetBoolean(SortByDate); - + Headers = AuthorizationHeader(Token); - + Parameters = New Structure; - + If ValueIsFilled(Count) Then Parameters.Insert("limit", OPI_Tools.NumberToString(Count)); EndIf; - + If ValueIsFilled(OffsetFromStart) Then Parameters.Insert("offset", OPI_Tools.NumberToString(OffsetFromStart)); EndIf; - + If ValueIsFilled(FilterByType) Then Parameters.Insert("media_type", FilterByType); EndIf; - + If SortByDate Then Destination = "last-uploaded"; Else Destination = "files"; EndIf; - + Response = OPI_Tools.Get("https://cloud-api.yandex.net/v1/disk/resources/" + Destination, Parameters, Headers); - + Return Response; - + EndFunction // Move object // Moves the object to the specified path and path to the original -// +// // Parameters: // Token - String - Token - token // Original - String - Path to the original file or folder - from // Path - String - Destination path for moving - to // Overwrite - Boolean - Overwrite if a file with the same name already exists - rewrite -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function MoveObject(Val Token, Val Original, Val Path, Val Overwrite = False) Export @@ -315,97 +315,97 @@ Function MoveObject(Val Token, Val Original, Val Path, Val Overwrite = False) Ex OPI_TypeConversion.GetLine(Original); OPI_TypeConversion.GetLine(Path); OPI_TypeConversion.GetBoolean(Overwrite); - + Headers = AuthorizationHeader(Token); - URL = "https://cloud-api.yandex.net/v1/disk/resources/move"; - Href = "href"; - + URL = "https://cloud-api.yandex.net/v1/disk/resources/move"; + Href = "href"; + Parameters = New Structure; - Parameters.Insert("from" , Original); - Parameters.Insert("path" , Path); + Parameters.Insert("from" , Original); + Parameters.Insert("path" , Path); Parameters.Insert("overwrite" , Overwrite); - - Parameters = OPI_Tools.RequestParametersToString(Parameters); - Response = OPI_Tools.Post(URL + Parameters, , Headers, False); - ResponseURL = Response[Href]; - + + Parameters = OPI_Tools.RequestParametersToString(Parameters); + Response = OPI_Tools.Post(URL + Parameters, , Headers, False); + ResponseURL = Response[Href]; + If Not ValueIsFilled(ResponseURL) Then - Return Response; + Return Response; EndIf; - + Response = OPI_Tools.Get(ResponseURL, , Headers); - + Return Response; - + EndFunction // Upload file // Uploads a file to disk at the specified path -// +// // Parameters: // Token - String - Token - token // Path - String - Path for saving the file to disk - path // File - String, BinaryData - File for upload - file // Overwrite - Boolean - Overwrite if a file with the same name already exists - rewrite -// +// // Returns: -// Map Of KeyAndValue - serialized JSON response from Yandex +// Map Of KeyAndValue - serialized JSON response from Yandex Function UploadFile(Val Token, Val Path, Val File, Val Overwrite = False) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Path); OPI_TypeConversion.GetBoolean(Overwrite); OPI_TypeConversion.GetBinaryData(File); - + Headers = AuthorizationHeader(Token); - Href = "href"; - File = New Structure("file", File); - + Href = "href"; + File = New Structure("file", File); + Parameters = New Structure; - Parameters.Insert("path" , Path); + Parameters.Insert("path" , Path); Parameters.Insert("overwrite" , Overwrite); - + Response = OPI_Tools.Get("https://cloud-api.yandex.net/v1/disk/resources/upload", Parameters, Headers); - URL = Response[Href]; - + URL = Response[Href]; + If Not ValueIsFilled(URL) Then - Return Response; + Return Response; EndIf; - + Response = OPI_Tools.PutMultipart(URL, New Structure(), File, "multipart", Headers); - + Return Response; - + EndFunction // Upload file by URL // Downloads a file to disk from the specified URL -// +// // Parameters: // Token - String - Token - token // Path - String - Path to place the downloaded file - path // Address - String - File URL - url -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function UploadFileByURL(Val Token, Val Path, Val Address) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Path); OPI_TypeConversion.GetLine(Address); - + Headers = AuthorizationHeader(Token); - URL = "https://cloud-api.yandex.net/v1/disk/resources/upload"; - + URL = "https://cloud-api.yandex.net/v1/disk/resources/upload"; + Parameters = New Structure; Parameters.Insert("url" , EncodeString(Address, StringEncodingMethod.URLencoding)); Parameters.Insert("path", Path); - - Parameters = OPI_Tools.RequestParametersToString(Parameters); - Response = OPI_Tools.Post(URL + Parameters, , Headers, False); - + + Parameters = OPI_Tools.RequestParametersToString(Parameters); + Response = OPI_Tools.Post(URL + Parameters, , Headers, False); + Return Response; - + EndFunction #EndRegion @@ -414,186 +414,186 @@ EndFunction // Publish object // Publishes the disk object for public access -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the object to be published - path -// +// // Returns: -// Map Of KeyAndValue - serialized JSON response from Yandex +// Map Of KeyAndValue - serialized JSON response from Yandex Function PublishObject(Val Token, Val Path) Export - - Return TogglePublicAccess(Token, Path, True); - + + Return TogglePublicAccess(Token, Path, True); + EndFunction // Unpublish object // Unpublishes a previously published object -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the previously published object - path -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function CancelObjectPublication(Val Token, Val Path) Export - + Return TogglePublicAccess(Token, Path, False); - + EndFunction // Get list of published objects. // Gets a list of published objects -// +// // Parameters: -// Token - String - Token - token +// Token - String - Token - token // Count - Number - Number of returned objects - amount // OffsetFromStart - Number - Offset for getting objects not from the beginning of the list - offset -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function GetPublishedObjectsList(Val Token, Val Count = 0, Val OffsetFromStart = 0) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Count); OPI_TypeConversion.GetLine(OffsetFromStart); - + Headers = AuthorizationHeader(Token); - + Parameters = New Structure; - + If ValueIsFilled(Count) Then Parameters.Insert("limit", Count); EndIf; - + If ValueIsFilled(OffsetFromStart) Then Parameters.Insert("offset", OffsetFromStart); EndIf; - + Response = OPI_Tools.Get("https://cloud-api.yandex.net/v1/disk/resources/public", Parameters, Headers); - + Return Response; - + EndFunction // Get public object // Gets information about the published object by its URL -// +// // Parameters: // Token - String - Token - token -// URL - String - Object address - url +// URL - String - Object address - url // Count - Number - Number of returned nested objects (for catalog) - amount // OffsetFromStart - Number - Offset for getting nested objects not from the beginning of the list - offset -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function GetPublicObject(Val Token, Val URL, Val Count = 0, Val OffsetFromStart = 0) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(URL); OPI_TypeConversion.GetLine(Count); OPI_TypeConversion.GetLine(OffsetFromStart); - + Headers = AuthorizationHeader(Token); - + Parameters = New Structure; - + If ValueIsFilled(Count) Then Parameters.Insert("limit", OPI_Tools.NumberToString(Count)); EndIf; - + If ValueIsFilled(OffsetFromStart) Then Parameters.Insert("offset", OPI_Tools.NumberToString(OffsetFromStart)); EndIf; - + Parameters.Insert("public_key", URL); - + Response = OPI_Tools.Get("https://cloud-api.yandex.net/v1/disk/public/resources", Parameters, Headers); - + Return Response; - + EndFunction // Get download link for public object // Gets a direct link to download the public object -// +// // Parameters: // Token - String - Token - token // URL - String - Object address - url // Path - String - Path inside the object - path -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function GetDownloadLinkForPublicObject(Val Token, Val URL, Val Path = "") Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(URL); OPI_TypeConversion.GetLine(Path); - + Headers = AuthorizationHeader(Token); - + Parameters = New Structure; - + If ValueIsFilled(Path) Then Parameters.Insert("path", Path); EndIf; - + Parameters.Insert("public_key", URL); - + Response = OPI_Tools.Get("https://cloud-api.yandex.net/v1/disk/public/resources/download", Parameters, Headers); - - Return Response; - + + Return Response; + EndFunction - + // Save public object to disk // Saves the public object to your disk -// +// // Parameters: // Token - String - Token - token // URL - String - Object address - url // From - String - Path within public catalog (folders only) - from // Target - String - File save path - to -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function SavePublicObjectToDisk(Val Token, Val URL, From = "", Target = "") Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(URL); OPI_TypeConversion.GetLine(From); OPI_TypeConversion.GetLine(Target); - + Headers = AuthorizationHeader(Token); Address = "https://cloud-api.yandex.net/v1/disk/public/resources/save-to-disk"; - Href = "href"; - + Href = "href"; + Parameters = New Structure; Parameters.Insert("public_key", EncodeString(URL, StringEncodingMethod.URLencoding)); - + If ValueIsFilled(From) Then Parameters.Insert("path", From); EndIf; - + If ValueIsFilled(Target) Then Parameters.Insert("save_path", Target); EndIf; - - Parameters = OPI_Tools.RequestParametersToString(Parameters); - Response = OPI_Tools.Post(Address + Parameters, , Headers, False); - - ResponseURL = Response[Href]; - + + Parameters = OPI_Tools.RequestParametersToString(Parameters); + Response = OPI_Tools.Post(Address + Parameters, , Headers, False); + + ResponseURL = Response[Href]; + If Not ValueIsFilled(ResponseURL) Then - Return Response; + Return Response; EndIf; - + Response = OPI_Tools.Get(ResponseURL, , Headers); - + Return Response; - + EndFunction - + #EndRegion #EndRegion @@ -601,42 +601,42 @@ EndFunction #Region Private Function AuthorizationHeader(Val Token) - + Headers = New Map; Headers.Insert("Authorization", "OAuth " + Token); - + Return Headers; - + EndFunction -Function TogglePublicAccess(Val Token, Val Path, Val PublicAccess) - +Function TogglePublicAccess(Val Token, Val Path, Val PublicAccess) + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Path); OPI_TypeConversion.GetBoolean(PublicAccess); - - Headers = AuthorizationHeader(Token); + + Headers = AuthorizationHeader(Token); Destination = ?(PublicAccess, "publish", "unpublish"); - Href = "href"; - + Href = "href"; + URL = "https://cloud-api.yandex.net/v1/disk/resources/" + Destination; - + Parameters = New Structure; Parameters.Insert("path", Path); - - Parameters = OPI_Tools.RequestParametersToString(Parameters); - Response = OPI_Tools.Put(URL + Parameters, , Headers, False); - + + Parameters = OPI_Tools.RequestParametersToString(Parameters); + Response = OPI_Tools.Put(URL + Parameters, , Headers, False); + ResponseURL = Response[Href]; - + If Not ValueIsFilled(ResponseURL) Then - Return Response; - EndIf; - + Return Response; + EndIf; + Response = OPI_Tools.Get(ResponseURL, , Headers); - + Return Response; - + EndFunction #EndRegion diff --git a/src/en/OInt/core/Modules/OPI_YandexID.os b/src/en/OInt/core/Modules/OPI_YandexID.os index 97c617a176..a8d908e0ff 100644 --- a/src/en/OInt/core/Modules/OPI_YandexID.os +++ b/src/en/OInt/core/Modules/OPI_YandexID.os @@ -41,77 +41,77 @@ // Get confirmation code // Gets the confirmation code and the address of the page where it needs to be entered -// +// // Parameters: // ClientId - String - Client id - id -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function GetConfirmationCode(Val ClientId) Export OPI_TypeConversion.GetLine(ClientId); - + Parameters = New Structure("client_id", ClientId); - Response = OPI_Tools.Post("https://oauth.yandex.ru/device/code", Parameters, , False); - + Response = OPI_Tools.Post("https://oauth.yandex.ru/device/code", Parameters, , False); + Return Response; - + EndFunction // Convert code to token // Converts the code to a token after entering the code when executing GetConfirmationCode -// +// // Parameters: // ClientId - String - Client id - id // ClientSecret - String - Client secret - secret // DeviceCode - String - device_code from GetConfirmationCode() - device -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function ConvertCodeToToken(Val ClientId, Val ClientSecret, Val DeviceCode) Export - + OPI_TypeConversion.GetLine(ClientId); OPI_TypeConversion.GetLine(ClientSecret); OPI_TypeConversion.GetLine(DeviceCode); - + Parameters = New Structure; - Parameters.Insert("grant_type" , "device_code"); - Parameters.Insert("code" , DeviceCode); - Parameters.Insert("client_id" , ClientId); + Parameters.Insert("grant_type" , "device_code"); + Parameters.Insert("code" , DeviceCode); + Parameters.Insert("client_id" , ClientId); Parameters.Insert("client_secret" , ClientSecret); - + Response = OPI_Tools.Post("https://oauth.yandex.ru/token", Parameters, , False); - + Return Response; - + EndFunction // Refresh token // Updates token by Refresh token -// +// // Parameters: // ClientId - String - Client id - id // ClientSecret - String - Client secret - secret // RefreshToken - String - Refresh token - refresh -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function RefreshToken(Val ClientId, Val ClientSecret, Val RefreshToken) Export - + OPI_TypeConversion.GetLine(ClientId); OPI_TypeConversion.GetLine(ClientSecret); OPI_TypeConversion.GetLine(RefreshToken); - + Parameters = New Structure; - Parameters.Insert("grant_type" , "refresh_token"); + Parameters.Insert("grant_type" , "refresh_token"); Parameters.Insert("refresh_token" , RefreshToken); - Parameters.Insert("client_id" , ClientId); + Parameters.Insert("client_id" , ClientId); Parameters.Insert("client_secret" , ClientSecret); - + Response = OPI_Tools.Post("https://oauth.yandex.ru/token", Parameters, , False); - + Return Response; - + EndFunction #EndRegion diff --git a/src/en/OInt/tests/Modules/internal/OPI_Tests.os b/src/en/OInt/tests/Modules/internal/OPI_Tests.os index 330d4c1b5a..a9fd8ed9c2 100644 --- a/src/en/OInt/tests/Modules/internal/OPI_Tests.os +++ b/src/en/OInt/tests/Modules/internal/OPI_Tests.os @@ -67,56 +67,56 @@ EndFunction #Region Telegram Procedure TelegramAPI_GetBotInfo() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token", TestParameters); - + Telegram_GetBotInformation(TestParameters); - + EndProcedure Procedure TelegramAPI_GetUpdates() Export TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token", TestParameters); - + Telegram_DeleteWebhook(TestParameters); Telegram_GetUpdates(TestParameters); - + EndProcedure Procedure TelegramAPI_SetWebhook() Export TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_URL" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_URL" , TestParameters); Telegram_SetWebhook(TestParameters); Telegram_DeleteWebhook(TestParameters); - + EndProcedure Procedure TelegramAPI_SendTextMessage() Export TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); + Telegram_SendTextMessage(TestParameters); - + EndProcedure Procedure TelegramAPI_SendImage() Export TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); + Telegram_SendPicture(TestParameters); Telegram_DownloadFile(TestParameters); @@ -125,12 +125,12 @@ EndProcedure Procedure TelegramAPI_SendVideo() Export TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Video" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Video" , TestParameters); + Telegram_SendVideo(TestParameters); Telegram_DownloadFile(TestParameters); @@ -139,12 +139,12 @@ EndProcedure Procedure TelegramAPI_SendAudio() Export TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Audio" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Audio" , TestParameters); + Telegram_SendAudio(TestParameters); Telegram_DownloadFile(TestParameters); @@ -153,12 +153,12 @@ EndProcedure Procedure TelegramAPI_SendDocument() Export TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Document" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Document" , TestParameters); + Telegram_SendDocument(TestParameters); EndProcedure @@ -166,110 +166,110 @@ EndProcedure Procedure TelegramAPI_SendGIF() Export TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("GIF" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("GIF" , TestParameters); + Telegram_SendGif(TestParameters); EndProcedure Procedure TelegramAPI_SendMediaGroup() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Video" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Document" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Video" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Document" , TestParameters); + Telegram_SendMediaGroup(TestParameters); EndProcedure Procedure TelegramAPI_SendLocation() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Long" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Lat" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("Long" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Lat" , TestParameters); + Telegram_SendLocation(TestParameters); EndProcedure Procedure TelegramAPI_SendContact() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Name" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Surname" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Phone" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Name" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Surname" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Phone" , TestParameters); Telegram_SendContact(TestParameters); EndProcedure Procedure TelegramAPI_SendPoll() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID", TestParameters); - + Telegram_SendPoll(TestParameters); EndProcedure Procedure TelegramAPI_ForwardMessage() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelMessageID", TestParameters); Telegram_ForwardMessage(TestParameters); - + EndProcedure Procedure TelegramAPI_BanUnban() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID" , TestParameters); - + Telegram_Ban(TestParameters); Telegram_Unban(TestParameters); - + EndProcedure Procedure TelegramAPI_CreateInvitationLink() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID", TestParameters); - + Telegram_CreateInviteLink(TestParameters); EndProcedure Procedure TelegramAPI_PinUnpinMessage() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelMessageID", TestParameters); - + Telegram_PinMessage(TestParameters); Telegram_UnpinMessage(TestParameters); Telegram_DeleteMessage(TestParameters); @@ -277,32 +277,32 @@ Procedure TelegramAPI_PinUnpinMessage() Export EndProcedure Procedure TelegramAPI_GetMemberCount() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID", TestParameters); - + Telegram_GetParticipantCount(TestParameters); EndProcedure Procedure TelegramAPI_GetForumAvatarsList() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token", TestParameters); - + Telegram_GetForumAvatarList(TestParameters); - + EndProcedure Procedure TelegramAPI_CreateDeleteForumTopic() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ForumID", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); + Telegram_CreateForumTopic(TestParameters); Telegram_EditForumTopic(TestParameters); Telegram_CloseForumTopic(TestParameters); @@ -313,9 +313,9 @@ Procedure TelegramAPI_CreateDeleteForumTopic() Export EndProcedure Procedure TelegramAPI_HideShowMainTopic() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ForumID", TestParameters); Telegram_HideMainForumTopic(TestParameters); @@ -324,13 +324,13 @@ Procedure TelegramAPI_HideShowMainTopic() Export EndProcedure Procedure TelegramAPI_ChangeMainTopicName() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ForumID", TestParameters); Telegram_ChangeMainTopicName(TestParameters); - + EndProcedure #EndRegion @@ -338,251 +338,251 @@ EndProcedure #Region VK Procedure VKAPI_CreateTokenLink() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("VK_AppID", TestParameters); - VK_CreateTokenRetrievalLink(TestParameters); - + VK_CreateTokenRetrievalLink(TestParameters); + EndProcedure Procedure VKAPI_CreateDeletePost() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Picture2", TestParameters); - + VK_CreatePost(TestParameters); VK_DeletePost(TestParameters); EndProcedure Procedure VKAPI_CreateCompositePost() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Video" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("Video" , TestParameters); + VK_CreateCompositePost(TestParameters); - + EndProcedure Procedure VKAPI_CreatePoll() Export - + VK_CreatePoll(); - + EndProcedure Procedure VKAPI_SaveDeleteImage() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); - + VK_CreateAlbum(TestParameters); VK_SavePictureToAlbum(TestParameters); VK_DeleteImage(TestParameters); VK_DeleteAlbum(TestParameters); - + EndProcedure Procedure VKAPI_CreateStory() Export - + TestParameters = New Map; OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); - + VK_CreateStory(TestParameters); - + EndProcedure Procedure VKAPI_DiscussionMethods() Export - + TestParameters = New Structure; - Parameters = GetVKParameters(); - + Parameters = GetVKParameters(); + VK_CreateDiscussion(TestParameters); VK_CloseDiscussion(TestParameters); VK_OpenDiscussion(TestParameters); - VK_PostToDiscussion(TestParameters); - + VK_PostToDiscussion(TestParameters); + OPI_VK.CloseDiscussion(TestParameters["VK_ConvID"], True, Parameters); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VKAPI_LikeRepostComment() Export - + TestParameters = New Structure(); - Parameters = GetVKParameters(); - Text = "Post from autotest"; - - Result = OPI_VK.CreatePost(Text, New Array, , , Parameters); - PostID = Result["response"]["post_id"]; - + Parameters = GetVKParameters(); + Text = "Post from autotest"; + + Result = OPI_VK.CreatePost(Text, New Array, , , Parameters); + PostID = Result["response"]["post_id"]; + OPI_TestDataRetrieval.WriteParameter("VK_PostID", PostID); OPI_TestDataRetrieval.ParameterToCollection("VK_PostID", TestParameters); - - VK_LikePost(TestParameters); - VK_MakeRepost(TestParameters); - VK_WriteComment(TestParameters); - - OPI_VK.DeletePost(PostID, Parameters); + + VK_LikePost(TestParameters); + VK_MakeRepost(TestParameters); + VK_WriteComment(TestParameters); + + OPI_VK.DeletePost(PostID , Parameters); OPI_VK.DeletePost(TestParameters["Repost"], Parameters); - + OPI_Tools.Pause(5); EndProcedure Procedure VKAPI_GetStatistics() Export - + TestParameters = New Structure(); - + VK_GetStatistics(TestParameters); - + OPI_Tools.Pause(5); EndProcedure Procedure VKAPI_GetPostStatistics() Export - + TestParameters = New Structure(); - + VK_GetPostStatistics(TestParameters); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VKAPI_CreateAdCampaign() Export - + Parameters = GetVKParameters(); - Text = "Post from autotest"; - - Result = OPI_VK.CreatePost(Text, New Array, , , Parameters); - PostID = Result["response"]["post_id"]; - + Text = "Post from autotest"; + + Result = OPI_VK.CreatePost(Text, New Array, , , Parameters); + PostID = Result["response"]["post_id"]; + OPI_TestDataRetrieval.WriteParameter("VK_PostID", PostID); - + TestParameters = New Structure(); OPI_TestDataRetrieval.ParameterToCollection("VK_AdsCabinetID", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("VK_PostID" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("VK_PostID" , TestParameters); + VK_CreateAdCampaign(TestParameters); VK_CreateAd(TestParameters); VK_PauseAdvertising(TestParameters); - + OPI_VK.DeletePost(PostID, Parameters); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VKAPI_SendMessage() Export - + TestParameters = New Structure; - - OPI_TestDataRetrieval.ParameterToCollection("VK_UserID", TestParameters); + + OPI_TestDataRetrieval.ParameterToCollection("VK_UserID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("VK_CommunityToken", TestParameters); VK_FormKeyboard(TestParameters); VK_WriteMessage(TestParameters); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VKAPI_GetProductCategories() Export - + TestParameters = New Structure; - + VK_GetProductCategoryList(TestParameters); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VKAPI_CreateProductSelection() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Picture", TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Picture2", TestParameters); - + CreateProductCollection(TestParameters); EditProductCollection(TestParameters); VK_AddProduct(TestParameters); VK_EditProduct(TestParameters); - VK_AddProductToCollection(TestParameters); + VK_AddProductToCollection(TestParameters); VK_RemoveProductFromCollection(TestParameters); VK_DeleteProduct(TestParameters); VK_DeleteCollection(TestParameters); OPI_Tools.Pause(5); - + EndProcedure Procedure VKAPI_CreateProductWithProperties() Export - + Parameters = GetVKParameters(); - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Picture", TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Picture2", TestParameters); - + VK_CreateProductProperty(TestParameters); - VK_EditProductProperty(TestParameters); - VK_AddProductPropertyVariant(TestParameters); - VK_EditProductPropertyVariant(TestParameters); + VK_EditProductProperty(TestParameters); + VK_AddProductPropertyVariant(TestParameters); + VK_EditProductPropertyVariant(TestParameters); VK_CreateProductWithProp(TestParameters); VK_GetProductsByID(TestParameters); VK_GroupProducts(TestParameters); - + OPI_VK.DeleteProduct(TestParameters["VK_MarketItemID2"], Parameters); OPI_VK.DeleteProduct(TestParameters["VK_MarketItemID3"], Parameters); - + VK_DeleteProductPropertyVariant(TestParameters); VK_DeleteProductProperty(TestParameters); - + EndProcedure Procedure VKAPI_GetProductList() Export - + TestParameters = New Structure; - + VK_GetProductList(TestParameters); - + EndProcedure Procedure VKAPI_GetSelectionList() Export - + TestParameters = New Structure; - + VK_GetSelectionList(TestParameters); - + EndProcedure Procedure VKAPI_GetPropertyList() Export - + TestParameters = New Structure; - + VK_GetPropertyList(TestParameters); EndProcedure Procedure VKAPI_GetOrderList() Export - + TestParameters = New Structure; - + VK_GetOrderList(TestParameters); - + EndProcedure Procedure VKAPI_UploadVideo() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Video", TestParameters); - + VK_UploadVideoToServer(TestParameters); - + EndProcedure #EndRegion @@ -590,135 +590,135 @@ EndProcedure #Region YandexDisk Procedure YDisk_GetDiskInfo() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("YandexDisk_Token", TestParameters); - + YandexDisk_GetDiskInfo(TestParameters); - + EndProcedure Procedure YDisk_CreateFolder() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("YandexDisk_Token", TestParameters); - + YandexDisk_CreateFolder(TestParameters); - + EndProcedure Procedure YDisk_UploadByUrlAndGetObject() Export - + Token = OPI_TestDataRetrieval.GetParameter("YandexDisk_Token"); - Path = "/" + String(New UUID) + ".png"; - URL = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/Media/logo.png"; + Path = "/" + String(New UUID) + ".png"; + URL = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/Media/logo.png"; OPI_YandexDisk.UploadFileByURL(Token, Path, URL); OPI_Tools.Pause(5); - + Result = OPI_YandexDisk.GetObject(Token, Path); - + OPI_TestDataRetrieval.WriteLog(Result, "GetObject"); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["type"]).Равно("file"); OPI_TestDataRetrieval.ExpectsThat(Result["path"]).Равно("disk:" + Path); OPI_YandexDisk.DeleteObject(Token, Path, False); - + OPI_Tools.Pause(5); - + EndProcedure Procedure YDisk_UploadDeleteFile() Export - + Token = OPI_TestDataRetrieval.GetParameter("YandexDisk_Token"); - Path = "/" + String(New UUID) + ".png"; + Path = "/" + String(New UUID) + ".png"; Image = OPI_TestDataRetrieval.GetBinary("Picture"); - TFN = GetTempFileName("png"); + TFN = GetTempFileName("png"); Image.Write(TFN); Result = OPI_YandexDisk.UploadFile(Token, Path, Image, True); - + OPI_TestDataRetrieval.WriteLog(Result, "UploadFile"); - + Check_Empty(Result); OPI_Tools.Pause(5); - + Result = OPI_YandexDisk.DeleteObject(Token, Path, False); - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteObject"); - + Check_Empty(Result); - + Result = OPI_YandexDisk.UploadFile(Token, Path, TFN, True); - + OPI_TestDataRetrieval.WriteLog(Result, "UploadFile"); - + Check_Empty(Result); OPI_Tools.Pause(5); - - Result = OPI_YandexDisk.DeleteObject(Token, Path, False); - + + Result = OPI_YandexDisk.DeleteObject(Token, Path, False); + OPI_TestDataRetrieval.WriteLog(Result, "DeleteObject"); - - Check_Empty(Result); + + Check_Empty(Result); DeleteFiles(TFN); - + OPI_Tools.Pause(5); - + EndProcedure Procedure YDisk_CreateObjectCopy() Export - - Token = OPI_TestDataRetrieval.GetParameter("YandexDisk_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("YandexDisk_Token"); OriginalPath = "/" + String(New UUID) + ".png"; - CopyPath = "/" + String(New UUID) + ".png"; - URL = "https://raw.githubusercontent.com/Bayselonarrend/" + CopyPath = "/" + String(New UUID) + ".png"; + URL = "https://raw.githubusercontent.com/Bayselonarrend/" + "OpenIntegrations/main/Media/logo.png"; OPI_YandexDisk.UploadFileByURL(Token, OriginalPath, URL); OPI_Tools.Pause(25); - + Result = OPI_YandexDisk.CreateObjectCopy(Token, OriginalPath, CopyPath, True); - + OPI_TestDataRetrieval.WriteLog(Result, "CreateObjectCopy"); - + OPI_Tools.Pause(5); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["type"]).Равно("file"); OPI_TestDataRetrieval.ExpectsThat(Result["path"]).Равно("disk:" + CopyPath); OPI_YandexDisk.DeleteObject(Token, OriginalPath, False); - OPI_YandexDisk.DeleteObject(Token, CopyPath, False); - + OPI_YandexDisk.DeleteObject(Token, CopyPath , False); + OPI_Tools.Pause(5); - + EndProcedure Procedure YDisk_GetDownloadLink() Export - + Token = OPI_TestDataRetrieval.GetParameter("YandexDisk_Token"); - Path = "/" + String(New UUID) + ".png"; - URL = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/Media/logo.png"; + Path = "/" + String(New UUID) + ".png"; + URL = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/Media/logo.png"; OPI_YandexDisk.UploadFileByURL(Token, Path, URL); OPI_Tools.Pause(5); - + Result = OPI_YandexDisk.GetDownloadLink(Token, Path); - + OPI_TestDataRetrieval.WriteLog(Result, "GetDownloadLink"); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["method"]).Равно("GET"); OPI_TestDataRetrieval.ExpectsThat(Result["href"]).ИмеетТип("String").Заполнено(); - + URL = Result["href"]; - + Result = OPI_YandexDisk.DownloadFile(Token, Path); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("BinaryData").Заполнено(); OPI_YandexDisk.DeleteObject(Token, Path, False); @@ -726,131 +726,131 @@ Procedure YDisk_GetDownloadLink() Export EndProcedure Procedure YDisk_GetFileList() Export - - Token = OPI_TestDataRetrieval.GetParameter("YandexDisk_Token"); - Count = 2; + + Token = OPI_TestDataRetrieval.GetParameter("YandexDisk_Token"); + Count = 2; Indent = 1; - + Result = OPI_YandexDisk.GetFilesList(Token, Count, Indent, "image"); - + OPI_TestDataRetrieval.WriteLog(Result, "GetFilesList"); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["limit"]).Равно(Count); OPI_TestDataRetrieval.ExpectsThat(Result["offset"]).Равно(Indent); OPI_TestDataRetrieval.ExpectsThat(Result["items"]).ИмеетТип("Array"); - + OPI_Tools.Pause(5); - + EndProcedure Procedure YDisk_MoveObject() Export - - Token = OPI_TestDataRetrieval.GetParameter("YandexDisk_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("YandexDisk_Token"); OriginalPath = "/" + String(New UUID) + ".png"; - CopyPath = "/" + String(New UUID) + ".png"; - URL = "https://raw.githubusercontent.com/Bayselonarrend/" + CopyPath = "/" + String(New UUID) + ".png"; + URL = "https://raw.githubusercontent.com/Bayselonarrend/" + "OpenIntegrations/main/Media/logo.png"; Result = OPI_YandexDisk.UploadFileByURL(Token, OriginalPath, URL); - + OPI_TestDataRetrieval.WriteLog(Result, "UploadFileByURL"); - + OPI_Tools.Pause(15); - + Result = OPI_YandexDisk.MoveObject(Token, OriginalPath, CopyPath, True); - + OPI_TestDataRetrieval.WriteLog(Result, "MoveObject"); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["type"]).Равно("file"); OPI_TestDataRetrieval.ExpectsThat(Result["path"]).Равно("disk:" + CopyPath); OPI_YandexDisk.DeleteObject(Token, OriginalPath, False); - OPI_YandexDisk.DeleteObject(Token, CopyPath, False); - + OPI_YandexDisk.DeleteObject(Token, CopyPath , False); + OPI_Tools.Pause(5); - + EndProcedure Procedure YDisk_PublicObjectActions() Export - - PUrl = "public_url"; - Map = "Map"; + + PUrl = "public_url"; + Map = "Map"; Token = OPI_TestDataRetrieval.GetParameter("YandexDisk_Token"); - Path = "/" + String(New UUID) + ".png"; - URL = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/Media/logo.png"; - + Path = "/" + String(New UUID) + ".png"; + URL = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/Media/logo.png"; + OPI_YandexDisk.UploadFileByURL(Token, Path, URL); OPI_Tools.Pause(5); - + ResultArray = New Array; - - ResultArray.Add(OPI_YandexDisk.PublishObject(Token, Path)); + + ResultArray.Add(OPI_YandexDisk.PublishObject(Token, Path)); PublicURL = ResultArray[0][PUrl]; - + Result = OPI_YandexDisk.GetDownloadLinkForPublicObject(Token, PublicURL); - + OPI_TestDataRetrieval.WriteLog(Result, "GetDownloadLinkForPublicObject"); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип(Map).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["method"]).Равно("GET"); OPI_TestDataRetrieval.ExpectsThat(Result["href"]).ИмеетТип("String").Заполнено(); - + Result = OPI_YandexDisk.GetPublicObject(Token, PublicURL); - + OPI_TestDataRetrieval.WriteLog(Result, "GetPublicObject"); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип(Map).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["type"]).Равно("file"); OPI_TestDataRetrieval.ExpectsThat(Result["path"]).Равно("/"); - + ResultArray.Add(OPI_YandexDisk.SavePublicObjectToDisk(Token, PublicURL)); - + ResultArray.Add(OPI_YandexDisk.CancelObjectPublication(Token, Path)); - + Counter = 0; For Each Result In ResultArray Do - + OPI_TestDataRetrieval.WriteLog(Result, "PublicationChange"); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип(Map).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["type"]).Равно("file"); OPI_TestDataRetrieval.ExpectsThat(Result["path"]).Заполнено(); - - If Counter = 0 Then + + If Counter = 0 Then OPI_TestDataRetrieval.ExpectsThat(Result[PUrl]).ИмеетТип("String").Заполнено(); Else OPI_TestDataRetrieval.ExpectsThat(Result[PUrl]).ИмеетТип("Undefined"); EndIf; - + Counter = Counter + 1; - + EndDo; - + OPI_YandexDisk.DeleteObject(Token, Path, False); - + OPI_Tools.Pause(5); EndProcedure Procedure YDisk_GetPublishedList() Export - - Token = OPI_TestDataRetrieval.GetParameter("YandexDisk_Token"); - Count = 2; + + Token = OPI_TestDataRetrieval.GetParameter("YandexDisk_Token"); + Count = 2; Indent = 1; - + Result = OPI_YandexDisk.GetPublishedObjectsList(Token, Count, Indent); - + OPI_TestDataRetrieval.WriteLog(Result, "GetPublishedObjectsList"); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["limit"]).Равно(Count); OPI_TestDataRetrieval.ExpectsThat(Result["offset"]).Равно(Indent); OPI_TestDataRetrieval.ExpectsThat(Result["items"]).ИмеетТип("Array"); - + OPI_Tools.Pause(5); - + EndProcedure #EndRegion @@ -858,12 +858,12 @@ EndProcedure #Region Viber Procedure Viber_GetChannelInfo() Export - - Token = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); + + Token = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); Result = OPI_Viber.GetChannelInformation(Token); - + OPI_TestDataRetrieval.WriteLog(Result, "GetChannelInformation"); - + Check_ViberOk(Result); OPI_Tools.Pause(5); @@ -871,13 +871,13 @@ Procedure Viber_GetChannelInfo() Export EndProcedure Procedure Viber_GetUserData() Export - - Token = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); - User = OPI_TestDataRetrieval.GetParameter("Viber_ChannelAdminID"); + + Token = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); + User = OPI_TestDataRetrieval.GetParameter("Viber_ChannelAdminID"); Result = OPI_Viber.GetUserData(Token, User); - + OPI_TestDataRetrieval.WriteLog(Result, "GetUserData"); - + OPI_TestDataRetrieval.ExpectsThat(Result["chat_hostname"]).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["status_message"]).Заполнено(); OPI_Tools.Pause(5); @@ -885,184 +885,184 @@ Procedure Viber_GetUserData() Export EndProcedure Procedure Viber_GetOnlineUsers() Export - - Token = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); - User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); + + Token = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); + User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); Result = OPI_Viber.GetOnlineUsers(Token, User); - + OPI_TestDataRetrieval.WriteLog(Result, "GetOnlineUsers"); - + OPI_TestDataRetrieval.ExpectsThat(Result["users"]).ИмеетТип("Array"); Check_ViberOk(Result); - + OPI_Tools.Pause(5); EndProcedure Procedure Viber_SendTextMessage() Export - - Text = "TestMessage"; - ChannelToken = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); - BotToken = OPI_TestDataRetrieval.GetParameter("Viber_Token"); - User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); + + Text = "TestMessage"; + ChannelToken = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); + BotToken = OPI_TestDataRetrieval.GetParameter("Viber_Token"); + User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); Administrator = OPI_TestDataRetrieval.GetParameter("Viber_ChannelAdminID"); - + ButtonArray = New Array; ButtonArray.Add("Button 1"); ButtonArray.Add("Button 2"); ButtonArray.Add("Button 3"); - + Keyboard = OPI_Viber.CreateKeyboardFromArrayButton(ButtonArray); - + Result = OPI_Viber.SendTextMessage(BotToken, Text, User, False, Keyboard); - + OPI_TestDataRetrieval.WriteLog(Result, "SendTextMessage"); - + OPI_TestDataRetrieval.ExpectsThat(Result["message_token"]).Заполнено(); Check_ViberOk(Result); - + Result = OPI_Viber.SendTextMessage(ChannelToken, Text, Administrator, True, Keyboard); - + OPI_TestDataRetrieval.WriteLog(Result, "SendTextMessage"); - + OPI_TestDataRetrieval.ExpectsThat(Result["message_token"]).Заполнено(); Check_ViberOk(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Viber_SendImage() Export - Text = "TestMessage"; - Image = OPI_TestDataRetrieval.GetParameter("Picture"); - ChannelToken = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); - BotToken = OPI_TestDataRetrieval.GetParameter("Viber_Token"); - User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); + Text = "TestMessage"; + Image = OPI_TestDataRetrieval.GetParameter("Picture"); + ChannelToken = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); + BotToken = OPI_TestDataRetrieval.GetParameter("Viber_Token"); + User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); Administrator = OPI_TestDataRetrieval.GetParameter("Viber_ChannelAdminID"); - + Result = OPI_Viber.SendImage(BotToken, Image, User, False, Text); - + OPI_TestDataRetrieval.WriteLog(Result, "SendImage"); - + OPI_TestDataRetrieval.ExpectsThat(Result["message_token"]).Заполнено(); Check_ViberOk(Result); - + Result = OPI_Viber.SendImage(ChannelToken, Image, Administrator, True, Text); - + OPI_TestDataRetrieval.WriteLog(Result, "SendImage"); - + OPI_TestDataRetrieval.ExpectsThat(Result["message_token"]).Заполнено(); Check_ViberOk(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Viber_SendFile() Export - - Document = OPI_TestDataRetrieval.GetParameter("Document"); - ChannelToken = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); - BotToken = OPI_TestDataRetrieval.GetParameter("Viber_Token"); - User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); + + Document = OPI_TestDataRetrieval.GetParameter("Document"); + ChannelToken = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); + BotToken = OPI_TestDataRetrieval.GetParameter("Viber_Token"); + User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); Administrator = OPI_TestDataRetrieval.GetParameter("Viber_ChannelAdminID"); - + Result = OPI_Viber.SendFile(BotToken, Document, User, False, "docx"); - + OPI_TestDataRetrieval.WriteLog(Result, "SendFile"); - + OPI_TestDataRetrieval.ExpectsThat(Result["message_token"]).Заполнено(); Check_ViberOk(Result); - + Result = OPI_Viber.SendFile(ChannelToken, Document, Administrator, True, "docx"); - + OPI_TestDataRetrieval.WriteLog(Result, "SendFile"); - + OPI_TestDataRetrieval.ExpectsThat(Result["message_token"]).Заполнено(); Check_ViberOk(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Viber_SendContact() Export - - Name = "Petr Petrov"; - Phone = "+123456789"; - ChannelToken = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); - BotToken = OPI_TestDataRetrieval.GetParameter("Viber_Token"); - User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); + + Name = "Petr Petrov"; + Phone = "+123456789"; + ChannelToken = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); + BotToken = OPI_TestDataRetrieval.GetParameter("Viber_Token"); + User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); Administrator = OPI_TestDataRetrieval.GetParameter("Viber_ChannelAdminID"); - + Result = OPI_Viber.SendContact(BotToken, Name, Phone, User, False); - + OPI_TestDataRetrieval.WriteLog(Result, "SendContact"); - + OPI_TestDataRetrieval.ExpectsThat(Result["message_token"]).Заполнено(); Check_ViberOk(Result); - + Result = OPI_Viber.SendContact(ChannelToken, Name, Phone, Administrator, True); - + OPI_TestDataRetrieval.WriteLog(Result, "SendContact"); - + OPI_TestDataRetrieval.ExpectsThat(Result["message_token"]).Заполнено(); Check_ViberOk(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Viber_SendLocation() Export - Latitude = "48.87373649724122"; - Longitude = "2.2954639195323967"; - ChannelToken = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); - BotToken = OPI_TestDataRetrieval.GetParameter("Viber_Token"); - User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); + Latitude = "48.87373649724122"; + Longitude = "2.2954639195323967"; + ChannelToken = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); + BotToken = OPI_TestDataRetrieval.GetParameter("Viber_Token"); + User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); Administrator = OPI_TestDataRetrieval.GetParameter("Viber_ChannelAdminID"); - + Result = OPI_Viber.SendLocation(BotToken, Latitude, Longitude, User, False); - + OPI_TestDataRetrieval.WriteLog(Result, "SendLocation"); - + OPI_TestDataRetrieval.ExpectsThat(Result["message_token"]).Заполнено(); Check_ViberOk(Result); - + Result = OPI_Viber.SendLocation(ChannelToken, Latitude, Longitude, Administrator, True); - + OPI_TestDataRetrieval.WriteLog(Result, "SendLocation"); - + OPI_TestDataRetrieval.ExpectsThat(Result["message_token"]).Заполнено(); Check_ViberOk(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Viber_SendLink() Export - URL = "https://github.com/Bayselonarrend/OpenIntegrations"; - ChannelToken = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); - BotToken = OPI_TestDataRetrieval.GetParameter("Viber_Token"); - User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); + URL = "https://github.com/Bayselonarrend/OpenIntegrations"; + ChannelToken = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); + BotToken = OPI_TestDataRetrieval.GetParameter("Viber_Token"); + User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); Administrator = OPI_TestDataRetrieval.GetParameter("Viber_ChannelAdminID"); - + Result = OPI_Viber.SendLink(BotToken, URL, User, False); - + OPI_TestDataRetrieval.WriteLog(Result, "SendLink"); - + OPI_TestDataRetrieval.ExpectsThat(Result["message_token"]).Заполнено(); Check_ViberOk(Result); - + Result = OPI_Viber.SendLink(ChannelToken, URL, Administrator, True); - + OPI_TestDataRetrieval.WriteLog(Result, "SendLink"); - + OPI_TestDataRetrieval.ExpectsThat(Result["message_token"]).Заполнено(); Check_ViberOk(Result); - + OPI_Tools.Pause(5); - + EndProcedure #EndRegion @@ -1070,53 +1070,53 @@ EndProcedure #Region GoogleWorkspace Procedure GV_GetAuthorizationLink() Export - - ClientID = OPI_TestDataRetrieval.GetParameter("Google_ClientID"); - Result = OPI_GoogleWorkspace.FormCodeRetrievalLink(ClientID); - + + ClientID = OPI_TestDataRetrieval.GetParameter("Google_ClientID"); + Result = OPI_GoogleWorkspace.FormCodeRetrievalLink(ClientID); + OPI_TestDataRetrieval.ExpectsThat(Result) - .ИмеетТип("String") + .ИмеетТип("String") .Заполнено(); - + OPI_TestDataRetrieval.WriteParameter("Google_Link", Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure GV_GetToken() Export - - ClientID = OPI_TestDataRetrieval.GetParameter("Google_ClientID"); + + ClientID = OPI_TestDataRetrieval.GetParameter("Google_ClientID"); ClientSecret = OPI_TestDataRetrieval.GetParameter("Google_ClientSecret"); - Code = OPI_TestDataRetrieval.GetParameter("Google_Code"); - + Code = OPI_TestDataRetrieval.GetParameter("Google_Code"); + Result = OPI_GoogleWorkspace.GetTokenByCode(ClientID, ClientSecret, Code); - + If ValueIsFilled(Result["access_token"]) And ValueIsFilled(Result["refresh_token"]) Then - - OPI_TestDataRetrieval.WriteParameter("Google_Token" , Result["access_token"]); + + OPI_TestDataRetrieval.WriteParameter("Google_Token" , Result["access_token"]); OPI_TestDataRetrieval.WriteParameter("Google_Refresh", Result["refresh_token"]); - + EndIf; - + OPI_Tools.Pause(5); - + EndProcedure Procedure GV_UpdateToken() Export - - ClientID = OPI_TestDataRetrieval.GetParameter("Google_ClientID"); + + ClientID = OPI_TestDataRetrieval.GetParameter("Google_ClientID"); ClientSecret = OPI_TestDataRetrieval.GetParameter("Google_ClientSecret"); RefreshToken = OPI_TestDataRetrieval.GetParameter("Google_Refresh"); - + Result = OPI_GoogleWorkspace.RefreshToken(ClientID, ClientSecret, RefreshToken); - - OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map"); + + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["access_token"]).Заполнено(); - + OPI_TestDataRetrieval.WriteParameter("Google_Token", Result["access_token"]); - + OPI_Tools.Pause(5); EndProcedure @@ -1126,181 +1126,181 @@ EndProcedure #Region GoogleCalendar Procedure GC_GetCalendarList() Export - - Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); Result = OPI_GoogleCalendar.GetCalendarList(Token); - + OPI_TestDataRetrieval.WriteLog(Result, "GetCalendarList"); - + OPI_TestDataRetrieval.ExpectsThat(Result) .ИмеетТип("Array"); OPI_Tools.Pause(5); - + EndProcedure Procedure GC_CreateDeleteCalendar() Export - - Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); - Name = "TestCalendar"; + + Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); + Name = "TestCalendar"; Description = "TestDescription"; - EditedName = Name + " (change.)"; - TypeMap = Type("Map"); - TypeString = Type("String"); - Summary = "summary"; - Black = "#000000"; - Yellow = "#ffd800"; - - Result = OPI_GoogleCalendar.CreateCalendar(Token, Name); - + EditedName = Name + " (change.)"; + TypeMap = Type("Map"); + TypeString = Type("String"); + Summary = "summary"; + Black = "#000000"; + Yellow = "#ffd800"; + + Result = OPI_GoogleCalendar.CreateCalendar(Token, Name); + OPI_TestDataRetrieval.WriteLog(Result, "CreateCalendar"); - - OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип(TypeMap); + + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип(TypeMap); OPI_TestDataRetrieval.ExpectsThat(Result[Summary]).Равно(Name); OPI_TestDataRetrieval.ExpectsThat(Result["id"]).ИмеетТип(TypeString).Заполнено(); - + Calendar = Result["id"]; - + Result = OPI_GoogleCalendar.EditCalendarMetadata(Token , Calendar , EditedName , Description); - + OPI_TestDataRetrieval.WriteLog(Result, "EditCalendarMetadata"); - + Check_GKObject(Result, EditedName, Description); - + Result = OPI_GoogleCalendar.GetCalendarMetadata(Token, Calendar); - - OPI_TestDataRetrieval.WriteLog(Result, "GetCalendarMetadata"); - + + OPI_TestDataRetrieval.WriteLog(Result, "GetCalendarMetadata"); + Check_GKObject(Result, EditedName, Description); Result = OPI_GoogleCalendar.AddCalendarToList(Token, Calendar); - + OPI_TestDataRetrieval.WriteLog(Result, "AddCalendarToList"); - + Check_GKObject(Result, EditedName, Description); - + Result = OPI_GoogleCalendar.EditListCalendar(Token, Calendar, Black, Yellow, False); - + OPI_TestDataRetrieval.WriteLog(Result, "EditListCalendar"); - - OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип(TypeMap); + + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип(TypeMap); OPI_TestDataRetrieval.ExpectsThat(Result[Summary]).Равно(EditedName); OPI_TestDataRetrieval.ExpectsThat(Result["foregroundColor"]).Равно(Black); OPI_TestDataRetrieval.ExpectsThat(Result["backgroundColor"]).Равно(Yellow); - + Result = OPI_GoogleCalendar.GetListCalendar(Token, Calendar); - + OPI_TestDataRetrieval.WriteLog(Result, "GetListCalendar"); - - OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип(TypeMap); + + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип(TypeMap); OPI_TestDataRetrieval.ExpectsThat(Result[Summary]).Равно(EditedName); OPI_TestDataRetrieval.ExpectsThat(Result["foregroundColor"]).Равно(Black); OPI_TestDataRetrieval.ExpectsThat(Result["backgroundColor"]).Равно(Yellow); Result = OPI_GoogleCalendar.ClearMainCalendar(Token); - + OPI_TestDataRetrieval.WriteLog(Result, "ClearMainCalendar"); - + Check_Empty(Result); - + Result = OPI_GoogleCalendar.DeleteCalendarFromList(Token, Calendar); - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteCalendarFromList"); - + Check_Empty(Result); - + Result = OPI_GoogleCalendar.DeleteCalendar(Token, Calendar); - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteCalendar"); - + Check_Empty(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure GC_CreateDeleteEvent() Export - - CurrentDate = OPI_Tools.GetCurrentDate(); - Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); - Calendar = OPI_TestDataRetrieval.GetParameter("Google_CalendarID"); + + CurrentDate = OPI_Tools.GetCurrentDate(); + Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); + Calendar = OPI_TestDataRetrieval.GetParameter("Google_CalendarID"); Name = "New event"; - Description = "TestEventDescription"; + Description = "TestEventDescription"; EditedDescription = "Test event description (change.)"; UID = "id"; Hour = 3600; Attachments = New Map; - + Attachments.Insert("Image1" , "https://opi.neocities.org/assets/images/logo_long-e8fdcca6ff8b32e679ea49a1ccdd3eac.png"); Attachments.Insert("Image2" , "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/Media/logo.png?v1"); - + EventMap = New Map; - EventMap.Insert("Description" , Description); - EventMap.Insert("Title" , Name); - EventMap.Insert("Venue" , "InOffice"); - EventMap.Insert("StartDate" , CurrentDate); - EventMap.Insert("EndDate" , EventMap["StartDate"] + Hour); + EventMap.Insert("Description" , Description); + EventMap.Insert("Title" , Name); + EventMap.Insert("Venue" , "InOffice"); + EventMap.Insert("StartDate" , CurrentDate); + EventMap.Insert("EndDate" , EventMap["StartDate"] + Hour); EventMap.Insert("ArrayOfAttachmentURLs" , Attachments); - EventMap.Insert("SendNotifications" , True); - + EventMap.Insert("SendNotifications" , True); + Result = OPI_GoogleCalendar.CreateEvent(Token, Calendar, EventMap); - + OPI_TestDataRetrieval.WriteLog(Result, "CreateEvent"); - + Event = Result[UID]; - + Check_GKObject(Result, Name, Description); - - EventMap = New Map; + + EventMap = New Map; EventMap.Insert("Description", EditedDescription); - + Result = OPI_GoogleCalendar.EditEvent(Token, Calendar, EventMap, Event); - + OPI_TestDataRetrieval.WriteLog(Result, "EditEvent"); - + Check_GKObject(Result, Name, EditedDescription); - + Result = OPI_GoogleCalendar.GetEvent(Token, Calendar, Event); - + OPI_TestDataRetrieval.WriteLog(Result, "GetEvent"); - + Check_GKObject(Result, Name, EditedDescription); Result = OPI_GoogleCalendar.MoveEvent(Token, Calendar, Calendar, Event); - + OPI_TestDataRetrieval.WriteLog(Result, "MoveEvent"); - + Check_GKObject(Result, Name, EditedDescription); - - Result = OPI_GoogleCalendar.DeleteEvent(Token, Calendar, Event); - + + Result = OPI_GoogleCalendar.DeleteEvent(Token, Calendar, Event); + OPI_TestDataRetrieval.WriteLog(Result, "DeleteEvent"); - + Check_Empty(Result); - + OPI_Tools.Pause(5); EndProcedure Procedure GC_GetEventList() Export - - Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); Calendar = OPI_TestDataRetrieval.GetParameter("Google_CalendarID"); Result = OPI_GoogleCalendar.GetEventList(Token, Calendar); - + OPI_TestDataRetrieval.WriteLog(Result, "GetEventList"); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Array"); - + OPI_Tools.Pause(5); - + EndProcedure #EndRegion @@ -1308,197 +1308,197 @@ EndProcedure #Region GoogleDrive Procedure GD_GetCatalogList() Export - + MimeType_ = "mimeType"; - Name_ = "name"; - Name = "TestFolder"; - Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); - Result = OPI_GoogleDrive.GetDirectoriesList(Token, Name, True); - + Name_ = "name"; + Name = "TestFolder"; + Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); + Result = OPI_GoogleDrive.GetDirectoriesList(Token, Name, True); + OPI_TestDataRetrieval.WriteLog(Result, "GetDirectoriesList"); - + Result = Result[0]; - + OPI_TestDataRetrieval.ExpectsThat(Result["files"]).ИмеетТип("Array"); OPI_TestDataRetrieval.ExpectsThat(Result[MimeType_]).Равно("application/vnd.google-apps.folder"); OPI_TestDataRetrieval.ExpectsThat(Result[Name_]).Заполнено(); - + OPI_Tools.Pause(5); Identifier = Result["id"]; - + OPI_TestDataRetrieval.WriteParameter("GD_Catalog", Identifier); - + Result = OPI_GoogleDrive.GetObjectInformation(Token, Identifier); - + OPI_TestDataRetrieval.WriteLog(Result, "GetObjectInformation"); - + OPI_TestDataRetrieval.ExpectsThat(Result[MimeType_]).Равно("application/vnd.google-apps.folder"); OPI_TestDataRetrieval.ExpectsThat(Result[Name_]).Заполнено(); - + OPI_Tools.Pause(5); EndProcedure Procedure GD_UploadDeleteFile() Export - + ExtraBytes = 2; - - Kind_ = "kind"; - Content_ = "content"; - MIME_ = "MIME"; + + Kind_ = "kind"; + Content_ = "content"; + MIME_ = "MIME"; MimeType_ = "mimeType"; - Name_ = "name"; - Id_ = "id"; - + Name_ = "name"; + Id_ = "id"; + ArrayOfDeletions = New Array; - Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); - Image = OPI_TestDataRetrieval.GetBinary("Picture"); + Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); + Image = OPI_TestDataRetrieval.GetBinary("Picture"); ReplacementImage = OPI_TestDataRetrieval.GetBinary("Picture2"); - Directory = OPI_TestDataRetrieval.GetParameter("GD_Catalog"); - + Directory = OPI_TestDataRetrieval.GetParameter("GD_Catalog"); + Description = OPI_GoogleDrive.GetFileDescription(); Description.Insert("Parent", Directory); - + Result = OPI_GoogleDrive.UploadFile(Token, Image, Description); - + OPI_TestDataRetrieval.WriteLog(Result, "UploadFile"); - + OPI_TestDataRetrieval.ExpectsThat(Result[MimeType_]).Равно(Description[MIME_]); OPI_TestDataRetrieval.ExpectsThat(Result[Name_]).Равно(Description["Name"]); Identifier = Result[Id_]; ArrayOfDeletions.Add(Identifier); - + NewName = "CopiedFile.jpeg"; - Result = OPI_GoogleDrive.CopyObject(Token, Identifier, NewName, "root"); - + Result = OPI_GoogleDrive.CopyObject(Token, Identifier, NewName, "root"); + OPI_TestDataRetrieval.WriteLog(Result, "CopyObject"); - + OPI_Tools.Pause(5); - + OPI_TestDataRetrieval.ExpectsThat(Result[MimeType_]).Равно(Description[MIME_]); OPI_TestDataRetrieval.ExpectsThat(Result[Name_]).Равно(NewName); - + ArrayOfDeletions.Add(Result[Id_]); - + Result = OPI_GoogleDrive.DownloadFile(Token, Identifier); - + OPI_TestDataRetrieval.WriteLog(Result, "DownloadFile"); - + OPI_TestDataRetrieval.ExpectsThat(Result.Size()).Равно(Image.Size() + ExtraBytes); OPI_Tools.Pause(5); - + NewName = "UpdatedFile.jpg"; - Result = OPI_GoogleDrive.UpdateFile(Token, Identifier, ReplacementImage, NewName); - + Result = OPI_GoogleDrive.UpdateFile(Token, Identifier, ReplacementImage, NewName); + OPI_TestDataRetrieval.WriteLog(Result, "UpdateFile"); - + OPI_TestDataRetrieval.ExpectsThat(Result[MimeType_]).Равно(Description[MIME_]); OPI_TestDataRetrieval.ExpectsThat(Result[Name_]).Равно(NewName); OPI_Tools.Pause(5); - + Comment = "Yo"; - Result = OPI_GoogleDrive.CreateComment(Token, Identifier, Comment); - + Result = OPI_GoogleDrive.CreateComment(Token, Identifier, Comment); + OPI_TestDataRetrieval.WriteLog(Result, "CreateComment"); - + OPI_TestDataRetrieval.ExpectsThat(Result[Content_]).Равно(Comment); OPI_TestDataRetrieval.ExpectsThat(Result[Kind_]).Равно("drive#comment"); - + OPI_Tools.Pause(5); - + For Each Deletable In ArrayOfDeletions Do - Result = OPI_GoogleDrive.DeleteObject(Token, Deletable); - + Result = OPI_GoogleDrive.DeleteObject(Token, Deletable); + OPI_TestDataRetrieval.WriteLog(Result, "DeleteObject"); - + OPI_TestDataRetrieval.ExpectsThat(ValueIsFilled(Result)).Равно(False); OPI_Tools.Pause(2); EndDo; - + OPI_Tools.Pause(5); - + EndProcedure Procedure GD_CreateDeleteComment() Export - - Kind_ = "kind"; - Content_ = "content"; - Id_ = "id"; + + Kind_ = "kind"; + Content_ = "content"; + Id_ = "id"; Comments_ = "comments"; - Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); + Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); Directory = OPI_TestDataRetrieval.GetParameter("GD_Catalog"); - Image = OPI_TestDataRetrieval.GetBinary("Picture"); - + Image = OPI_TestDataRetrieval.GetBinary("Picture"); + Description = OPI_GoogleDrive.GetFileDescription(); Description.Insert("Parent", Directory); - - Result = OPI_GoogleDrive.UploadFile(Token, Image, Description); + + Result = OPI_GoogleDrive.UploadFile(Token, Image, Description); Identifier = Result[Id_]; - - Comment = "NewComment"; + + Comment = "NewComment"; ResultArray = New Array; - Result = OPI_GoogleDrive.CreateComment(Token, Identifier, Comment); - + Result = OPI_GoogleDrive.CreateComment(Token, Identifier, Comment); + OPI_TestDataRetrieval.WriteLog(Result, "CreateComment"); - + CommentID = Result[Id_]; - + ResultArray.Add(Result); - + Result = OPI_GoogleDrive.GetComment(Token, Identifier, CommentID); - + OPI_TestDataRetrieval.WriteLog(Result, "GetComment"); - + ResultArray.Add(Result); - + Result = OPI_GoogleDrive.GetCommentList(Token, Identifier); - + OPI_TestDataRetrieval.WriteLog(Result, "GetCommentList"); - - Comments = Result[Comments_]; + + Comments = Result[Comments_]; CommentObject = Comments[Comments.UBound()]; - + ResultArray.Add(CommentObject); - - For Each Result In ResultArray Do + + For Each Result In ResultArray Do OPI_TestDataRetrieval.ExpectsThat(Result[Content_]).Равно(Comment); OPI_TestDataRetrieval.ExpectsThat(Result[Kind_]).Равно("drive#comment"); EndDo; - - Result = OPI_GoogleDrive.DeleteComment(Token, Identifier, CommentID); - + + Result = OPI_GoogleDrive.DeleteComment(Token, Identifier, CommentID); + OPI_TestDataRetrieval.WriteLog(Result, "DeleteComment"); - + OPI_TestDataRetrieval.ExpectsThat(ValueIsFilled(Result)).Равно(False); OPI_GoogleDrive.DeleteObject(Token, Identifier); - + EndProcedure Procedure GD_CreateCatalog() Export - - Name_ = "name"; - Name = "TestFolder"; - Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); + + Name_ = "name"; + Name = "TestFolder"; + Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); Directory = OPI_TestDataRetrieval.GetParameter("GD_Catalog"); - + ResultArray = New Array; - + ResultArray.Add(OPI_GoogleDrive.CreateFolder(Token, Name)); ResultArray.Add(OPI_GoogleDrive.CreateFolder(Token, Name, Directory)); - + For Each Result In ResultArray Do - + OPI_TestDataRetrieval.WriteLog(Result, "CreateFolder"); - + CatalogID = Result["id"]; - + OPI_TestDataRetrieval.ExpectsThat(Result[Name_]).Равно(Name); - + OPI_GoogleDrive.DeleteObject(Token, CatalogID); - + EndDo; EndProcedure @@ -1508,93 +1508,93 @@ EndProcedure #Region GoogleSheets Procedure GT_CreateTable() Export - + Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); - Name = "TestTable"; - + Name = "TestTable"; + SheetArray = New Array; SheetArray.Add("Sheet1"); SheetArray.Add("Sheet2"); - + Result = OPI_GoogleSheets.CreateSpreadsheet(Token, Name, SheetArray); - + OPI_TestDataRetrieval.WriteLog(Result, "CreateSpreadsheet"); - + OPI_TestDataRetrieval.ExpectsThat(Result["properties"]["title"]).Равно(Name); For N = 0 To SheetArray.UBound() Do - + SheetName = Result["sheets"][N]["properties"]["title"]; OPI_TestDataRetrieval.ExpectsThat(SheetName).Равно(SheetArray[N]); - Sheet = Result["sheets"][N]["properties"]["sheetId"]; - Sheet = OPI_Tools.NumberToString(Sheet); - + Sheet = Result["sheets"][N]["properties"]["sheetId"]; + Sheet = OPI_Tools.NumberToString(Sheet); + EndDo; - + Spreadsheet = Result["spreadsheetId"]; - + OPI_TestDataRetrieval.WriteParameter("GS_Spreadsheet", Spreadsheet); - OPI_TestDataRetrieval.WriteParameter("GS_Sheet" , Sheet); - - Name = "Test table (new.)"; + OPI_TestDataRetrieval.WriteParameter("GS_Sheet" , Sheet); + + Name = "Test table (new.)"; Result = OPI_GoogleSheets.CreateSpreadsheet(Token, Name, SheetArray); - + OPI_TestDataRetrieval.WriteLog(Result, "CopySheet (new.)"); - + Spreadsheet2 = Result["spreadsheetId"]; - + Result = OPI_GoogleSheets.CopySheet(Token, Spreadsheet, Spreadsheet2, Sheet); - + OPI_TestDataRetrieval.WriteLog(Result, "CopySheet"); OPI_TestDataRetrieval.ExpectsThat(Result["title"]).Заполнено(); - + Name = "TestSheet"; - + Result = OPI_GoogleSheets.AddSheet(Token, Spreadsheet, Name); - + OPI_TestDataRetrieval.WriteLog(Result, "AddSheet"); NewSheet = Result["replies"][0]["addSheet"]["properties"]["sheetId"]; NewSheet = OPI_Tools.NumberToString(NewSheet); - - OPI_TestDataRetrieval.ExpectsThat(Result["spreadsheetId"]).Равно(Spreadsheet); + + OPI_TestDataRetrieval.ExpectsThat(Result["spreadsheetId"]).Равно(Spreadsheet); Result = OPI_GoogleSheets.DeleteSheet(Token, Spreadsheet, NewSheet); - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteSheet"); - + OPI_TestDataRetrieval.ExpectsThat(Result["spreadsheetId"]).Равно(Spreadsheet); - + Name = "Test table (changed.)"; - + Result = OPI_GoogleSheets.EditSpreadsheetTitle(Token, Spreadsheet, Name); - + OPI_TestDataRetrieval.WriteLog(Result, "EditSpreadsheetTitle"); - + OPI_TestDataRetrieval.ExpectsThat(Result["spreadsheetId"]).Равно(Spreadsheet); - + EndProcedure Procedure GT_GetTable() Export - - Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); Spreadsheet = OPI_TestDataRetrieval.GetParameter("GS_Spreadsheet"); - Name = "Test table (changed.)"; + Name = "Test table (changed.)"; Result = OPI_GoogleSheets.GetSpreadsheet(Token, Spreadsheet); - + OPI_TestDataRetrieval.WriteLog(Result, "GetTable"); - + OPI_TestDataRetrieval.ExpectsThat(Result["properties"]["title"]).Равно(Name); EndProcedure Procedure GT_FillClearCells() Export - - Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); Spreadsheet = OPI_TestDataRetrieval.GetParameter("GS_Spreadsheet"); - Sheet = "Sheet2"; + Sheet = "Sheet2"; CellStructure = New Map; CellStructure.Insert("A1", "ThisIsA1"); @@ -1605,41 +1605,41 @@ Procedure GT_FillClearCells() Export CellStructure.Insert("A4", "ThisIsA4"); CellStructure.Insert("B1", "ThisIsB1"); CellStructure.Insert("B4", "ThisIsB4"); - + CellsArray = New Array; CellsArray.Add("B2"); CellsArray.Add("A3"); CellsArray.Add("B4"); Result = OPI_GoogleSheets.SetCellValues(Token, Spreadsheet, CellStructure, Sheet); - + OPI_TestDataRetrieval.WriteLog(Result, "SetCellValues"); - + OPI_TestDataRetrieval.ExpectsThat(Result["spreadsheetId"]).Равно(Spreadsheet); OPI_TestDataRetrieval.ExpectsThat(Result["totalUpdatedCells"]).Равно(CellStructure.Count()); - + Result = OPI_GoogleSheets.GetCellValues(Token, Spreadsheet, CellsArray, Sheet); - + OPI_TestDataRetrieval.WriteLog(Result, "GetCellValues"); - + OPI_TestDataRetrieval.ExpectsThat(Result["spreadsheetId"]).Равно(Spreadsheet); OPI_TestDataRetrieval.ExpectsThat(Result["valueRanges"].Count()).Равно(CellsArray.Count()); - + Result = OPI_GoogleSheets.GetCellValues(Token, Spreadsheet, , Sheet); - + OPI_TestDataRetrieval.WriteLog(Result, "GetCellValues"); - + OPI_TestDataRetrieval.ExpectsThat(Result["spreadsheetId"]).Равно(Spreadsheet); - + CellsArray = New Array; CellsArray.Add("B2"); CellsArray.Add("A3"); CellsArray.Add("B4"); Result = OPI_GoogleSheets.ClearCells(Token, Spreadsheet, CellsArray, Sheet); - + OPI_TestDataRetrieval.WriteLog(Result, "ClearCells"); - + OPI_TestDataRetrieval.ExpectsThat(Result["spreadsheetId"]).Равно(Spreadsheet); OPI_TestDataRetrieval.ExpectsThat(Result["clearedRanges"].Count()).Равно(CellsArray.Count()); @@ -1650,154 +1650,154 @@ EndProcedure #Region Twitter Procedure Twitter_GetAuthorizationLink() Export - + Parameters = GetTwitterParameters(); - Result = OPI_Twitter.GetAuthorizationLink(Parameters); - + Result = OPI_Twitter.GetAuthorizationLink(Parameters); + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("String").Заполнено(); - + OPI_TestDataRetrieval.WriteParameter("Twitter_URL", Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Twitter_UpdateToken() Export - + Parameters = GetTwitterParameters(); - Result = OPI_Twitter.RefreshToken(Parameters); - + Result = OPI_Twitter.RefreshToken(Parameters); + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["access_token"]).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["refresh_token"]).Заполнено(); - + Refresh = Result["refresh_token"]; - Token = Result["access_token"]; - - If ValueIsFilled(Refresh) And Not Refresh = "null" Then + Token = Result["access_token"]; + + If ValueIsFilled(Refresh) And Not Refresh = "null" Then OPI_TestDataRetrieval.WriteParameter("Twitter_Refresh", Refresh); EndIf; - + If ValueIsFilled(Token) And Not Token = "null" Then OPI_TestDataRetrieval.WriteParameter("Twitter_Token" , Token); EndIf; - + OPI_Tools.Pause(5); - + EndProcedure Procedure Twitter_CreateTextTweet() Export - + Parameters = GetTwitterParameters(); - Text = "TestTweet" + String(New UUID); - + Text = "TestTweet" + String(New UUID); + Result = OPI_Twitter.CreateTextTweet(Text, Parameters); - + OPI_TestDataRetrieval.WriteLog(Result, "CreateTextTweet"); - + Check_TwitterText(Result, Text); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Twitter_CreateTweetWithImage() Export - + Parameters = GetTwitterParameters(); - Text = "TestTweet" + String(New UUID); - Image = OPI_TestDataRetrieval.GetBinary("Picture"); - TFN = GetTempFileName("png"); + Text = "TestTweet" + String(New UUID); + Image = OPI_TestDataRetrieval.GetBinary("Picture"); + TFN = GetTempFileName("png"); Image.Write(TFN); - - Result = OPI_Twitter.CreateImageTweet(Text, Image, Parameters); - + + Result = OPI_Twitter.CreateImageTweet(Text, Image, Parameters); + OPI_TestDataRetrieval.WriteLog(Result, "CreateImageTweet"); - - Check_TwitterText(Result, Text); - - Text = "TestTweet" + String(New UUID); - Result = OPI_Twitter.CreateImageTweet(Text, TFN, Parameters); - - OPI_TestDataRetrieval.WriteLog(Result, "CreateImageTweet"); - + Check_TwitterText(Result, Text); - + + Text = "TestTweet" + String(New UUID); + Result = OPI_Twitter.CreateImageTweet(Text, TFN, Parameters); + + OPI_TestDataRetrieval.WriteLog(Result, "CreateImageTweet"); + + Check_TwitterText(Result, Text); + DeleteFiles(TFN); - + OPI_Tools.Pause(20); - + EndProcedure Procedure Twitter_CreateTweetWithVideo() Export - + Parameters = GetTwitterParameters(); - Text = "TestTweet" + String(New UUID); - Video = OPI_TestDataRetrieval.GetBinary("Video"); - TFN = GetTempFileName("mp4"); + Text = "TestTweet" + String(New UUID); + Video = OPI_TestDataRetrieval.GetBinary("Video"); + TFN = GetTempFileName("mp4"); Video.Write(TFN); - - Result = OPI_Twitter.CreateVideoTweet(Text, Video, Parameters); - + + Result = OPI_Twitter.CreateVideoTweet(Text, Video, Parameters); + OPI_TestDataRetrieval.WriteLog(Result, "CreateVideoTweet"); - - Check_TwitterText(Result, Text); - - Text = "TestTweet" + String(New UUID); - Result = OPI_Twitter.CreateVideoTweet(Text, TFN, Parameters); - - OPI_TestDataRetrieval.WriteLog(Result, "CreateVideoTweet"); - + Check_TwitterText(Result, Text); - + + Text = "TestTweet" + String(New UUID); + Result = OPI_Twitter.CreateVideoTweet(Text, TFN, Parameters); + + OPI_TestDataRetrieval.WriteLog(Result, "CreateVideoTweet"); + + Check_TwitterText(Result, Text); + DeleteFiles(TFN); - + OPI_Tools.Pause(20); - + EndProcedure Procedure Twitter_CreateTweetWithGif() Export - + Parameters = GetTwitterParameters(); - Text = "TestTweet" + String(New UUID); - GIF = OPI_TestDataRetrieval.GetBinary("GIF"); - TFN = GetTempFileName("gif"); + Text = "TestTweet" + String(New UUID); + GIF = OPI_TestDataRetrieval.GetBinary("GIF"); + TFN = GetTempFileName("gif"); GIF.Write(TFN); - - Result = OPI_Twitter.CreateGifTweet(Text, GIF, Parameters); - + + Result = OPI_Twitter.CreateGifTweet(Text, GIF, Parameters); + OPI_TestDataRetrieval.WriteLog(Result, "CreateGifTweet"); - - Check_TwitterText(Result, Text); - - Text = "TestTweet" + String(New UUID); - Result = OPI_Twitter.CreateGifTweet(Text, TFN, Parameters); - - OPI_TestDataRetrieval.WriteLog(Result, "CreateGifTweet"); - + Check_TwitterText(Result, Text); - + + Text = "TestTweet" + String(New UUID); + Result = OPI_Twitter.CreateGifTweet(Text, TFN, Parameters); + + OPI_TestDataRetrieval.WriteLog(Result, "CreateGifTweet"); + + Check_TwitterText(Result, Text); + DeleteFiles(TFN); - + OPI_Tools.Pause(20); - + EndProcedure Procedure Twitter_CreateTweetWithPoll() Export - - Parameters = GetTwitterParameters(); - Text = "TestTweet" + String(New UUID); + + Parameters = GetTwitterParameters(); + Text = "TestTweet" + String(New UUID); AnswersArray = New Array; AnswersArray.Add("Option 1"); AnswersArray.Add("Option 2"); - + Result = OPI_Twitter.CreatePollTweet(Text, AnswersArray, 60, Parameters); - + OPI_TestDataRetrieval.WriteLog(Result, "CreatePollTweet"); - + Check_TwitterText(Result, Text); - + OPI_Tools.Pause(20); - + EndProcedure #EndRegion @@ -1805,203 +1805,203 @@ EndProcedure #Region Notion Procedure Notion_CreatePage() Export - - Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); Parent = OPI_TestDataRetrieval.GetParameter("Notion_Parent"); - Title = "TestTitle"; - + Title = "TestTitle"; + Result = OPI_Notion.CreatePage(Token, Parent, Title); - + OPI_TestDataRetrieval.WriteLog(Result, "CreatePage"); - + Check_NotionObject(Result); EndProcedure Procedure Notion_CreateEditDatabase() Export - - Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); Parent = OPI_TestDataRetrieval.GetParameter("Notion_Parent"); - Title = "TestTitle"; - + Title = "TestTitle"; + Properties = New Map; - Properties.Insert("Name" , "title"); - Properties.Insert("Description" , "rich_text"); - Properties.Insert("Number" , "number"); - Properties.Insert("Status" , "status"); + Properties.Insert("Name" , "title"); + Properties.Insert("Description" , "rich_text"); + Properties.Insert("Number" , "number"); + Properties.Insert("Status" , "status"); Properties.Insert("CreationDate" , "date"); - Properties.Insert("Image" , "files"); - Properties.Insert("Active" , "checkbox"); - Properties.Insert("Website" , "url"); - Properties.Insert("Email" , "email"); - Properties.Insert("Phone" , "phone_number"); - Properties.Insert("User" , "people"); - + Properties.Insert("Image" , "files"); + Properties.Insert("Active" , "checkbox"); + Properties.Insert("Website" , "url"); + Properties.Insert("Email" , "email"); + Properties.Insert("Phone" , "phone_number"); + Properties.Insert("User" , "people"); + ValueSelection = New Map; - ValueSelection.Insert("New", "green"); + ValueSelection.Insert("New" , "green"); ValueSelection.Insert("InProgress", "yellow"); - ValueSelection.Insert("Remote", "red"); + ValueSelection.Insert("Remote" , "red"); Properties.Insert("Status", ValueSelection); - - Result = OPI_Notion.CreateDatabase(Token, Parent, Title, Properties); - + + Result = OPI_Notion.CreateDatabase(Token, Parent, Title, Properties); + OPI_TestDataRetrieval.WriteLog(Result, "CreateDatabase"); - + Check_NotionObject(Result, "database"); - - Base = Result["id"]; - Title = "TestTitle"; + + Base = Result["id"]; + Title = "TestTitle"; Description = "TestDescription"; - + Properties = New Map; Properties.Insert("Email", "rich_text"); // Type fields "Email" will changed with email to text Properties.Insert("Website"); // Field "Website" will deleted - + Result = OPI_Notion.EditDatabaseProperties(Token, Base, Properties, Title, Description); - + OPI_TestDataRetrieval.WriteLog(Result, "EditDatabaseProperties"); - + Check_NotionObject(Result, "database"); EndProcedure Procedure Notion_GetPageInfo() Export - + Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); - Page = OPI_TestDataRetrieval.GetParameter("Notion_Page"); - + Page = OPI_TestDataRetrieval.GetParameter("Notion_Page"); + Result = OPI_Notion.GetPage(Token, Page); - + OPI_TestDataRetrieval.WriteLog(Result, "GetPage"); - - Check_NotionObject(Result); - + + Check_NotionObject(Result); + EndProcedure Procedure Notion_GetDatabaseInfo() Export Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); - Base = OPI_TestDataRetrieval.GetParameter("Notion_Base"); - + Base = OPI_TestDataRetrieval.GetParameter("Notion_Base"); + Result = OPI_Notion.GetDatabase(Token, Base); - + OPI_TestDataRetrieval.WriteLog(Result, "GetDatabase"); - + Check_NotionObject(Result, "database"); - + EndProcedure Procedure Notion_CreatePageInDatabase() Export - + Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); - Base = OPI_TestDataRetrieval.GetParameter("Notion_Base"); - + Base = OPI_TestDataRetrieval.GetParameter("Notion_Base"); + Image = New Map; Image.Insert("Logo", OPI_TestDataRetrieval.GetParameter("Picture")); - + Properties = New Map; - Properties.Insert("Name" , "LLC Vector"); - Properties.Insert("Description" , "OurFirstClient"); - Properties.Insert("Number" , 1); - Properties.Insert("Status" , "Regular"); + Properties.Insert("Name" , "LLC Vector"); + Properties.Insert("Description" , "OurFirstClient"); + Properties.Insert("Number" , 1); + Properties.Insert("Status" , "Regular"); Properties.Insert("CreationDate" , OPI_Tools.GetCurrentDate()); - Properties.Insert("Image" , Image); - Properties.Insert("Active" , True); - Properties.Insert("Website" , "https://vector.ru"); - Properties.Insert("Email" , "mail@vector.ru"); - Properties.Insert("Phone" , "88005553535"); - Properties.Insert("Status" , "New"); - + Properties.Insert("Image" , Image); + Properties.Insert("Active" , True); + Properties.Insert("Website" , "https://vector.ru"); + Properties.Insert("Email" , "mail@vector.ru"); + Properties.Insert("Phone" , "88005553535"); + Properties.Insert("Status" , "New"); + Result = OPI_Notion.CreatePageInDatabase(Token, Base, Properties); - + OPI_TestDataRetrieval.WriteLog(Result, "CreatePageInDatabase"); - + Check_NotionObject(Result); - + Parent = StrReplace(Result["parent"]["database_id"], "-", ""); OPI_TestDataRetrieval.ExpectsThat(Parent).Равно(Base); - + EndProcedure Procedure Notion_EditPageProperties() Export - - Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); - Page = OPI_TestDataRetrieval.GetParameter("Notion_Page"); - Icon = OPI_TestDataRetrieval.GetParameter("Picture"); - Cover = OPI_TestDataRetrieval.GetParameter("Picture2"); + + Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); + Page = OPI_TestDataRetrieval.GetParameter("Notion_Page"); + Icon = OPI_TestDataRetrieval.GetParameter("Picture"); + Cover = OPI_TestDataRetrieval.GetParameter("Picture2"); Archive = False; - + Properties = New Map; Properties.Insert("Active" , False); - Properties.Insert("Email" , "vector@mail.ru"); - + Properties.Insert("Email" , "vector@mail.ru"); + Result = OPI_Notion.EditPageProperties(Token , Page , Properties , Icon , Cover , Archive); - + OPI_TestDataRetrieval.WriteLog(Result, "EditPageProperties"); - + Check_NotionObject(Result); - + EndProcedure Procedure Notion_CreateDeleteBlock() Export - - Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); Parent = OPI_TestDataRetrieval.GetParameter("Notion_Parent"); - Block = OPI_TestDataRetrieval.GetParameter("Notion_Block"); - - Result = OPI_Notion.ReturnBlock(Token, Block); - + Block = OPI_TestDataRetrieval.GetParameter("Notion_Block"); + + Result = OPI_Notion.ReturnBlock(Token, Block); + OPI_TestDataRetrieval.WriteLog(Result, "ReturnBlock"); - + Check_NotionObject(Result, "block"); - + Result = OPI_Notion.CreateBlock(Token, Parent, Result); - + OPI_TestDataRetrieval.WriteLog(Result, "CreateBlock"); - + Check_NotionObject(Result, "list"); - + Block = Result["results"][0]["id"]; - Result = OPI_Notion.ReturnChildBlocks(Token, Block); - + Result = OPI_Notion.ReturnChildBlocks(Token, Block); + OPI_TestDataRetrieval.WriteLog(Result, "ReturnChildBlocks"); - + Check_NotionObject(Result, "list"); - + Result = OPI_Notion.DeleteBlock(Token, Block); - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteBlock"); - + Check_NotionObject(Result, "block"); - + EndProcedure Procedure Notion_GetUsers() Export - - Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); Result = OPI_Notion.UserList(Token); - + OPI_TestDataRetrieval.WriteLog(Result, "UserList"); - + Check_NotionObject(Result, "list"); - + EndProcedure Procedure Notion_GetUserData() Export - - Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); - User = OPI_TestDataRetrieval.GetParameter("Notion_User"); + + Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); + User = OPI_TestDataRetrieval.GetParameter("Notion_User"); Result = OPI_Notion.GetUserData(Token, User); - + OPI_TestDataRetrieval.WriteLog(Result, "GetUserData"); - + Check_NotionObject(Result, "user"); - + EndProcedure #EndRegion @@ -2009,160 +2009,160 @@ EndProcedure #Region Slack Procedure Slack_GetBotInfo() Export - - Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); Result = OPI_Slack.GetBotInformation(Token); - + OPI_TestDataRetrieval.WriteLog(Result, "GetBotInformation"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["bot_id"]).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["user_id"]).Заполнено(); - + EndProcedure Procedure Slack_GetUserList() Export - - Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); Result = OPI_Slack.GetUserList(Token); - + OPI_TestDataRetrieval.WriteLog(Result, "GetUserList"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["members"]).ИмеетТип("Array"); - + EndProcedure Procedure Slack_GetRegionList() Export - - Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); Result = OPI_Slack.GetWorkspaceList(Token); - + OPI_TestDataRetrieval.WriteLog(Result, "GetWorkspaceList"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["teams"]).ИмеетТип("Array"); - + EndProcedure Procedure Slack_SendDeleteMessage() Export - Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); + Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); Channel = OPI_TestDataRetrieval.GetParameter("Slack_Channel"); - Text = "TestMessage1"; - Text2 = "TestMessage2"; - Tags = New Array; - Image = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/Media/logo.png?v1"; - + Text = "TestMessage1"; + Text2 = "TestMessage2"; + Tags = New Array; + Image = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/Media/logo.png?v1"; + Result = OPI_Slack.SendMessage(Token, Channel, Text); - + OPI_TestDataRetrieval.WriteLog(Result, "SendMessage"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["channel"]).Равно(Channel); OPI_TestDataRetrieval.ExpectsThat(Result["ts"]).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["message"]["text"]).Равно(Text); - + Timestamp = Result["ts"]; - + Result = OPI_Slack.EditMessage(Token, Channel, Timestamp, Text2); - + OPI_TestDataRetrieval.WriteLog(Result, "EditMessage"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["channel"]).Равно(Channel); OPI_TestDataRetrieval.ExpectsThat(Result["ts"]).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["message"]["text"]).Равно(Text2); - + Result = OPI_Slack.GetMessageReplyList(Token, Channel, Timestamp); - + OPI_TestDataRetrieval.WriteLog(Result, "GetMessageReplyList"); - + OPI_TestDataRetrieval.ExpectsThat(Result["messages"]).ИмеетТип("Array"); - + Result = OPI_Slack.GetMessageLink(Token, Channel, Timestamp); - + OPI_TestDataRetrieval.WriteLog(Result, "GetMessageLink"); - + OPI_TestDataRetrieval.ExpectsThat(Result["channel"]).Равно(Channel); OPI_TestDataRetrieval.ExpectsThat(Result["permalink"]).Заполнено(); - + Check_SlackOk(Result); - + Tags.Add(Timestamp); - + BlockArray = New Array; - Block = OPI_Slack.GenerateImageBlock(Image, "Yo"); + Block = OPI_Slack.GenerateImageBlock(Image, "Yo"); BlockArray.Add(Block); - + Result = OPI_Slack.SendMessage(Token, Channel, Text, , BlockArray); - + OPI_TestDataRetrieval.WriteLog(Result, "SendMessage (picture)"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["channel"]).Равно(Channel); OPI_TestDataRetrieval.ExpectsThat(Result["ts"]).Заполнено(); - + Tags.Add(Result["ts"]); - - Block = OPI_Slack.GenerateImageBlock(Image, "Yo"); + + Block = OPI_Slack.GenerateImageBlock(Image, "Yo"); JSONBlock = OPI_Tools.JSONString(Block); - + TFN = GetTempFileName("json"); - + TextDocument = New TextDocument(); TextDocument.SetText(JSONBlock); TextDocument.Write(TFN); - + Result = OPI_Slack.SendMessage(Token, Channel, Text, , TFN); - + OPI_TestDataRetrieval.WriteLog(Result, "SendMessage (json)"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["channel"]).Равно(Channel); OPI_TestDataRetrieval.ExpectsThat(Result["ts"]).Заполнено(); - + Tags.Add(Result["ts"]); - + Blocks = "['" + TFN + "','" + TFN + "']"; Result = OPI_Slack.SendMessage(Token, Channel, Text, , Blocks); - + OPI_TestDataRetrieval.WriteLog(Result, "SendMessage (json array)"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["channel"]).Равно(Channel); OPI_TestDataRetrieval.ExpectsThat(Result["ts"]).Заполнено(); - + Tags.Add(Result["ts"]); DeleteFiles(TFN); - + For Each Timestamp In Tags Do - + Result = OPI_Slack.DeleteMessage(Token, Channel, Timestamp); - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteMessage"); Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["channel"]).Равно(Channel); OPI_TestDataRetrieval.ExpectsThat(Result["ts"]).Заполнено(); - + EndDo; - - Hour = 3600; - Day = 24; + + Hour = 3600; + Day = 24; Sending = OPI_Tools.GetCurrentDate() + (Day * Hour); - Result = OPI_Slack.SendMessage(Token, Channel, Text, Sending); - + Result = OPI_Slack.SendMessage(Token, Channel, Text, Sending); + OPI_TestDataRetrieval.WriteLog(Result, "SendMessage (scheduled)"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["channel"]).Равно(Channel); OPI_TestDataRetrieval.ExpectsThat(Result["scheduled_message_id"]).Заполнено(); - + Timestamp = Result["scheduled_message_id"]; - Result = OPI_Slack.DeleteMessage(Token, Channel, Timestamp, True); - + Result = OPI_Slack.DeleteMessage(Token, Channel, Timestamp, True); + OPI_TestDataRetrieval.WriteLog(Result, "DeleteMessage"); Check_SlackOk(Result); @@ -2170,51 +2170,51 @@ Procedure Slack_SendDeleteMessage() Export EndProcedure Procedure Slack_SendDeleteEphemeral() Export - - Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); Channel = OPI_TestDataRetrieval.GetParameter("Slack_Channel"); - User = OPI_TestDataRetrieval.GetParameter("Slack_User"); - Image = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/Media/logo.png?v1"; - Text = "TestMessage1"; - - Block = OPI_Slack.GenerateImageBlock(Image, "Yo"); + User = OPI_TestDataRetrieval.GetParameter("Slack_User"); + Image = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/Media/logo.png?v1"; + Text = "TestMessage1"; + + Block = OPI_Slack.GenerateImageBlock(Image, "Yo"); Result = OPI_Slack.SendEphemeralMessage(Token, Channel, Text, User, Block); - + OPI_TestDataRetrieval.WriteLog(Result, "SendMessage"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["message_ts"]).Заполнено(); - + EndProcedure Procedure Slack_GetScheduledMessages() Export - - Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); Channel = OPI_TestDataRetrieval.GetParameter("Slack_Channel"); - + Result = OPI_Slack.GetDelayedMessageList(Token, Channel); - + OPI_TestDataRetrieval.WriteLog(Result, "GetDelayedMessageList"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["scheduled_messages"]).ИмеетТип("Array"); - + EndProcedure Procedure Slack_CreateArchiveChannel() Export - - Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); - User = OPI_TestDataRetrieval.GetParameter("Slack_User"); - Name = "testconv" + String(New UUID); - Topic = "TestTopic"; + + Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); + User = OPI_TestDataRetrieval.GetParameter("Slack_User"); + Name = "testconv" + String(New UUID); + Topic = "TestTopic"; Purpose = "TestGoal"; - + #Region CreateChannel Result = OPI_Slack.CreateChannel(Token, Name); - + OPI_TestDataRetrieval.WriteLog(Result, "CreateChannel"); - - Data = Result["channel"]; + + Data = Result["channel"]; Channel = Data["id"]; Check_SlackOk(Result); @@ -2223,154 +2223,154 @@ Procedure Slack_CreateArchiveChannel() Export #Region SetChannelTopic Result = OPI_Slack.SetChannelTopic(Token, Channel, Topic); - + OPI_TestDataRetrieval.WriteLog(Result, "SetChannelTopic"); - - Data = Result["channel"]; + + Data = Result["channel"]; Channel = Data["id"]; Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Data["name"]).Равно(Name); OPI_TestDataRetrieval.ExpectsThat(Data["topic"]["value"]).Равно(Topic); #EndRegion - + #Region SetChannelGoal Result = OPI_Slack.SetChannelGoal(Token, Channel, Purpose); - + OPI_TestDataRetrieval.WriteLog(Result, "SetChannelGoal"); - + Check_SlackOk(Result); #EndRegion - + #Region GetChannel Result = OPI_Slack.GetChannel(Token, Channel); - + OPI_TestDataRetrieval.WriteLog(Result, "GetChannel"); - - Data = Result["channel"]; + + Data = Result["channel"]; Channel = Data["id"]; Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Data["name"]).Равно(Name); #EndRegion - + #Region InviteUsersToChannel Result = OPI_Slack.InviteUsersToChannel(Token, Channel, User); - + OPI_TestDataRetrieval.WriteLog(Result, "InviteUsersToChannel"); - - Data = Result["channel"]; + + Data = Result["channel"]; Channel = Data["id"]; Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Data["name"]).Равно(Name); #EndRegion - + #Region KickUserFromChannel Result = OPI_Slack.KickUserFromChannel(Token, Channel, User); - + OPI_TestDataRetrieval.WriteLog(Result, "KickUserFromChannel"); - + Check_SlackOk(Result); #EndRegion - + #Region GetChannelHistory Result = OPI_Slack.GetChannelHistory(Token, Channel); - + OPI_TestDataRetrieval.WriteLog(Result, "GetChannelHistory"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["messages"]).ИмеетТип("Array"); #EndRegion - + #Region GetChannelUserList Result = OPI_Slack.GetChannelUserList(Token, Channel); - + OPI_TestDataRetrieval.WriteLog(Result, "GetChannelUserList"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["members"]).ИмеетТип("Array"); #EndRegion #Region LeaveChannel Result = OPI_Slack.LeaveChannel(Token, Channel); - + OPI_TestDataRetrieval.WriteLog(Result, "LeaveChannel"); - + Check_SlackOk(Result); #EndRegion - + #Region JoinChannel Result = OPI_Slack.JoinChannel(Token, Channel); - + OPI_TestDataRetrieval.WriteLog(Result, "JoinChannel"); - - Data = Result["channel"]; + + Data = Result["channel"]; Channel = Data["id"]; Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Data["name"]).Равно(Name); #EndRegion - + #Region RenameChannel NewName = "testconv" + String(New UUID); - Result = OPI_Slack.RenameChannel(Token, Channel, NewName); - + Result = OPI_Slack.RenameChannel(Token, Channel, NewName); + OPI_TestDataRetrieval.WriteLog(Result, "RenameChannel"); - - Data = Result["channel"]; + + Data = Result["channel"]; Channel = Data["id"]; Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Data["name"]).Равно(NewName); #EndRegion - + #Region ArchiveChannel Result = OPI_Slack.ArchiveChannel(Token, Channel); - + OPI_TestDataRetrieval.WriteLog(Result, "ArchiveChannel"); - + Check_SlackOk(Result); #EndRegion - + EndProcedure Procedure Slack_GetChannelList() Export - + Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); - + Result = OPI_Slack.GetChannelList(Token); - + OPI_TestDataRetrieval.WriteLog(Result, "GetChannelList"); Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["channels"]).ИмеетТип("Array"); - + EndProcedure Procedure Slack_OpenCloseDialog() Export - + Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); - User = OPI_TestDataRetrieval.GetParameter("Slack_User"); - Text = "Yo, dude"; - + User = OPI_TestDataRetrieval.GetParameter("Slack_User"); + Text = "Yo, dude"; + Result = OPI_Slack.OpenDialog(Token, User); - + OPI_TestDataRetrieval.WriteLog(Result, "OpenDialog"); Dialog = Result["channel"]["id"]; Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["channel"]).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Dialog).Заполнено(); - + Result = OPI_Slack.SendMessage(Token, Dialog, Text); - + OPI_TestDataRetrieval.WriteLog(Result, "SendMessage"); - + Check_SlackOk(Result); Result = OPI_Slack.CloseDialog(Token, Dialog); - + OPI_TestDataRetrieval.WriteLog(Result, "CloseDialog"); Check_SlackOk(Result); @@ -2378,12 +2378,12 @@ Procedure Slack_OpenCloseDialog() Export EndProcedure Procedure Slack_GetFileList() Export - - Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); Channel = OPI_TestDataRetrieval.GetParameter("Slack_Channel"); - + Result = OPI_Slack.GetFilesList(Token, Channel); - + OPI_TestDataRetrieval.WriteLog(Result, "GetFilesList"); Check_SlackOk(Result); @@ -2392,113 +2392,113 @@ Procedure Slack_GetFileList() Export EndProcedure Procedure Slack_UploadDeleteFile() Export - - Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); - File = OPI_TestDataRetrieval.GetBinary("Document"); - Channel = OPI_TestDataRetrieval.GetParameter("Slack_Channel"); + + Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); + File = OPI_TestDataRetrieval.GetBinary("Document"); + Channel = OPI_TestDataRetrieval.GetParameter("Slack_Channel"); ArrayOfFiles = New Array; - FileName = "megadoc.docx"; - Title = "NewFile"; - + FileName = "megadoc.docx"; + Title = "NewFile"; + Result = OPI_Slack.UploadFile(Token, File, FileName, Title); - + OPI_TestDataRetrieval.WriteLog(Result, "UploadFile"); UploadedFile = Result["files"][0]; ArrayOfFiles.Add(UploadedFile["id"]); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(UploadedFile["name"]).Равно(FileName); - + Result = OPI_Slack.UploadFile(Token, File, FileName, Title, Channel); - + OPI_TestDataRetrieval.WriteLog(Result, "UploadFile (to channel)"); UploadedFile = Result["files"][0]; ArrayOfFiles.Add(UploadedFile["id"]); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(UploadedFile["name"]).Равно(FileName); - + Result = OPI_Slack.GetFileData(Token, UploadedFile["id"]); - + OPI_TestDataRetrieval.WriteLog(Result, "GetFile"); - + UploadedFile = Result["file"]; - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(UploadedFile["name"]).Равно(FileName); - + For Each UploadedFile In ArrayOfFiles Do - + Result = OPI_Slack.DeleteFile(Token, UploadedFile); - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteFile"); - + Check_SlackOk(Result); - + EndDo; EndProcedure Procedure Slack_GetExternalFileList() Export - - Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); Channel = OPI_TestDataRetrieval.GetParameter("Slack_Channel"); - + Result = OPI_Slack.GetExternalFileList(Token); - + OPI_TestDataRetrieval.WriteLog(Result, "GetExternalFileList"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["files"]).ИмеетТип("Array"); - + Result = OPI_Slack.GetExternalFileList(Token, Channel); - + OPI_TestDataRetrieval.WriteLog(Result, "GetExternalFileList"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["files"]).ИмеетТип("Array"); - + EndProcedure Procedure Slack_UploadDeleteExternalFile() Export - - Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); - File = OPI_TestDataRetrieval.GetParameter("Document"); + + Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); + File = OPI_TestDataRetrieval.GetParameter("Document"); Channel = OPI_TestDataRetrieval.GetParameter("Slack_Channel"); - Title = "NewFile"; - + Title = "NewFile"; + Result = OPI_Slack.AddExternalFile(Token, File, Title); - + OPI_TestDataRetrieval.WriteLog(Result, "AddExternalFile"); - + UploadedFile = Result["file"]; - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(UploadedFile["title"]).Равно(Title); - + Result = OPI_Slack.GetExternalFile(Token, UploadedFile["id"]); - + OPI_TestDataRetrieval.WriteLog(Result, "GetExternalFile"); - + UploadedFile = Result["file"]; - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(UploadedFile["title"]).Равно(Title); - + Result = OPI_Slack.SendExternalFile(Token, UploadedFile["id"], Channel); - + OPI_TestDataRetrieval.WriteLog(Result, "SendExternalFile"); - + Check_SlackOk(Result); - + Result = OPI_Slack.DeleteExternalFile(Token, UploadedFile["id"]); - + OPI_TestDataRetrieval.WriteLog(Result, "SendExternalFile"); - + Check_SlackOk(Result); - + EndProcedure #EndRegion @@ -2506,222 +2506,222 @@ EndProcedure #Region Airtable Procedure AT_CreateDatabase() Export - - Token = OPI_TestDataRetrieval.GetParameter("Airtable_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Airtable_Token"); Region = OPI_TestDataRetrieval.GetParameter("Airtable_Workspace"); - Name = "TestDatabase"; - + Name = "TestDatabase"; + FieldArray = New Array; FieldArray.Add(OPI_Airtable.GetNumberField("Number")); FieldArray.Add(OPI_Airtable.GetStringField("String")); - + TableName = "TestTable"; - + TableMapping = New Map; TableMapping.Insert(TableName, FieldArray); - + Result = OPI_Airtable.CreateDatabase(Token, Region, Name, TableMapping); - + OPI_TestDataRetrieval.WriteLog(Result, "CreateDatabase"); - + OPI_TestDataRetrieval.ExpectsThat(Result["id"]).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["tables"][0]["name"]).Равно(TableName); - + Base = Result["id"]; OPI_TestDataRetrieval.WriteParameter("Airtable_Base", Base); - + Result = OPI_Airtable.GetDatabaseTables(Token, Base); - + OPI_TestDataRetrieval.WriteLog(Result, "GetDatabaseTables"); - + OPI_TestDataRetrieval.ExpectsThat(Result["tables"]).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["tables"]).ИмеетТип("Array"); Result = OPI_Airtable.GetListOfBases(Token); - + OPI_TestDataRetrieval.WriteLog(Result, "GetListOfBases"); - + OPI_TestDataRetrieval.ExpectsThat(Result["bases"]).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["bases"]).ИмеетТип("Array"); - + EndProcedure Procedure AT_CreateTable() Export - + Token = OPI_TestDataRetrieval.GetParameter("Airtable_Token"); - Base = OPI_TestDataRetrieval.GetParameter("Airtable_Base"); - + Base = OPI_TestDataRetrieval.GetParameter("Airtable_Base"); + FieldArray = New Array; - FieldArray.Add(OPI_Airtable.GetNumberField("Number")); + FieldArray.Add(OPI_Airtable.GetNumberField("Number")); OPI_TestDataRetrieval.WriteLog(FieldArray[0], "GetNumberField"); - + FieldArray.Add(OPI_Airtable.GetStringField("String")); OPI_TestDataRetrieval.WriteLog(FieldArray[1], "GetStringField"); - + FieldArray.Add(OPI_Airtable.GetAttachmentField("Attachment")); OPI_TestDataRetrieval.WriteLog(FieldArray[2], "GetAttachmentField"); - + FieldArray.Add(OPI_Airtable.GetCheckboxField("Checkbox")); OPI_TestDataRetrieval.WriteLog(FieldArray[3], "GetCheckboxField"); - + FieldArray.Add(OPI_Airtable.GetDateField("Date")); OPI_TestDataRetrieval.WriteLog(FieldArray[4], "GetDateField"); - + FieldArray.Add(OPI_Airtable.GetPhoneField("Phone")); OPI_TestDataRetrieval.WriteLog(FieldArray[5], "GetPhoneField"); - + FieldArray.Add(OPI_Airtable.GetEmailField("Email")); - OPI_TestDataRetrieval.WriteLog(FieldArray[6], "GetEmailField"); - + OPI_TestDataRetrieval.WriteLog(FieldArray[6], "GetEmailField"); + FieldArray.Add(OPI_Airtable.GetLinkField("Link")); - OPI_TestDataRetrieval.WriteLog(FieldArray[7], "GetLinkField"); - - TableName = "TestTable2"; + OPI_TestDataRetrieval.WriteLog(FieldArray[7], "GetLinkField"); + + TableName = "TestTable2"; Description = "NewTable"; - + Result = OPI_Airtable.CreateTable(Token, Base, TableName, FieldArray, Description); - + OPI_TestDataRetrieval.WriteLog(Result, "CreateTable"); - + OPI_TestDataRetrieval.ExpectsThat(Result["name"]).Равно(TableName); OPI_TestDataRetrieval.ExpectsThat(Result["description"]).Равно(Description); - - Table = Result["id"]; - TableName = "Test table 2 (change.)"; + + Table = Result["id"]; + TableName = "Test table 2 (change.)"; Description = "New table (change.)"; - + OPI_TestDataRetrieval.WriteParameter("Airtable_Table", Table); - + Result = OPI_Airtable.ModifyTable(Token, Base, Table, TableName, Description); - + OPI_TestDataRetrieval.WriteLog(Result, "ModifyTable"); - + OPI_TestDataRetrieval.ExpectsThat(Result["name"]).Равно(TableName); OPI_TestDataRetrieval.ExpectsThat(Result["description"]).Равно(Description); EndProcedure Procedure AT_CreateField() Export - + Token = OPI_TestDataRetrieval.GetParameter("Airtable_Token"); - Base = OPI_TestDataRetrieval.GetParameter("Airtable_Base"); + Base = OPI_TestDataRetrieval.GetParameter("Airtable_Base"); Table = OPI_TestDataRetrieval.GetParameter("Airtable_Table"); - Name = String(New UUID); - + Name = String(New UUID); + Field = OPI_Airtable.GetNumberField(Name); - + Result = OPI_Airtable.CreateField(Token, Base, Table, Field); - + OPI_TestDataRetrieval.WriteLog(Result, "CreateField"); - + OPI_TestDataRetrieval.ExpectsThat(Result["name"]).Равно(Name); - - Field = Result["id"]; - Name = Name + "(change.)"; + + Field = Result["id"]; + Name = Name + "(change.)"; Description = "New description"; - + Result = OPI_Airtable.ModifyField(Token, Base, Table, Field, Name, Description); - + OPI_TestDataRetrieval.WriteLog(Result, "ModifyField"); - + OPI_TestDataRetrieval.ExpectsThat(Result["name"]).Равно(Name); OPI_TestDataRetrieval.ExpectsThat(Result["description"]).Равно(Description); - + EndProcedure Procedure AT_CreateDeleteRecords() Export Token = OPI_TestDataRetrieval.GetParameter("Airtable_Token"); - Base = OPI_TestDataRetrieval.GetParameter("Airtable_Base"); + Base = OPI_TestDataRetrieval.GetParameter("Airtable_Base"); Table = OPI_TestDataRetrieval.GetParameter("Airtable_Table"); - - Numeric = 10; + + Numeric = 10; StringType = "Hello"; - + RowDescription1 = New Structure("Number,String", Numeric, StringType); RowDescription2 = New Structure("Number,String", Numeric, StringType); - - ArrayOfDeletions = New Array; + + ArrayOfDeletions = New Array; ArrayOfDescriptions = New Array; ArrayOfDescriptions.Add(RowDescription1); ArrayOfDescriptions.Add(RowDescription2); - + Result = OPI_Airtable.CreatePosts(Token, Base, Table, ArrayOfDescriptions); OPI_TestDataRetrieval.WriteLog(Result, "CreatePosts"); - + OPI_TestDataRetrieval.ExpectsThat(Result["records"]).ИмеетТип("Array"); OPI_TestDataRetrieval.ExpectsThat(Result["records"].Count()).Равно(2); - + For Each Record In Result["records"] Do ArrayOfDeletions.Add(Record["id"]); EndDo; - + Result = OPI_Airtable.CreatePosts(Token, Base, Table, RowDescription1); - + OPI_TestDataRetrieval.WriteLog(Result, "CreateRecords (one)"); - + SingleRecord = Result["id"]; OPI_TestDataRetrieval.ExpectsThat(SingleRecord).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["createdTime"]).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["fields"]["Number"]).Равно(Numeric); OPI_TestDataRetrieval.ExpectsThat(TrimAll(Result["fields"]["String"])).Равно(StringType); - + Result = OPI_Airtable.GetRecord(Token, Base, Table, SingleRecord); - + OPI_TestDataRetrieval.WriteLog(Result, "GetRecord"); - + OPI_TestDataRetrieval.ExpectsThat(Result["id"]).Равно(SingleRecord); - - Text = "TestComment"; + + Text = "TestComment"; Result = OPI_Airtable.CreateComment(Token, Base, Table, SingleRecord, Text); - + OPI_TestDataRetrieval.WriteLog(Result, "CreateComment"); - + OPI_TestDataRetrieval.ExpectsThat(Result["text"]).Равно(Text); - + Comment = Result["id"]; - Text = "Test comment (change.)"; - Result = OPI_Airtable.EditComment(Token, Base, Table, SingleRecord, Comment, Text); - + Text = "Test comment (change.)"; + Result = OPI_Airtable.EditComment(Token, Base, Table, SingleRecord, Comment, Text); + OPI_TestDataRetrieval.WriteLog(Result, "EditComment"); - + OPI_TestDataRetrieval.ExpectsThat(Result["text"]).Равно(Text); - + Result = OPI_Airtable.GetComments(Token, Base, Table, SingleRecord); - + OPI_TestDataRetrieval.WriteLog(Result, "GetComments"); - + OPI_TestDataRetrieval.ExpectsThat(Result["comments"]).ИмеетТип("Array"); - + Result = OPI_Airtable.DeleteComment(Token, Base, Table, SingleRecord, Comment); - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteComment"); - + OPI_TestDataRetrieval.ExpectsThat(Result["deleted"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["id"]).Равно(Comment); - + Result = OPI_Airtable.GetListOfRecords(Token, Base, Table); - + OPI_TestDataRetrieval.WriteLog(Result, "GetListOfRecords"); - + OPI_TestDataRetrieval.ExpectsThat(Result["records"]).ИмеетТип("Array"); OPI_TestDataRetrieval.ExpectsThat(Result["records"]).Заполнено(); - + Result = OPI_Airtable.DeletePosts(Token, Base, Table, ArrayOfDeletions); - + OPI_TestDataRetrieval.WriteLog(Result, "DeletePosts"); - + OPI_TestDataRetrieval.ExpectsThat(Result["records"]).ИмеетТип("Array"); OPI_TestDataRetrieval.ExpectsThat(Result["records"]).Заполнено(); - + Result = OPI_Airtable.DeletePosts(Token, Base, Table, SingleRecord); - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteRecords (one)"); - + OPI_TestDataRetrieval.ExpectsThat(Result["records"]).ИмеетТип("Array"); OPI_TestDataRetrieval.ExpectsThat(Result["records"]).Заполнено(); - + EndProcedure #EndRegion @@ -2729,29 +2729,29 @@ EndProcedure #Region Dropbox Procedure DropboxAPI_GetUpdateToken() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Dropbox_Appkey" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Dropbox_Appkey" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Dropbox_Appsecret", TestParameters); - - Dropbox_GetAuthorizationLink(TestParameters); - + + Dropbox_GetAuthorizationLink(TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Dropbox_Code", TestParameters); Dropbox_GetToken(TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("Dropbox_Refresh", TestParameters); - + Dropbox_UpdateToken(TestParameters); - + EndProcedure Procedure DropboxAPI_UploadFile() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Dropbox_Token", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Picture", TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); + Dropbox_UploadFile(TestParameters); Dropbox_GetObjectInformation(TestParameters); Dropbox_GetObjectVersionList(TestParameters); @@ -2761,73 +2761,73 @@ Procedure DropboxAPI_UploadFile() Export Dropbox_MoveObject(TestParameters); Dropbox_CopyObject(TestParameters); Dropbox_DeleteObject(TestParameters); - + EndProcedure Procedure DropboxAPI_CreateFolder() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Dropbox_Token", TestParameters); - + Dropbox_CreateFolder(TestParameters); Dropbox_DownloadFolder(TestParameters); - + EndProcedure Procedure DropboxAPI_GetFolderFileList() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Dropbox_Token", TestParameters); - + Dropbox_GetFolderFileList(TestParameters); - + EndProcedure Procedure DropboxAPI_UploadFileByURL() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Dropbox_Token", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Document", TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("Document" , TestParameters); + Dropbox_UploadFileByURL(TestParameters); Dropbox_GetUploadStatusByURL(TestParameters); - + EndProcedure Procedure DropboxAPI_CreateDeleteTag() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Dropbox_Token", TestParameters); - + Dropbox_AddTag(TestParameters); Dropbox_GetTagList(TestParameters); Dropbox_DeleteTag(TestParameters); - + EndProcedure Procedure DropboxAPI_GetAccount() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Dropbox_Token", TestParameters); - + Dropbox_GetAccountInformation(TestParameters); Dropbox_GetSpaceUsageData(TestParameters); - + EndProcedure Procedure DropboxAPI_AccessManagement() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Dropbox_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Dropbox_Token" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Dropbox_OtherUser", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Dropbox_FileID" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("Dropbox_FileID" , TestParameters); + Dropbox_AddUsersToFile(TestParameters); Dropbox_PublishFolder(TestParameters); Dropbox_AddUsersToFolder(TestParameters); Dropbox_CancelFolderPublication(TestParameters); Dropbox_CancelFilePublication(TestParameters); - + EndProcedure #EndRegion @@ -2835,43 +2835,43 @@ EndProcedure #Region Bitrix24 Procedure B24_TokenManagment() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Domain" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_ClientID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Domain" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_ClientID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_ClientSecret", TestParameters); - + Bitrix24_GetAppAuthLink(TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Code", TestParameters); - + Bitrix24_GetToken(TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Refresh", TestParameters); - + Bitrix24_RefreshToken(TestParameters); - + EndProcedure Procedure B24_ServerTime() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Domain", TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Token" , TestParameters); - - Bitrix24_ServerTime(TestParameters); + + Bitrix24_ServerTime(TestParameters); EndProcedure Procedure B24_PostsManagment() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Domain", TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Picture2" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Picture2" , TestParameters); Bitrix24_CreatePost(TestParameters); Bitrix24_UpdatePost(TestParameters); @@ -2880,18 +2880,18 @@ Procedure B24_PostsManagment() Export Bitrix24_AddPostComment(TestParameters); Bitrix_AddPostRecipients(TestParameters); Bitrix24_DeletePost(TestParameters); - + EndProcedure Procedure B24_TaskManagment() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Domain", TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Token" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_UserID", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); + Bitrix24_GetTaskFieldsStructure(TestParameters); Bitrix24_CreateTask(TestParameters); Bitrix24_CreateTasksDependencies(TestParameters); @@ -2910,7 +2910,7 @@ Procedure B24_TaskManagment() Export Bitrix24_StartTask(TestParameters); Bitrix24_StartWatchingTask(TestParameters); Bitrix24_StopWatchingTask(TestParameters); - Bitrix24_PauseTask(TestParameters); + Bitrix24_PauseTask(TestParameters); Bitrix24_GetTaskHistory(TestParameters); Bitrix24_GetTasksList(TestParameters); Bitrix24_CheckTaskAccesses(TestParameters); @@ -2922,35 +2922,35 @@ Procedure B24_TaskManagment() Export Bitrix24_RenewTasksChecklistElement(TestParameters); Bitrix24_DeleteTasksChecklistElement(TestParameters); Bitrix24_GetDailyPlan(TestParameters); - - Name = "Topic picture.jpg"; - Image = TestParameters["Picture"]; + + Name = "Topic picture.jpg"; + Image = TestParameters["Picture"]; DestinationID = 3; - + URL = TestParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.UploadFileToStorage(URL, Name, Image, DestinationID); - FileID = Result["result"]["ID"]; - - OPI_TestDataRetrieval.WriteParameter("Bitrix24_TaskFileID", FileID); + FileID = Result["result"]["ID"]; + + OPI_TestDataRetrieval.WriteParameter("Bitrix24_TaskFileID", FileID); TestParameters.Insert("Bitrix24_TaskFileID", FileID); - - Bitrix24_AttachFileToTopic(TestParameters); - + + Bitrix24_AttachFileToTopic(TestParameters); + OPI_Bitrix24.DeleteFile(URL, FileID); - + Bitrix24_DeleteTask(TestParameters); - + EndProcedure Procedure B24_WorkingWithDrive() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Domain", TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Picture2" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Picture2" , TestParameters); Bitrix24_GetStoragesList(TestParameters); Bitrix24_GetAppStorage(TestParameters); @@ -2979,34 +2979,34 @@ Procedure B24_WorkingWithDrive() Export Bitrxi24_MarkFolderAsDeleted(TestParameters); Bitrix24_RestoreFolder(TestParameters); Bitrix24_DeleteFolder(TestParameters); - + EndProcedure Procedure B24_CommentsManagment() Export TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Domain", TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Token" , TestParameters); - + CurrentDate = OPI_Tools.GetCurrentDate(); - Hour = 3600; - Day = 24; + Hour = 3600; + Day = 24; Responsible = 1; - + TaskData = New Structure; - TaskData.Insert("TITLE" , "New task"); - TaskData.Insert("DESCRIPTION" , "New task description"); - TaskData.Insert("PRIORITY" , "2"); - TaskData.Insert("DEADLINE" , CurrentDate + Hour * Day); + TaskData.Insert("TITLE" , "New task"); + TaskData.Insert("DESCRIPTION" , "New task description"); + TaskData.Insert("PRIORITY" , "2"); + TaskData.Insert("DEADLINE" , CurrentDate + Hour * Day); TaskData.Insert("RESPONSIBLE_ID", Responsible); - + URL = TestParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.CreateTask(URL, TaskData); - TaskID = Result["result"]["task"]["id"]; - - OPI_TestDataRetrieval.WriteParameter("Bitrix24_CommentsTaskID", TaskID); + TaskID = Result["result"]["task"]["id"]; + + OPI_TestDataRetrieval.WriteParameter("Bitrix24_CommentsTaskID", TaskID); TestParameters.Insert("Bitrix24_CommentsTaskID", TaskID); Bitrix24_AddTaskComment(TestParameters); @@ -3017,36 +3017,36 @@ Procedure B24_CommentsManagment() Export Bitrix24_GetTaskCommentsList(TestParameters); Bitrix24_GetTaskComment(TestParameters); Bitrix24_DeleteTaskComment(TestParameters); - - OPI_Bitrix24.DeleteTask(URL, TaskID); - + + OPI_Bitrix24.DeleteTask(URL, TaskID); + EndProcedure Procedure B24_Timekeeping() Export TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Domain", TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Token" , TestParameters); - + CurrentDate = OPI_Tools.GetCurrentDate(); - Hour = 3600; - Day = 24; + Hour = 3600; + Day = 24; Responsible = 1; - + TaskData = New Structure; - TaskData.Insert("TITLE" , "New task"); - TaskData.Insert("DESCRIPTION" , "New task description"); - TaskData.Insert("PRIORITY" , "2"); - TaskData.Insert("DEADLINE" , CurrentDate + Hour * Day); + TaskData.Insert("TITLE" , "New task"); + TaskData.Insert("DESCRIPTION" , "New task description"); + TaskData.Insert("PRIORITY" , "2"); + TaskData.Insert("DEADLINE" , CurrentDate + Hour * Day); TaskData.Insert("RESPONSIBLE_ID", Responsible); - + URL = TestParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.CreateTask(URL, TaskData); - TaskID = Result["result"]["task"]["id"]; - - OPI_TestDataRetrieval.WriteParameter("Bitrix24_ElapsedTaskID", TaskID); + TaskID = Result["result"]["task"]["id"]; + + OPI_TestDataRetrieval.WriteParameter("Bitrix24_ElapsedTaskID", TaskID); TestParameters.Insert("Bitrix24_ElapsedTaskID", TaskID); Bitrix24_AddTaskTimeAccounting(TestParameters); @@ -3054,59 +3054,59 @@ Procedure B24_Timekeeping() Export Bitrix24_GetTaskTimeAccountingList(TestParameters); Bitrix24_UpdateTaskTimeAccounting(TestParameters); Bitrix24_DeleteTaskTimeAccounting(TestParameters); - - OPI_Bitrix24.DeleteTask(URL, TaskID); - + + OPI_Bitrix24.DeleteTask(URL, TaskID); + EndProcedure Procedure B24_Kanban() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Domain", TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Token" , TestParameters); - + CurrentDate = OPI_Tools.GetCurrentDate(); - Hour = 3600; - Day = 24; + Hour = 3600; + Day = 24; Responsible = 1; - + TaskData = New Structure; - TaskData.Insert("TITLE" , "New task"); - TaskData.Insert("DESCRIPTION" , "New task description"); - TaskData.Insert("PRIORITY" , "2"); - TaskData.Insert("DEADLINE" , CurrentDate + Hour * Day); + TaskData.Insert("TITLE" , "New task"); + TaskData.Insert("DESCRIPTION" , "New task description"); + TaskData.Insert("PRIORITY" , "2"); + TaskData.Insert("DEADLINE" , CurrentDate + Hour * Day); TaskData.Insert("RESPONSIBLE_ID", Responsible); - + URL = TestParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.CreateTask(URL, TaskData); - TaskID = Result["result"]["task"]["id"]; - - OPI_TestDataRetrieval.WriteParameter("Bitrix24_KanbanTaskID", TaskID); + TaskID = Result["result"]["task"]["id"]; + + OPI_TestDataRetrieval.WriteParameter("Bitrix24_KanbanTaskID", TaskID); TestParameters.Insert("Bitrix24_KanbanTaskID", TaskID); - + Bitrix24_AddKanbanStage(TestParameters); Bitrix24_GetKanbanStages(TestParameters); Bitrix24_MoveTaskToKanbanStage(TestParameters); Bitrix24_UpdateKanbansStage(TestParameters); - - OPI_Bitrix24.DeleteTask(URL, TaskID); - + + OPI_Bitrix24.DeleteTask(URL, TaskID); + Bitrix24_DeleteKanbanStage(TestParameters); - + EndProcedure Procedure B24_ChatManagment() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Domain", TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Picture2" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Document" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Picture2" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Document" , TestParameters); + Bitrix24_GetUserStatus(TestParameters); Bitrix24_SetUserStatus(TestParameters); Bitrix24_GetUsers(TestParameters); @@ -3134,23 +3134,23 @@ Procedure B24_ChatManagment() Export Bitrix24_ReadAll(TestParameters); Bitrix24_ChangeChatOwner(TestParameters); Bitrix24_LeaveChat(TestParameters); - + EndProcedure Procedure B24_NotificationsManagment() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Domain", TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Picture2" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Document" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Picture2" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Document" , TestParameters); + Bitrix24_CreatePersonalNotification(TestParameters); Bitrix24_CreateSystemNotification(TestParameters); Bitrix24_DeleteNotification(TestParameters); - + EndProcedure #EndRegion @@ -3161,127 +3161,127 @@ EndProcedure #Region Private -Function GetVKParameters() - - Parameters = New Structure; +Function GetVKParameters() + + Parameters = New Structure; GroupNumber = OPI_TestDataRetrieval.GetParameter("VK_GroupID"); - + Parameters.Insert("access_token" , OPI_TestDataRetrieval.GetParameter("VK_Token")); - Parameters.Insert("owner_id" , "-" + GroupNumber); - Parameters.Insert("app_id" , OPI_TestDataRetrieval.GetParameter("VK_AppID")); - Parameters.Insert("group_id" , GroupNumber); - + Parameters.Insert("owner_id" , "-" + GroupNumber); + Parameters.Insert("app_id" , OPI_TestDataRetrieval.GetParameter("VK_AppID")); + Parameters.Insert("group_id" , GroupNumber); + Return Parameters; - + EndFunction -Function GetTwitterParameters() - +Function GetTwitterParameters() + Parameters = New Map; - - Parameters.Insert("redirect_uri" , OPI_TestDataRetrieval.GetParameter("Twitter_Redirect")); - Parameters.Insert("client_id" , OPI_TestDataRetrieval.GetParameter("Twitter_ClinetID")); - Parameters.Insert("client_secret" , OPI_TestDataRetrieval.GetParameter("Twitter_ClientSecret")); - Parameters.Insert("access_token" , OPI_TestDataRetrieval.GetParameter("Twitter_Token")); - Parameters.Insert("refresh_token" , OPI_TestDataRetrieval.GetParameter("Twitter_Refresh")); - Parameters.Insert("oauth_token" , OPI_TestDataRetrieval.GetParameter("Twitter_OAuthToken")); + + Parameters.Insert("redirect_uri" , OPI_TestDataRetrieval.GetParameter("Twitter_Redirect")); + Parameters.Insert("client_id" , OPI_TestDataRetrieval.GetParameter("Twitter_ClinetID")); + Parameters.Insert("client_secret" , OPI_TestDataRetrieval.GetParameter("Twitter_ClientSecret")); + Parameters.Insert("access_token" , OPI_TestDataRetrieval.GetParameter("Twitter_Token")); + Parameters.Insert("refresh_token" , OPI_TestDataRetrieval.GetParameter("Twitter_Refresh")); + Parameters.Insert("oauth_token" , OPI_TestDataRetrieval.GetParameter("Twitter_OAuthToken")); Parameters.Insert("oauth_token_secret" , OPI_TestDataRetrieval.GetParameter("Twitter_OAuthSecret")); - - Parameters.Insert("oauth_consumer_key" + + Parameters.Insert("oauth_consumer_key" , OPI_TestDataRetrieval.GetParameter("Twitter_OAuthConsumerKey")); - Parameters.Insert("oauth_consumer_secret" + Parameters.Insert("oauth_consumer_secret" , OPI_TestDataRetrieval.GetParameter("Twitter_OAuthConsumerSecret")); Return Parameters; - + EndFunction #Region Checks -Procedure Check_Empty(Val Result) +Procedure Check_Empty(Val Result) OPI_TestDataRetrieval.ExpectsThat(ValueIsFilled(Result)).Равно(False); EndProcedure -Procedure Check_String(Val Result) - OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("String"); +Procedure Check_String(Val Result) + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("String"); EndProcedure Procedure Check_BinaryData(Val Result, Val Size = Undefined) - + MinimumSize = 500000; - - OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("BinaryData"); - + + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("BinaryData"); + If Not Size = Undefined Then - OPI_TestDataRetrieval.ExpectsThat(Result.Size() >= Size).Равно(True); + OPI_TestDataRetrieval.ExpectsThat(Result.Size() >= Size).Равно(True); Else OPI_TestDataRetrieval.ExpectsThat(Result.Size() > MinimumSize).Равно(True); EndIf; - + EndProcedure Procedure Check_Array(Val Result, Val Count = Undefined) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Array"); - + If Not Count = Undefined Then - OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетДлину(Count); - EndIf; - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетДлину(Count); + EndIf; + EndProcedure Procedure Check_Map(Val Result) - OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); + EndProcedure Procedure Check_Structure(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Structure").Заполнено(); - + EndProcedure Procedure Check_TelegramTrue(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]).Равно(True); - + EndProcedure Procedure Check_TelegramBotInformation(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["username"]).Заполнено(); - + EndProcedure Procedure Check_TelegramArray(Result) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map") .Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Array"); - + EndProcedure Procedure Check_TelegramWebhookSetup(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["description"]).Равно("Webhook was set"); - + EndProcedure Procedure Check_TelegramWebhookDeletion(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["description"]).Заполнено(); - + EndProcedure Procedure Check_TelegramMessage(Val Result, Val Text) @@ -3289,16 +3289,16 @@ Procedure Check_TelegramMessage(Val Result, Val Text) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["text"]).Равно(Text); - + EndProcedure Procedure Check_TelegramImage(Val Result, Val Text) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map") .Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["caption"]).Равно(Text); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["photo"]).ИмеетТип("Array"); - + EndProcedure Procedure Check_TelegramVideo(Val Result, Val Text) @@ -3307,7 +3307,7 @@ Procedure Check_TelegramVideo(Val Result, Val Text) OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["caption"]).Равно(Text); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["video"]["mime_type"]).Равно("video/mp4"); - + EndProcedure Procedure Check_TelegramAudio(Val Result, Val Text) @@ -3316,7 +3316,7 @@ Procedure Check_TelegramAudio(Val Result, Val Text) OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["caption"]).Равно(Text); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["audio"]["mime_type"]).Равно("audio/mpeg"); - + EndProcedure Procedure Check_TelegramDocument(Val Result, Val Text) @@ -3324,20 +3324,20 @@ Procedure Check_TelegramDocument(Val Result, Val Text) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["caption"]).Равно(Text); - OPI_TestDataRetrieval.ExpectsThat(Result["result"]["document"]).ИмеетТип("Map").Заполнено(); - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]["document"]).ИмеетТип("Map").Заполнено(); + EndProcedure Procedure Check_TelegramGif(Val Result, Val Text) Result_ = "result"; - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result[Result_]["caption"]).Равно(Text); OPI_TestDataRetrieval.ExpectsThat(Result[Result_]["document"]).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result[Result_]["animation"]["mime_type"]).Равно("video/mp4"); - + EndProcedure Procedure Check_TelegramMediaGroup(Val Result) @@ -3345,15 +3345,15 @@ Procedure Check_TelegramMediaGroup(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Array"); - + EndProcedure Procedure Check_TelegramLocation(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); - OPI_TestDataRetrieval.ExpectsThat(Result["result"]["location"]).ИмеетТип("Map").Заполнено(); - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]["location"]).ИмеетТип("Map").Заполнено(); + EndProcedure Procedure Check_TelegramContact(Val Result, Val Name) @@ -3362,7 +3362,7 @@ Procedure Check_TelegramContact(Val Result, Val Name) OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["contact"]).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["contact"]["first_name"]).Равно(Name); - + EndProcedure Procedure Check_TelegramPoll(Val Result, Val Question) @@ -3371,22 +3371,22 @@ Procedure Check_TelegramPoll(Val Result, Val Question) OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["poll"]).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["poll"]["question"]).Равно(Question); - + EndProcedure Procedure Check_TelegramForward(Val Result, Val MessageID) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["forward_origin"]["message_id"]).Равно(Number(MessageID)); - + EndProcedure Procedure Check_TelegramBan(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["description"]).Равно("Bad Request: can't remove chat owner"); - + EndProcedure Procedure Check_TelegramInvitation(Val Result, Val Title, Val UnixExpiration) @@ -3397,7 +3397,7 @@ Procedure Check_TelegramInvitation(Val Result, Val Title, Val UnixExpiration) OPI_TestDataRetrieval.ExpectsThat(Result[Result_]["member_limit"]).Равно(200); OPI_TestDataRetrieval.ExpectsThat(Result[Result_]["name"]).Равно(Title); OPI_TestDataRetrieval.ExpectsThat(Result[Result_]["expire_date"]).Равно(Number(UnixExpiration)); - + EndProcedure Procedure Check_TelegramNumber(Val Result) @@ -3405,7 +3405,7 @@ Procedure Check_TelegramNumber(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Number"); - + EndProcedure Procedure Check_TelegramCreateTopic(Val Result, Val Name, Icon) @@ -3414,60 +3414,60 @@ Procedure Check_TelegramCreateTopic(Val Result, Val Name, Icon) OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["name"]).Равно(Name); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["icon_custom_emoji_id"]).Равно(Icon); - + EndProcedure Procedure Check_VKPost(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["post_id"]).ИмеетТип("Number").Заполнено(); - + EndProcedure Procedure Check_VKTrue(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["response"]).ИмеетТип("Number").Равно(1); - + EndProcedure Procedure Check_VKAlbum(Val Result, Val Description) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["description"]).Равно(Description); - + EndProcedure Procedure Check_VKAlbumPicture(Val Result, Val ImageDescription, Val AlbumID) Response = "response"; - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result[Response][0]["text"]).Равно(ImageDescription); OPI_TestDataRetrieval.ExpectsThat(Result[Response][0]["album_id"]).Равно(AlbumID); - + EndProcedure Procedure Check_VKStory(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["count"]).ИмеетТип("Number").Равно(1); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["items"]).ИмеетТип("Array").Заполнено(); - + EndProcedure Procedure Check_VKDiscussion(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); - OPI_TestDataRetrieval.ExpectsThat(Result["response"]).ИмеетТип("Number").Заполнено(); - + OPI_TestDataRetrieval.ExpectsThat(Result["response"]).ИмеетТип("Number").Заполнено(); + EndProcedure Procedure Check_VKLike(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["likes"]).ИмеетТип("Number").Заполнено(); - + EndProcedure Procedure Check_VKRepost(Val Result) @@ -3475,37 +3475,37 @@ Procedure Check_VKRepost(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["success"]).ИмеетТип("Number").Равно(1); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["wall_repost_count"]).ИмеетТип("Number").Равно(1); - + EndProcedure Procedure Check_VKComment(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["comment_id"]).ИмеетТип("Number").Заполнено(); - + EndProcedure Procedure Check_VKStatistic(Val Result) - + TypeMap = "Map"; - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип(TypeMap).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["response"][0]["visitors"]).ИмеетТип(TypeMap).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["response"][0]["reach"]).ИмеетТип(TypeMap).Заполнено(); - + EndProcedure Procedure Check_VKPostsStatistic(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Array").ИмеетДлину(2); - + EndProcedure Procedure Check_VKNumber(Val Result) - OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map"); + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["response"]).ИмеетТип("Number").Заполнено(); - + EndProcedure Procedure Check_VKCollection(Val Result) @@ -3513,59 +3513,59 @@ Procedure Check_VKCollection(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["albums_count"]).ИмеетТип("Number").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["market_album_id"]).ИмеетТип("Number").Заполнено(); - + EndProcedure Procedure Check_VKProduct(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["market_item_id"]).ИмеетТип("Number").Заполнено(); - + EndProcedure Procedure Check_VKProp(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["property_id"]).ИмеетТип("Number").Заполнено(); - + EndProcedure Procedure Check_VKPropVariant(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["variant_id"]).ИмеетТип("Number").Заполнено(); - + EndProcedure Procedure Check_VKProductData(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["items"]).ИмеетТип("Array").ИмеетДлину(2); - + EndProcedure Procedure Check_VKProductsGroup(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["item_group_id"]).ИмеетТип("Number").Заполнено(); - + EndProcedure Procedure Check_VKVideo(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result["video_id"]).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["video_hash"]).Заполнено(); - + EndProcedure Procedure Check_YaDiskDrive(Val Result) Map_ = "Map"; - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип(Map_).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["system_folders"]).ИмеетТип(Map_); OPI_TestDataRetrieval.ExpectsThat(Result["user"]).ИмеетТип(Map_); - + EndProcedure Procedure Check_YaDiskFolder(Val Result, Val Path) @@ -3573,69 +3573,69 @@ Procedure Check_YaDiskFolder(Val Result, Val Path) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["type"]).Равно("dir"); OPI_TestDataRetrieval.ExpectsThat(Result["path"]).Равно("disk:" + Path); - + EndProcedure Procedure Check_GKObject(Val Result, Val Name, Val Description) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["summary"]).Равно(Name); OPI_TestDataRetrieval.ExpectsThat(Result["description"]).Равно(Description); OPI_TestDataRetrieval.ExpectsThat(Result["id"]).ИмеетТип("String").Заполнено(); - + EndProcedure Procedure Check_TwitterText(Val Result, Val Text) - + ReplyText = Result["data"]["text"]; ReplyText = Left(ReplyText, StrLen(Text)); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(ReplyText).Равно(Text); EndProcedure Procedure Check_ViberOk(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["status_message"]).Равно("ok"); OPI_TestDataRetrieval.ExpectsThat(Result["status"]).Равно(0); EndProcedure Procedure Check_NotionObject(Val Result, Val View = "page") - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["object"]).Равно(View); - + EndProcedure Procedure Check_SlackOk(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); EndProcedure Procedure Check_DropboxFile(Val Result, Val Path) - + OPI_TestDataRetrieval.ExpectsThat(Result["path_display"]).Равно(Path); - + EndProcedure Procedure Check_DropboxMetadata(Val Result, Val Path) - + OPI_TestDataRetrieval.ExpectsThat(Result["metadata"]["path_display"]).Равно(Path); - + EndProcedure Procedure Check_DropboxArray(Val Result, Val Count = Undefined) - + OPI_TestDataRetrieval.ExpectsThat(Result["entries"]).ИмеетТип("Array"); - + If Not Count = Undefined Then OPI_TestDataRetrieval.ExpectsThat(Result["entries"].Count()).Равно(Count); EndIf; - + EndProcedure Procedure Check_DropboxWork(Val Result) @@ -3647,10 +3647,10 @@ Procedure Check_DropboxStatus(Val Result) EndProcedure Procedure Check_DropboxTags(Val Result, Val Count) - + OPI_TestDataRetrieval.ExpectsThat(Result["paths_to_tags"]).ИмеетТип("Array"); OPI_TestDataRetrieval.ExpectsThat(Result["paths_to_tags"].Count()).Равно(Count); - + EndProcedure Procedure Check_DropboxAccount(Val Result) @@ -3673,38 +3673,38 @@ Procedure Check_DropboxPublicFolder(Val Result) EndProcedure Procedure Check_BitrixTime(Val Result) - + Time = Result["result"]; - + If Not TypeOf(Time) = Type("Date") Then - Time = XMLValue(Type("Date"), Time); + Time = XMLValue(Type("Date"), Time); EndIf; - + OPI_TestDataRetrieval.ExpectsThat(Time).ИмеетТип("Date").Заполнено(); - + EndProcedure Procedure Check_BitrixAuth(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["access_token"]).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["refresh_token"]).Заполнено(); EndProcedure Procedure Check_BitrixNumber(Val Result) - OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Number").Заполнено(); + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Number").Заполнено(); EndProcedure Procedure Check_BitrixTrue(Val Result) - OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Boolean").Равно(True); -EndProcedure + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Boolean").Равно(True); +EndProcedure Procedure Check_BitrixBool(Val Result) - OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Boolean"); + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Boolean"); EndProcedure Procedure Check_BitrixString(Val Result) - OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("String").Заполнено(); + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("String").Заполнено(); EndProcedure Procedure Check_BitrixArray(Val Result) @@ -3720,22 +3720,22 @@ Procedure Check_BitrixList(Val Result) EndProcedure Procedure Check_BitrixObjectsArray(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Array"); OPI_TestDataRetrieval.ExpectsThat(Result["result"][0]["ID"]).Заполнено(); - + EndProcedure Procedure Check_BitrixFields(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]["fields"]).Заполнено(); - + EndProcedure Procedure Check_BitrixTask(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]["task"]).Заполнено(); - + EndProcedure Procedure Check_BitrixTasksList(Val Result) @@ -3758,75 +3758,75 @@ Procedure Check_BitrixAttachment(Val Result) EndProcedure Procedure Check_BitrixAvailableActions(Val Result, Val Count) - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Map"); - + Actions = Result["result"]["allowedActions"]; OPI_TestDataRetrieval.ExpectsThat(Actions).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Actions.Count()).Равно(Count); - + EndProcedure Procedure Check_BitrixComment(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["POST_MESSAGE"]).Заполнено(); - + EndProcedure Procedure Check_BitrixResult(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["text"]).Заполнено(); EndProcedure Procedure Check_BitrixUndefined(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Undefined"); OPI_TestDataRetrieval.ExpectsThat(Result["time"]).Заполнено(); EndProcedure Procedure Check_BitrixCommentsList(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Array"); OPI_TestDataRetrieval.ExpectsThat(Result["result"][0]["POST_MESSAGE"]).Заполнено(); - + EndProcedure Procedure Check_BitrixResultsList(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Array"); OPI_TestDataRetrieval.ExpectsThat(Result["result"][0]["text"]).Заполнено(); - + EndProcedure Procedure Check_BitrixMessages(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]["messages"]).ИмеетТип("Array"); - + EndProcedure Procedure Check_BitrixDialog(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["dialogId"]).Заполнено(); - + EndProcedure Procedure Check_BitrixMessage(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["id"]).Заполнено(); - + EndProcedure Procedure Check_BitrixFileMessage(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["MESSAGE_ID"]).Заполнено(); - + EndProcedure #EndRegion @@ -3837,825 +3837,825 @@ EndProcedure Procedure Telegram_GetBotInformation(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; + Token = FunctionParameters["Telegram_Token"]; Result = OPI_Telegram.GetBotInformation(Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetBotInformation", "Telegram"); - + Check_TelegramBotInformation(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_GetUpdates(FunctionParameters) - - Token = FunctionParameters["Telegram_Token"]; + + Token = FunctionParameters["Telegram_Token"]; Result = OPI_Telegram.GetUpdates(Token); // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetUpdates", "Telegram"); - + Check_TelegramArray(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_SetWebhook(FunctionParameters) - + Token = FunctionParameters["Telegram_Token"]; - URL = FunctionParameters["Telegram_URL"]; - + URL = FunctionParameters["Telegram_URL"]; + Result = OPI_Telegram.SetWebhook(Token, URL); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "SetWebhook", "Telegram"); - + Check_TelegramWebhookSetup(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_DeleteWebhook(FunctionParameters) - - Token = FunctionParameters["Telegram_Token"]; + + Token = FunctionParameters["Telegram_Token"]; Result = OPI_Telegram.DeleteWebhook(Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteWebhook", "Telegram"); - + Check_TelegramWebhookDeletion(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_SendTextMessage(FunctionParameters) - - Token = FunctionParameters["Telegram_Token"]; - ChatID = FunctionParameters["Telegram_ChatID"]; - ChannelID = FunctionParameters["Telegram_ChannelID"]; - Text = FunctionParameters["String"]; - + + Token = FunctionParameters["Telegram_Token"]; + ChatID = FunctionParameters["Telegram_ChatID"]; + ChannelID = FunctionParameters["Telegram_ChannelID"]; + Text = FunctionParameters["String"]; + Result = OPI_Telegram.SendTextMessage(Token, ChatID, Text); - - OPI_TestDataRetrieval.WriteLog(Result, "SendTextMessage", "Telegram"); - + + OPI_TestDataRetrieval.WriteLog(Result, "SendTextMessage", "Telegram"); + Check_TelegramMessage(Result, Text); // SKIP - + Result = OPI_Telegram.SendTextMessage(Token, ChannelID, Text); - + // END - - OPI_TestDataRetrieval.WriteLog(Result, "SendTextMessage (channel)"); - + + OPI_TestDataRetrieval.WriteLog(Result, "SendTextMessage (channel)"); + Check_TelegramMessage(Result, Text); - + MessageID = OPI_Tools.NumberToString(Result["result"]["message_id"]); OPI_TestDataRetrieval.WriteParameter("Telegram_ChannelMessageID", MessageID); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_SendPicture(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - ChatID = FunctionParameters["Telegram_ChatID"]; + Token = FunctionParameters["Telegram_Token"]; + ChatID = FunctionParameters["Telegram_ChatID"]; ChannelID = FunctionParameters["Telegram_ChannelID"]; - Text = FunctionParameters["String"]; - Image = FunctionParameters["Picture"]; - + Text = FunctionParameters["String"]; + Image = FunctionParameters["Picture"]; + ImagePath = GetTempFileName("png"); CopyFile(Image, ImagePath); - + ImageDD = New BinaryData(ImagePath); - + Result = OPI_Telegram.SendImage(Token, ChatID, Text, Image); - + OPI_TestDataRetrieval.WriteLog(Result, "SendImage", "Telegram"); - + Check_TelegramImage(Result, Text); // SKIP - + Result = OPI_Telegram.SendImage(Token, ChannelID, Text, ImagePath); - + OPI_TestDataRetrieval.WriteLog(Result, "SendPicture (Path)"); - + Check_TelegramImage(Result, Text); // SKIP - + Result = OPI_Telegram.SendImage(Token, ChannelID, Text, ImageDD); - - // END - + + // END + OPI_TestDataRetrieval.WriteLog(Result, "SendPicture (DD)"); - + Check_TelegramImage(Result, Text); - + DeleteFiles(ImagePath); - + FileID = Result["result"]["photo"][0]["file_id"]; OPI_TestDataRetrieval.WriteParameter("Telegram_FileID", FileID); - + FunctionParameters.Insert("Telegram_FileID", FileID); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_SendVideo(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - ChatID = FunctionParameters["Telegram_ChatID"]; + Token = FunctionParameters["Telegram_Token"]; + ChatID = FunctionParameters["Telegram_ChatID"]; ChannelID = FunctionParameters["Telegram_ChannelID"]; - Text = FunctionParameters["String"]; - Video = FunctionParameters["Video"]; - + Text = FunctionParameters["String"]; + Video = FunctionParameters["Video"]; + VideoPath = GetTempFileName("mp4"); CopyFile(Video, VideoPath); - + VideoDD = New BinaryData(VideoPath); - + Result = OPI_Telegram.SendVideo(Token, ChatID, Text, Video); - + OPI_TestDataRetrieval.WriteLog(Result, "SendVideo", "Telegram"); - + Check_TelegramVideo(Result, Text); // SKIP - + Result = OPI_Telegram.SendVideo(Token, ChannelID, Text, VideoPath); - + OPI_TestDataRetrieval.WriteLog(Result, "SendVideo (Path)"); - + Check_TelegramVideo(Result, Text); // SKIP - + Result = OPI_Telegram.SendVideo(Token, ChannelID, Text, VideoDD); - - // END - + + // END + OPI_TestDataRetrieval.WriteLog(Result, "SendVideo (DD)"); - + Check_TelegramVideo(Result, Text); - + DeleteFiles(VideoPath); - + FileID = Result["result"]["video"]["file_id"]; OPI_TestDataRetrieval.WriteParameter("Telegram_FileID", FileID); - + FunctionParameters.Insert("Telegram_FileID", FileID); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_SendAudio(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - ChatID = FunctionParameters["Telegram_ChatID"]; + Token = FunctionParameters["Telegram_Token"]; + ChatID = FunctionParameters["Telegram_ChatID"]; ChannelID = FunctionParameters["Telegram_ChannelID"]; - Text = FunctionParameters["String"]; - Audio = FunctionParameters["Audio"]; - + Text = FunctionParameters["String"]; + Audio = FunctionParameters["Audio"]; + AudioPath = GetTempFileName("mp3"); CopyFile(Audio, AudioPath); - + AudioDD = New BinaryData(AudioPath); - + Result = OPI_Telegram.SendAudio(Token, ChatID, Text, Audio); - + OPI_TestDataRetrieval.WriteLog(Result, "SendAudio", "Telegram"); - + Check_TelegramAudio(Result, Text); // SKIP - + Result = OPI_Telegram.SendAudio(Token, ChannelID, Text, AudioPath); - + OPI_TestDataRetrieval.WriteLog(Result, "SendAudio (Path)"); - + Check_TelegramAudio(Result, Text); // SKIP - + Result = OPI_Telegram.SendAudio(Token, ChannelID, Text, AudioDD); - - // END - + + // END + OPI_TestDataRetrieval.WriteLog(Result, "SendAudio (DD)"); - + Check_TelegramAudio(Result, Text); - + DeleteFiles(AudioPath); - + FileID = Result["result"]["audio"]["file_id"]; OPI_TestDataRetrieval.WriteParameter("Telegram_FileID", FileID); - + FunctionParameters.Insert("Telegram_FileID", FileID); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_SendDocument(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - ChatID = FunctionParameters["Telegram_ChatID"]; + Token = FunctionParameters["Telegram_Token"]; + ChatID = FunctionParameters["Telegram_ChatID"]; ChannelID = FunctionParameters["Telegram_ChannelID"]; - Text = FunctionParameters["String"]; - Document = FunctionParameters["Document"]; - + Text = FunctionParameters["String"]; + Document = FunctionParameters["Document"]; + DocumentPath = GetTempFileName("docx"); CopyFile(Document, DocumentPath); - + DocumentDD = New BinaryData(DocumentPath); - + Result = OPI_Telegram.SendDocument(Token, ChatID, Text, Document); - + OPI_TestDataRetrieval.WriteLog(Result, "SendDocument", "Telegram"); - + Check_TelegramDocument(Result, Text); // SKIP - + Result = OPI_Telegram.SendDocument(Token, ChatID, Text, Document, , , "customname.docx"); - + OPI_TestDataRetrieval.WriteLog(Result, "SendDocument (with name)", "Telegram"); - + Check_TelegramDocument(Result, Text); // SKIP - + Result = OPI_Telegram.SendDocument(Token, ChannelID, Text, DocumentPath); - + OPI_TestDataRetrieval.WriteLog(Result, "SendDocument (Path)"); - + Check_TelegramDocument(Result, Text); // SKIP - + Result = OPI_Telegram.SendDocument(Token, ChannelID, Text, DocumentDD, , , "customname.docx"); - - // END - + + // END + OPI_TestDataRetrieval.WriteLog(Result, "SendDocument (DD)"); - + Check_TelegramDocument(Result, Text); - + DeleteFiles(DocumentPath); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_SendGif(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - ChatID = FunctionParameters["Telegram_ChatID"]; + Token = FunctionParameters["Telegram_Token"]; + ChatID = FunctionParameters["Telegram_ChatID"]; ChannelID = FunctionParameters["Telegram_ChannelID"]; - Text = FunctionParameters["String"]; - GIF = FunctionParameters["GIF"]; - + Text = FunctionParameters["String"]; + GIF = FunctionParameters["GIF"]; + GifPath = GetTempFileName("gif"); CopyFile(GIF, GifPath); - + GifDD = New BinaryData(GifPath); - + Result = OPI_Telegram.SendGif(Token, ChatID, Text, GIF); - + OPI_TestDataRetrieval.WriteLog(Result, "SendGif", "Telegram"); - + Check_TelegramGif(Result, Text); // SKIP - + Result = OPI_Telegram.SendGif(Token, ChannelID, Text, GifPath); - + OPI_TestDataRetrieval.WriteLog(Result, "SendGif (Path)"); - + Check_TelegramGif(Result, Text); // SKIP - + Result = OPI_Telegram.SendGif(Token, ChannelID, Text, GifDD); - - // END - + + // END + OPI_TestDataRetrieval.WriteLog(Result, "SendGif (DD)"); - + Check_TelegramGif(Result, Text); - + DeleteFiles(GifPath); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_SendMediaGroup(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; + Token = FunctionParameters["Telegram_Token"]; ChatID = FunctionParameters["Telegram_ChatID"]; - Text = FunctionParameters["String"]; - Image = FunctionParameters["Picture"]; - Video = FunctionParameters["Video"]; - + Text = FunctionParameters["String"]; + Image = FunctionParameters["Picture"]; + Video = FunctionParameters["Video"]; + ImagePath = GetTempFileName("png"); CopyFile(Image, ImagePath); - + VideoPath = GetTempFileName("mp4"); CopyFile(Video, VideoPath); - + VideoDD = New BinaryData(VideoPath); - + MediaGroup = New Map; MediaGroup.Insert(ImagePath, "photo"); - MediaGroup.Insert(VideoDD , "video"); - + MediaGroup.Insert(VideoDD , "video"); + Result = OPI_Telegram.SendMediaGroup(Token, ChatID, Text, MediaGroup); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "SendMediaGroup", "Telegram"); - + Check_TelegramMediaGroup(Result); - - DocumentURL = FunctionParameters["Document"]; + + DocumentURL = FunctionParameters["Document"]; DocumentPath = GetTempFileName("docx"); - ChannelID = FunctionParameters["Telegram_ChannelID"]; - + ChannelID = FunctionParameters["Telegram_ChannelID"]; + CopyFile(DocumentURL, DocumentPath); - + MediaGroup = New Map; MediaGroup.Insert(DocumentURL , "document"); - MediaGroup.Insert(DocumentPath, "document"); - + MediaGroup.Insert(DocumentPath, "document"); + Result = OPI_Telegram.SendMediaGroup(Token, ChannelID, Text, MediaGroup); - + OPI_TestDataRetrieval.WriteLog(Result, "SendMediaGroup (docs)", "Telegram"); - + Check_TelegramMediaGroup(Result); - + DeleteFiles(VideoPath); DeleteFiles(ImagePath); DeleteFiles(DocumentPath); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_SendLocation(FunctionParameters) - - Token = FunctionParameters["Telegram_Token"]; - ChatID = FunctionParameters["Telegram_ChatID"]; - ChannelID = FunctionParameters["Telegram_ChannelID"]; - Width = FunctionParameters["Lat"]; + + Token = FunctionParameters["Telegram_Token"]; + ChatID = FunctionParameters["Telegram_ChatID"]; + ChannelID = FunctionParameters["Telegram_ChannelID"]; + Width = FunctionParameters["Lat"]; Longitude = FunctionParameters["Long"]; - + Result = OPI_Telegram.SendLocation(Token, ChatID, Width, Longitude); - - OPI_TestDataRetrieval.WriteLog(Result, "SendLocation", "Telegram"); - + + OPI_TestDataRetrieval.WriteLog(Result, "SendLocation", "Telegram"); + Check_TelegramLocation(Result); // SKIP - + Result = OPI_Telegram.SendLocation(Token, ChannelID, Width, Longitude); - + // END - - OPI_TestDataRetrieval.WriteLog(Result, "SendLocation (channel)"); - + + OPI_TestDataRetrieval.WriteLog(Result, "SendLocation (channel)"); + Check_TelegramLocation(Result); OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_SendContact(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - ChatID = FunctionParameters["Telegram_ChatID"]; - ChannelID = FunctionParameters["Telegram_ChannelID"]; - Name = FunctionParameters["Name"]; - LastName = FunctionParameters["Surname"]; - Phone = FunctionParameters["Phone"]; - + Token = FunctionParameters["Telegram_Token"]; + ChatID = FunctionParameters["Telegram_ChatID"]; + ChannelID = FunctionParameters["Telegram_ChannelID"]; + Name = FunctionParameters["Name"]; + LastName = FunctionParameters["Surname"]; + Phone = FunctionParameters["Phone"]; + Result = OPI_Telegram.SendContact(Token, ChatID , Name, LastName, Phone); - - OPI_TestDataRetrieval.WriteLog(Result, "SendContact", "Telegram"); - + + OPI_TestDataRetrieval.WriteLog(Result, "SendContact", "Telegram"); + Check_TelegramContact(Result, Name); // SKIP OPI_Tools.Pause(20); // SKIP - + Result = OPI_Telegram.SendContact(Token, ChannelID, Name, LastName, Phone); - + // END - - OPI_TestDataRetrieval.WriteLog(Result, "SendContact (channel)"); - + + OPI_TestDataRetrieval.WriteLog(Result, "SendContact (channel)"); + Check_TelegramContact(Result, Name); OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_SendPoll(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - ChatID = FunctionParameters["Telegram_ChatID"]; - ChannelID = FunctionParameters["Telegram_ChannelID"]; - Question = "What's your favorite color?"; - + Token = FunctionParameters["Telegram_Token"]; + ChatID = FunctionParameters["Telegram_ChatID"]; + ChannelID = FunctionParameters["Telegram_ChannelID"]; + Question = "What's your favorite color?"; + AnswersArray = New Array; AnswersArray.Add("Red"); AnswersArray.Add("Yellow"); AnswersArray.Add("Green"); AnswersArray.Add("Blue"); - + Result = OPI_Telegram.SendPoll(Token, ChatID , Question, AnswersArray, False); - + OPI_TestDataRetrieval.WriteLog(Result, "SendPoll", "Telegram"); - + Check_TelegramPoll(Result, Question); // SKIP - + Result = OPI_Telegram.SendPoll(Token, ChannelID, Question, AnswersArray, True); - + OPI_TestDataRetrieval.WriteLog(Result, "SendPoll (channel)"); - + Check_TelegramPoll(Result, Question); // SKIP - + // END - + StringArray = "['Red', 'Yellow', 'Green', 'Blue']"; - + Result = OPI_Telegram.SendPoll(Token, ChannelID, Question, StringArray, True); - + OPI_TestDataRetrieval.WriteLog(Result, "SendPoll (string array)"); - + Check_TelegramPoll(Result, Question); OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_DownloadFile(FunctionParameters) - + FileID = FunctionParameters["Telegram_FileID"]; - Token = FunctionParameters["Telegram_Token"]; + Token = FunctionParameters["Telegram_Token"]; Result = OPI_Telegram.DownloadFile(Token, FileID); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "DownloadFile", "Telegram"); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("BinaryData"); - + EndProcedure Procedure Telegram_ForwardMessage(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - ChatID = FunctionParameters["Telegram_ChatID"]; + Token = FunctionParameters["Telegram_Token"]; + ChatID = FunctionParameters["Telegram_ChatID"]; ChannelID = FunctionParameters["Telegram_ChannelID"]; MessageID = FunctionParameters["Telegram_ChannelMessageID"]; - + Result = OPI_Telegram.ForwardMessage(Token, MessageID, ChannelID, ChatID); - + // END OPI_TestDataRetrieval.WriteLog(Result, "ForwardMessage", "Telegram"); - + Check_TelegramForward(Result, MessageID); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_Ban(FunctionParameters) - - Token = FunctionParameters["Telegram_Token"]; - UserID = FunctionParameters["Telegram_ChatID"]; + + Token = FunctionParameters["Telegram_Token"]; + UserID = FunctionParameters["Telegram_ChatID"]; ChannelID = FunctionParameters["Telegram_ChannelID"]; - + Result = OPI_Telegram.Ban(Token, ChannelID, UserID); // END - + OPI_TestDataRetrieval.WriteLog(Result, "Ban", "Telegram"); - + Check_TelegramBan(Result); OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_Unban(FunctionParameters) - - Token = FunctionParameters["Telegram_Token"]; - UserID = FunctionParameters["Telegram_ChatID"]; + + Token = FunctionParameters["Telegram_Token"]; + UserID = FunctionParameters["Telegram_ChatID"]; ChannelID = FunctionParameters["Telegram_ChannelID"]; - + Result = OPI_Telegram.Unban(Token, ChannelID, UserID); // END - + OPI_TestDataRetrieval.WriteLog(Result, "Unban", "Telegram"); - + Check_TelegramBan(Result); OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_CreateInviteLink(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - ChannelID = FunctionParameters["Telegram_ChannelID"]; - Day = 86400; + Token = FunctionParameters["Telegram_Token"]; + ChannelID = FunctionParameters["Telegram_ChannelID"]; + Day = 86400; CurrentDate = OPI_Tools.GetCurrentDate(); - Title = "Link " + String(CurrentDate); - Expiration = CurrentDate + Day; + Title = "Link " + String(CurrentDate); + Expiration = CurrentDate + Day; UnixExpiration = OPI_Tools.UNIXTime(Expiration); - + Result = OPI_Telegram.CreateInvitationLink(Token, ChannelID, Title, Expiration, 200); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CreateInvitationLink", "Telegram"); Check_TelegramInvitation(Result, Title, UnixExpiration); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_PinMessage(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; + Token = FunctionParameters["Telegram_Token"]; ChannelID = FunctionParameters["Telegram_ChannelID"]; MessageID = FunctionParameters["Telegram_ChannelMessageID"]; - + Result = OPI_Telegram.PinMessage(Token, ChannelID, MessageID); // END - + OPI_TestDataRetrieval.WriteLog(Result, "PinMessage", "Telegram"); - + Check_TelegramTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_UnpinMessage(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; + Token = FunctionParameters["Telegram_Token"]; ChannelID = FunctionParameters["Telegram_ChannelID"]; MessageID = FunctionParameters["Telegram_ChannelMessageID"]; - + Result = OPI_Telegram.UnpinMessage(Token, ChannelID, MessageID); // END - + OPI_TestDataRetrieval.WriteLog(Result, "UnpinMessage", "Telegram"); - + Check_TelegramTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_GetParticipantCount(FunctionParameters) - - Token = FunctionParameters["Telegram_Token"]; + + Token = FunctionParameters["Telegram_Token"]; ChannelID = FunctionParameters["Telegram_ChannelID"]; - + Result = OPI_Telegram.GetParticipantCount(Token, ChannelID); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetParticipantCount", "Telegram"); - + Check_TelegramNumber(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_GetForumAvatarList(FunctionParameters) - - Token = FunctionParameters["Telegram_Token"]; + + Token = FunctionParameters["Telegram_Token"]; Result = OPI_Telegram.GetAvatarIconList(Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetAvatarIconList", "Telegram"); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_CreateForumTopic(FunctionParameters) - - Token = FunctionParameters["Telegram_Token"]; + + Token = FunctionParameters["Telegram_Token"]; Chat = FunctionParameters["Telegram_ForumID"]; Icon = "5357419403325481346"; Name = "TestTopic " + String(New UUID); - + Result = OPI_Telegram.CreateForumThread(Token, Chat, Name, Icon); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CreateForumThread", "Telegram"); - + Topic = Result["result"]["message_thread_id"]; - + FunctionParameters.Insert("Telegram_TopicID", Topic); OPI_Tools.AddField("Telegram_TopicID", Topic, "String", FunctionParameters); OPI_TestDataRetrieval.WriteParameter("Telegram_TopicID", FunctionParameters["Telegram_TopicID"]); - + Check_TelegramCreateTopic(Result, Name, Icon); - + ChatTopic = Chat + "*" + Topic; - Text = FunctionParameters["String"]; + Text = FunctionParameters["String"]; Result = OPI_Telegram.SendTextMessage(Token, ChatTopic, Text); - + OPI_TestDataRetrieval.WriteLog(Result, "SendTextMessage (forum)"); - + Check_TelegramMessage(Result, Text); - + EndProcedure Procedure Telegram_EditForumTopic(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - Chat = FunctionParameters["Telegram_ForumID"]; - Topic = FunctionParameters["Telegram_TopicID"]; + Token = FunctionParameters["Telegram_Token"]; + Chat = FunctionParameters["Telegram_ForumID"]; + Topic = FunctionParameters["Telegram_TopicID"]; NewName = "NewTestTitle"; NewIcon = "5310132165583840589"; Result = OPI_Telegram.EditForumTopic(Token, Chat, Topic, NewName, NewIcon); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "EditForumTopic", "Telegram"); - + Check_TelegramTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_CloseForumTopic(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - Chat = FunctionParameters["Telegram_ForumID"]; + Token = FunctionParameters["Telegram_Token"]; + Chat = FunctionParameters["Telegram_ForumID"]; Topic = FunctionParameters["Telegram_TopicID"]; OPI_Telegram.OpenForumThread(Token, Chat); // SKIP - + Result = OPI_Telegram.CloseForumThread(Token, Chat); // Closes main topic - + OPI_TestDataRetrieval.WriteLog(Result, "CloseForumTopic (main)"); - + Check_TelegramTrue(Result); // SKIP - + Result = OPI_Telegram.CloseForumThread(Token, Chat, Topic); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CloseForumThread", "Telegram"); - + Check_TelegramTrue(Result); - + OPI_Tools.Pause(25); - + EndProcedure Procedure Telegram_OpenForumTopic(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - Chat = FunctionParameters["Telegram_ForumID"]; + Token = FunctionParameters["Telegram_Token"]; + Chat = FunctionParameters["Telegram_ForumID"]; Topic = FunctionParameters["Telegram_TopicID"]; Result = OPI_Telegram.OpenForumThread(Token, Chat); // Opens main topic - + OPI_TestDataRetrieval.WriteLog(Result, "OpenForumTopic (main)"); - + Check_TelegramTrue(Result); // SKIP - + Result = OPI_Telegram.OpenForumThread(Token, Chat, Topic); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "OpenForumThread", "Telegram"); - + Check_TelegramTrue(Result); - + OPI_Tools.Pause(25); - + EndProcedure Procedure Telegram_DeleteForumTopic(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - Chat = FunctionParameters["Telegram_ForumID"]; + Token = FunctionParameters["Telegram_Token"]; + Chat = FunctionParameters["Telegram_ForumID"]; Topic = FunctionParameters["Telegram_TopicID"]; - - Result = OPI_Telegram.DeleteForumTopic(Token, Chat, Topic); - + + Result = OPI_Telegram.DeleteForumTopic(Token, Chat, Topic); + // END - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteForumTopic", "Telegram"); - + Check_TelegramTrue(Result); - + OPI_Tools.Pause(25); - + EndProcedure Procedure Telegram_ClearPinnedMessagesList(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - Chat = FunctionParameters["Telegram_ForumID"]; + Token = FunctionParameters["Telegram_Token"]; + Chat = FunctionParameters["Telegram_ForumID"]; Topic = FunctionParameters["Telegram_TopicID"]; - + Result = OPI_Telegram.ClearThreadPinnedMessagesList(Token, Chat); - + OPI_TestDataRetrieval.WriteLog(Result, "ClearPinnedMessagesList (main)"); - + Check_TelegramTrue(Result); // SKIP - + Result = OPI_Telegram.ClearThreadPinnedMessagesList(Token, Chat, Topic); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "ClearThreadPinnedMessagesList", "Telegram"); - + Check_TelegramTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_HideMainForumTopic(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; + Token = FunctionParameters["Telegram_Token"]; Chat = FunctionParameters["Telegram_ForumID"]; - + Result = OPI_Telegram.HideMainForumTopic(Token, Chat); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "HideMainForumTopic", "Telegram"); - + Check_TelegramTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_ShowMainForumTopic(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; + Token = FunctionParameters["Telegram_Token"]; Chat = FunctionParameters["Telegram_ForumID"]; - + Result = OPI_Telegram.ShowMainForumTopic(Token, Chat); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "ShowMainForumTopic", "Telegram"); - + Check_TelegramTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_ChangeMainTopicName(FunctionParameters) - Title = "New main thread name " + String(New UUID); - Token = FunctionParameters["Telegram_Token"]; - Chat = FunctionParameters["Telegram_ForumID"]; - + Title = "New main thread name " + String(New UUID); + Token = FunctionParameters["Telegram_Token"]; + Chat = FunctionParameters["Telegram_ForumID"]; + Result = OPI_Telegram.EditMainForumTopicName(Token, Chat, Title); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "EditMainForumTopicName", "Telegram"); - + Check_TelegramTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_DeleteMessage(FunctionParameters) - - Token = FunctionParameters["Telegram_Token"]; - ChatID = FunctionParameters["Telegram_ChannelID"]; + + Token = FunctionParameters["Telegram_Token"]; + ChatID = FunctionParameters["Telegram_ChannelID"]; MessageID = FunctionParameters["Telegram_ChannelMessageID"]; - + Result = OPI_Telegram.DeleteMessage(Token, ChatID, MessageID); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteMessage", "Telegram"); - + Check_TelegramTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure #EndRegion @@ -4665,373 +4665,373 @@ EndProcedure Procedure VK_CreateTokenRetrievalLink(FunctionParameters) Application = FunctionParameters["VK_AppID"]; - Result = OPI_VK.CreateTokenRetrievalLink(Application); - + Result = OPI_VK.CreateTokenRetrievalLink(Application); + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CreateTokenRetrievalLink", "VK"); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("String").Заполнено(); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_CreatePost(FunctionParameters) - + Parameters = GetVKParameters(); - Text = "Post from autotest"; - URL = "https://github.com/Bayselonarrend/OpenIntegrations"; - - Image = FunctionParameters["Picture"]; // URL, Path or Binary Data + Text = "Post from autotest"; + URL = "https://github.com/Bayselonarrend/OpenIntegrations"; + + Image = FunctionParameters["Picture"]; // URL, Path or Binary Data Image2 = FunctionParameters["Picture2"]; // URL, Path or Binary Data - - TFN = GetTempFileName("png"); + + TFN = GetTempFileName("png"); CopyFile(Image2, TFN); - + ImageArray = New Array; ImageArray.Add(Image); ImageArray.Add(TFN); - + Result = OPI_VK.CreatePost(Text, ImageArray, True, URL, Parameters); - + OPI_TestDataRetrieval.WriteLog(Result, "CreatePost", "VK"); Check_VKPost(Result); // SKIP PostID = Result["response"]["post_id"]; // SKIP Result = OPI_VK.DeletePost(PostID, Parameters); // SKIP - + Result = OPI_VK.CreatePost(Text, Image, False , , Parameters); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CreatePost (one picture)"); - Check_VKPost(Result); - - PostID = Result["response"]["post_id"]; - Result = OPI_VK.DeletePost(PostID, Parameters); - - OPI_Tools.Pause(5); - + Check_VKPost(Result); + + PostID = Result["response"]["post_id"]; + Result = OPI_VK.DeletePost(PostID, Parameters); + + OPI_Tools.Pause(5); + Result = OPI_VK.CreatePost(Text, TFN , True, URL, Parameters); - + OPI_TestDataRetrieval.WriteLog(Result, "CreatePost (one path)"); - Check_VKPost(Result); - + Check_VKPost(Result); + PostID = Result["response"]["post_id"]; OPI_Tools.AddField("VK_PostID", PostID, "String", FunctionParameters); OPI_TestDataRetrieval.WriteParameter("VK_PostID", FunctionParameters["VK_PostID"]); - + DeleteFiles(TFN); OPI_Tools.Pause(5); - + EndProcedure Procedure VK_DeletePost(FunctionParameters) - + Parameters = GetVKParameters(); - PostID = FunctionParameters["VK_PostID"]; - + PostID = FunctionParameters["VK_PostID"]; + Result = OPI_VK.DeletePost(PostID, Parameters); // END OPI_TestDataRetrieval.WriteLog(Result, "DeletePost", "VK"); - + Check_VKTrue(Result); - + EndProcedure Procedure VK_CreateCompositePost(FunctionParameters) Parameters = GetVKParameters(); - Text = "Post from autotest"; - URL = "https://github.com/Bayselonarrend/OpenIntegrations"; - + Text = "Post from autotest"; + URL = "https://github.com/Bayselonarrend/OpenIntegrations"; + Image = FunctionParameters["Picture"]; // URL, Path or Binary Data Video = FunctionParameters["Video"]; // URL, Path or Binary Data - - TFN = GetTempFileName("png"); + + TFN = GetTempFileName("png"); CopyFile(Image, TFN); - + ImageUpload = OPI_VK.UploadPhotoToServer(TFN, Parameters)["response"][0]; VideoUpload = OPI_VK.UploadVideoToServer(Video, "NewVideo", , , Parameters); - + ImageOwner = OPI_Tools.NumberToString(ImageUpload["owner_id"]); VideoOwner = OPI_Tools.NumberToString(VideoUpload["owner_id"]); - + ImageID = OPI_Tools.NumberToString(ImageUpload["id"]); VideoID = OPI_Tools.NumberToString(VideoUpload["video_id"]); - + AttachmentsArray = New Array; AttachmentsArray.Add("photo" + ImageOwner + "_" + ImageID); AttachmentsArray.Add("video" + VideoOwner + "_" + VideoID); - + Result = OPI_VK.CreateCompositePost(Text, AttachmentsArray, False, URL, Parameters); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CreateCompositePost", "VK"); - + Check_VKPost(Result); - DeleteFiles(TFN); - + DeleteFiles(TFN); + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_CreatePoll() Parameters = GetVKParameters(); - Question = "What's your favorite color?"; - + Question = "What's your favorite color?"; + OptionArray = New Array; OptionArray.Add("Red"); OptionArray.Add("Yellow"); OptionArray.Add("Green"); - + Result = OPI_VK.CreatePoll(Question, OptionArray, , Parameters); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CreatePoll", "VK"); - + Check_VKPost(Result); - + PostID = Result["response"]["post_id"]; OPI_VK.DeletePost(PostID, Parameters); - + OPI_Tools.Pause(10); - + EndProcedure Procedure VK_CreateAlbum(FunctionParameters) - - Parameters = GetVKParameters(); - Name = "AlbumFromAutoTest"; + + Parameters = GetVKParameters(); + Name = "AlbumFromAutoTest"; Description = "NewAlbumFromAutoTest"; - + Result = OPI_VK.CreateAlbum(Name, Description, Parameters); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CreateAlbum", "VK"); - + Check_VKAlbum(Result, Description); - + AlbumID = Result["response"]["id"]; FunctionParameters.Insert("VK_AlbumID", AlbumID); OPI_TestDataRetrieval.WriteParameter("VK_AlbumID", AlbumID); - + EndProcedure Procedure VK_SavePictureToAlbum(FunctionParameters) - - Parameters = GetVKParameters(); + + Parameters = GetVKParameters(); ImageDescription = "AutoTestImage"; - AlbumID = FunctionParameters["VK_AlbumID"]; - + AlbumID = FunctionParameters["VK_AlbumID"]; + Image = FunctionParameters["Picture"]; // URL, Path to file or Binary Data - TFN = GetTempFileName("png"); + TFN = GetTempFileName("png"); CopyFile(Image, TFN); - + Image = New BinaryData(TFN); - + Result = OPI_VK.SaveImageToAlbum(AlbumID, Image, ImageDescription, Parameters); - + OPI_TestDataRetrieval.WriteLog(Result, "SaveImageToAlbum", "VK"); - + Check_VKAlbumPicture(Result, ImageDescription, AlbumID); // SKIP - + ImageID = Result["response"][0]["id"]; // SKIP - Result = OPI_VK.DeleteImage(ImageID, Parameters); // SKIP - + Result = OPI_VK.DeleteImage(ImageID, Parameters); // SKIP + Result = OPI_VK.SaveImageToAlbum(AlbumID, TFN, ImageDescription, Parameters); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "SavePictureToAlbum (path)"); - + Check_VKAlbumPicture(Result, ImageDescription, AlbumID); // SKIP - + ImageID = Result["response"][0]["id"]; FunctionParameters.Insert("VK_PictureID", ImageID); OPI_TestDataRetrieval.WriteParameter("VK_PictureID", ImageID); - + DeleteFiles(TFN); OPI_Tools.Pause(5); - + EndProcedure Procedure VK_DeleteImage(FunctionParameters) - + Parameters = GetVKParameters(); - ImageID = FunctionParameters["VK_PictureID"]; - + ImageID = FunctionParameters["VK_PictureID"]; + Result = OPI_VK.DeleteImage(ImageID, Parameters); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteImage", "VK"); - + Check_VKTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_DeleteAlbum(FunctionParameters) - + Parameters = GetVKParameters(); - AlbumID = FunctionParameters["VK_AlbumID"]; - + AlbumID = FunctionParameters["VK_AlbumID"]; + Result = OPI_VK.DeleteAlbum(AlbumID, Parameters); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteAlbum", "VK"); - + Check_VKTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_CreateStory(FunctionParameters) Parameters = GetVKParameters(); - URL = "https://github.com/Bayselonarrend/OpenIntegrations"; + URL = "https://github.com/Bayselonarrend/OpenIntegrations"; Image = FunctionParameters["Picture"]; // URL, Path to file or Binary Data - TFN = GetTempFileName("png"); + TFN = GetTempFileName("png"); CopyFile(Image, TFN); Image = New BinaryData(TFN); - + Result = OPI_VK.CreateStory(Image , URL, Parameters); OPI_TestDataRetrieval.WriteLog(Result, "CreateStory", "VK"); - + Check_VKStory(Result); // SKIP - + Result = OPI_VK.CreateStory(TFN, , Parameters); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CreateStory (path)"); - + Check_VKStory(Result); - + DeleteFiles(TFN); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_CreateDiscussion(FunctionParameters) Parameters = GetVKParameters(); - Name = "Discussing: Which color is better?"; - Message = "Red, yellow, blue, or some other?"; - + Name = "Discussing: Which color is better?"; + Message = "Red, yellow, blue, or some other?"; + Result = OPI_VK.CreateDiscussion(Name, Message, Parameters); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CreateDiscussion", "VK"); - + Check_VKDiscussion(Result); - + DiscussionID = Result["response"]; FunctionParameters.Insert("VK_ConvID", DiscussionID); - OPI_TestDataRetrieval.WriteParameter("VK_ConvID", DiscussionID); - + OPI_TestDataRetrieval.WriteParameter("VK_ConvID", DiscussionID); + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_CloseDiscussion(FunctionParameters) - - Parameters = GetVKParameters(); + + Parameters = GetVKParameters(); DiscussionID = FunctionParameters["VK_ConvID"]; - Result = OPI_VK.CloseDiscussion(DiscussionID, False, Parameters); - + Result = OPI_VK.CloseDiscussion(DiscussionID, False, Parameters); + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CloseDiscussion", "VK"); - + Check_VKTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_OpenDiscussion(FunctionParameters) - - Parameters = GetVKParameters(); + + Parameters = GetVKParameters(); DiscussionID = FunctionParameters["VK_ConvID"]; - Result = OPI_VK.OpenDiscussion(DiscussionID, Parameters); - + Result = OPI_VK.OpenDiscussion(DiscussionID, Parameters); + // END - + OPI_TestDataRetrieval.WriteLog(Result, "OpenDiscussion", "VK"); - + Check_VKTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_PostToDiscussion(FunctionParameters) - - Parameters = GetVKParameters(); + + Parameters = GetVKParameters(); DiscussionID = FunctionParameters["VK_ConvID"]; - Message = "I like yellow more"; - + Message = "I like yellow more"; + Result = OPI_VK.WriteInDiscussion(DiscussionID, Message, Parameters); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "WriteInDiscussion", "VK"); - + Check_VKDiscussion(Result); - + EndProcedure Procedure VK_LikePost(FunctionParameters) Parameters = GetVKParameters(); - PostID = FunctionParameters["VK_PostID"]; - + PostID = FunctionParameters["VK_PostID"]; + Result = OPI_VK.LikePost(PostID, , Parameters); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "LikePost", "VK"); - + Check_VKLike(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_MakeRepost(FunctionParameters) - + Parameters = GetVKParameters(); - PostID = 2571; - WallID = -218704372; - + PostID = 2571; + WallID = -218704372; + Result = OPI_VK.MakeRepost(PostID, WallID, , , Parameters); // END - + OPI_TestDataRetrieval.WriteLog(Result, "MakeRepost", "VK"); - + Check_VKRepost(Result); - + FunctionParameters.Insert("Repost", Result["response"]["post_id"]); - + OPI_Tools.Pause(5); EndProcedure @@ -5039,81 +5039,81 @@ EndProcedure Procedure VK_WriteComment(FunctionParameters) Parameters = GetVKParameters(); - Text = "NewComment"; - PostID = FunctionParameters["VK_PostID"]; - WallID = Parameters["owner_id"]; - + Text = "NewComment"; + PostID = FunctionParameters["VK_PostID"]; + WallID = Parameters["owner_id"]; + Result = OPI_VK.WriteComment(PostID, WallID, Text, Parameters); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "WriteComment", "VK"); - + Check_VKComment(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_GetStatistics(FunctionParameters) Parameters = GetVKParameters(); - + CurrentDate = OPI_Tools.GetCurrentDate(); - StartDate = BegOfDay(CurrentDate); - EndDate = EndOfDay(StartDate); - + StartDate = BegOfDay(CurrentDate); + EndDate = EndOfDay(StartDate); + Result = OPI_VK.GetStatistics(StartDate, EndDate, Parameters); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetStatistics", "VK"); - + Check_VKStatistic(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_GetPostStatistics(FunctionParameters) Parameters = GetVKParameters(); - + ArrayOfPosts = New Array; ArrayOfPosts.Add(214); ArrayOfPosts.Add(215); - + Result = OPI_VK.GetPostStatistics(ArrayOfPosts, Parameters); // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetPostStatistics", "VK"); - + Check_VKPostsStatistic(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_CreateAdCampaign(FunctionParameters) Parameters = GetVKParameters(); - + AccountID = FunctionParameters["VK_AdsCabinetID"]; - Name = "New campaign"; - + Name = "New campaign"; + Result = OPI_VK.CreateAdvertisingCampaign(AccountID, Name, Parameters); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CreateAdvertisingCampaign", "VK"); - + Check_Map(Result); - + CampaignID = Result["response"][0]["id"]; OPI_TestDataRetrieval.WriteParameter("VK_AdsCampaignID", CampaignID); FunctionParameters.Insert("VK_AdsCampaignID", CampaignID); - + EndProcedure Procedure VK_CreateAd(FunctionParameters) @@ -5121,260 +5121,260 @@ Procedure VK_CreateAd(FunctionParameters) Parameters = GetVKParameters(); CampaignNumber = FunctionParameters["VK_AdsCampaignID"]; - DailyLimit = 150; + DailyLimit = 150; CategoryNumber = 126; - PostID = FunctionParameters["VK_PostID"]; - AccountID = FunctionParameters["VK_AdsCabinetID"]; - + PostID = FunctionParameters["VK_PostID"]; + AccountID = FunctionParameters["VK_AdsCabinetID"]; + Result = OPI_VK.CreateAd(CampaignNumber , DailyLimit , CategoryNumber , PostID , AccountID , Parameters); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CreateAd", "VK"); - + Check_Map(Result); - + AnnouncementID = Result["response"][0]["id"]; OPI_TestDataRetrieval.WriteParameter("VK_AdsPostID", AnnouncementID); FunctionParameters.Insert("VK_AdsPostID", AnnouncementID); - + EndProcedure Procedure VK_PauseAdvertising(FunctionParameters) Parameters = GetVKParameters(); - + AccountID = FunctionParameters["VK_AdsCabinetID"]; - AdID = FunctionParameters["VK_AdsPostID"]; - + AdID = FunctionParameters["VK_AdsPostID"]; + Result = OPI_VK.PauseAdvertising(AccountID, AdID, Parameters); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "PauseAdvertising", "VK"); - + Check_Map(Result); - + EndProcedure Procedure VK_FormKeyboard(FunctionParameters) ButtonArray = New Array; ButtonArray.Add("Button 1"); - ButtonArray.Add("Button 2"); - + ButtonArray.Add("Button 2"); + Keyboard = OPI_VK.FormKeyboard(ButtonArray); - + // END - + Check_String(Keyboard); - + EndProcedure Procedure VK_WriteMessage(FunctionParameters) Parameters = GetVKParameters(); - - Text = "Message from autotest"; - UserID = FunctionParameters["VK_UserID"]; + + Text = "Message from autotest"; + UserID = FunctionParameters["VK_UserID"]; Communitytoken = FunctionParameters["VK_CommunityToken"]; - + ButtonArray = New Array; ButtonArray.Add("Button 1"); - ButtonArray.Add("Button 2"); - + ButtonArray.Add("Button 2"); + Keyboard = OPI_VK.FormKeyboard(ButtonArray); - Result = OPI_VK.WriteMessage(Text, UserID, Communitytoken, Keyboard, Parameters); - + Result = OPI_VK.WriteMessage(Text, UserID, Communitytoken, Keyboard, Parameters); + // END - + OPI_TestDataRetrieval.WriteLog(Result, "WriteMessage", "VK"); - - Check_VKNumber(Result); - + + Check_VKNumber(Result); + EndProcedure Procedure VK_GetProductCategoryList(FunctionParameters) Parameters = GetVKParameters(); - + Result = OPI_VK.GetProductCategoryList(Parameters); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetProductCategoryList", "VK"); - + Check_Map(Result); - + EndProcedure Procedure CreateProductCollection(FunctionParameters) Parameters = GetVKParameters(); - - Name = "TestCollection"; - Image = FunctionParameters["Picture"]; - Main = True; + + Name = "TestCollection"; + Image = FunctionParameters["Picture"]; + Main = True; Hidden = False; - + Result = OPI_VK.CreateProductCollection(Name , Image , Main , Hidden - , Parameters); - + , Parameters); + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CreateProductCollection", "VK"); - + Check_VKCollection(Result); - + OPI_Tools.Pause(5); - + SelectionID = Result["response"]["market_album_id"]; OPI_TestDataRetrieval.WriteParameter("VK_MarketAlbumID", SelectionID); FunctionParameters.Insert("VK_MarketAlbumID", SelectionID); - + EndProcedure Procedure EditProductCollection(FunctionParameters) Parameters = GetVKParameters(); - - Name = "EditedCollection"; - Selection = FunctionParameters["VK_MarketAlbumID"]; - + + Name = "EditedCollection"; + Selection = FunctionParameters["VK_MarketAlbumID"]; + Result = OPI_VK.EditProductCollection(Name, Selection, , , , Parameters); - + OPI_TestDataRetrieval.WriteLog(Result, "EditProductCollection", "VK"); - + Check_VKTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_AddProduct(FunctionParameters) Parameters = GetVKParameters(); - - Image1 = FunctionParameters["Picture"]; // URL, Path to file or binary Data - Image2 = FunctionParameters["Picture2"]; // URL, Path to file or binary Data - Selection = FunctionParameters["VK_MarketAlbumID"]; - + + Image1 = FunctionParameters["Picture"]; // URL, Path to file or binary Data + Image2 = FunctionParameters["Picture2"]; // URL, Path to file or binary Data + Selection = FunctionParameters["VK_MarketAlbumID"]; + ImageArray = New Array; ImageArray.Add(Image1); ImageArray.Add(Image2); - + ProductDescription = New Map(); - ProductDescription.Insert("Name" , "TestProduct"); - ProductDescription.Insert("Description" , "Product description"); - ProductDescription.Insert("Category" , "20173"); - ProductDescription.Insert("Price" , 1); - ProductDescription.Insert("OldPrice" , 15); - ProductDescription.Insert("MainPhoto" , Image1); - ProductDescription.Insert("URL" , "https://github.com/Bayselonarrend/OpenIntegrations"); - ProductDescription.Insert("AdditionalPhotos" , ImageArray); - ProductDescription.Insert("MainInGroup" , True); - ProductDescription.Insert("Width" , 20); - ProductDescription.Insert("Height" , 30); - ProductDescription.Insert("Depth" , 40); - ProductDescription.Insert("Weight" , 100); - ProductDescription.Insert("SKU" , "12345"); + ProductDescription.Insert("Name" , "TestProduct"); + ProductDescription.Insert("Description" , "Product description"); + ProductDescription.Insert("Category" , "20173"); + ProductDescription.Insert("Price" , 1); + ProductDescription.Insert("OldPrice" , 15); + ProductDescription.Insert("MainPhoto" , Image1); + ProductDescription.Insert("URL" , "https://github.com/Bayselonarrend/OpenIntegrations"); + ProductDescription.Insert("AdditionalPhotos" , ImageArray); + ProductDescription.Insert("MainInGroup" , True); + ProductDescription.Insert("Width" , 20); + ProductDescription.Insert("Height" , 30); + ProductDescription.Insert("Depth" , 40); + ProductDescription.Insert("Weight" , 100); + ProductDescription.Insert("SKU" , "12345"); ProductDescription.Insert("AvailableBalance" , "10"); - - Result = OPI_VK.AddProduct(ProductDescription, Selection, Parameters); - - // END - + + Result = OPI_VK.AddProduct(ProductDescription, Selection, Parameters); + + // END + OPI_TestDataRetrieval.WriteLog(Result, "AddProduct", "VK"); - + Check_VKProduct(Result); - + ProductID = Result["response"]["market_item_id"]; OPI_TestDataRetrieval.WriteParameter("VK_MarketItemID", ProductID); FunctionParameters.Insert("VK_MarketItemID", ProductID); - + EndProcedure Procedure VK_EditProduct(FunctionParameters) Parameters = GetVKParameters(); - - Product = FunctionParameters["VK_MarketItemID"]; - + + Product = FunctionParameters["VK_MarketItemID"]; + ProductDescription = New Map; ProductDescription.Insert("Name", "EditedTestProduct"); - + Result = OPI_VK.EditProduct(Product, ProductDescription, , Parameters); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "EditProduct", "VK"); - + Check_VKTrue(Result); - + EndProcedure Procedure VK_AddProductToCollection(FunctionParameters) Parameters = GetVKParameters(); - - Product = FunctionParameters["VK_MarketItemID"]; + + Product = FunctionParameters["VK_MarketItemID"]; Selection = FunctionParameters["VK_MarketAlbumID"]; - + Result = OPI_VK.AddProductToCollection(Product, Selection, Parameters); - - // END - + + // END + OPI_TestDataRetrieval.WriteLog(Result, "AddProductToCollection", "VK"); - + Check_VKNumber(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_RemoveProductFromCollection(FunctionParameters) Parameters = GetVKParameters(); - - Product = FunctionParameters["VK_MarketItemID"]; + + Product = FunctionParameters["VK_MarketItemID"]; Selection = FunctionParameters["VK_MarketAlbumID"]; - - Result = OPI_VK.RemoveProductFromSelection(Product, Selection, Parameters); - + + Result = OPI_VK.RemoveProductFromSelection(Product, Selection, Parameters); + // END - + OPI_TestDataRetrieval.WriteLog(Result, "RemoveProductFromSelection", "VK"); - + Check_VKTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_DeleteProduct(FunctionParameters) Parameters = GetVKParameters(); - + Product = FunctionParameters["VK_MarketItemID"]; - + Result = OPI_VK.DeleteProduct(Product, Parameters); - - // END - + + // END + OPI_TestDataRetrieval.WriteLog(Result, "DeleteProduct", "VK"); - + Check_VKTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_DeleteCollection(FunctionParameters) @@ -5382,235 +5382,235 @@ Procedure VK_DeleteCollection(FunctionParameters) Parameters = GetVKParameters(); Selection = FunctionParameters["VK_MarketAlbumID"]; - - Result = OPI_VK.DeleteSelection(Selection, Parameters); - + + Result = OPI_VK.DeleteSelection(Selection, Parameters); + // END - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteSelection", "VK"); - + Check_VKTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_CreateProductProperty(FunctionParameters) Parameters = GetVKParameters(); - + Name = "Color"; - + Result = OPI_VK.CreateProductProperty(Name, Parameters); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CreateProductProperty", "VK"); - + Check_VKProp(Result); - + OPI_Tools.Pause(5); - + Property = Result["response"]["property_id"]; Property = OPI_Tools.NumberToString(Property); - + OPI_TestDataRetrieval.WriteParameter("VK_PropID", Property); FunctionParameters.Insert("VK_PropID", Property); - + EndProcedure Procedure VK_EditProductProperty(FunctionParameters) Parameters = GetVKParameters(); - - Name = "Color (change.)"; + + Name = "Color (change.)"; Property = FunctionParameters["VK_PropID"]; - + Result = OPI_VK.EditProductProperty(Name, Property, Parameters); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "EditProductProperty", "VK"); - + OPI_Tools.Pause(5); - + Check_VKTrue(Result); - + EndProcedure Procedure VK_AddProductPropertyVariant(FunctionParameters) - Counter = 1; // SKIP + Counter = 1; // SKIP Parameters = GetVKParameters(); - - Property = FunctionParameters["VK_PropID"]; + + Property = FunctionParameters["VK_PropID"]; OptionArray = New Array; OptionArray.Add("Yellow"); OptionArray.Add("Blue"); OptionArray.Add("Red"); - + For Each Value In OptionArray Do - + Result = OPI_VK.AddProductPropertyVariant(Value, Property, Parameters); - + OPI_TestDataRetrieval.WriteLog(Result, "AddProductPropertyVariant", "VK"); - - Check_VKPropVariant(Result); // SKIP + + Check_VKPropVariant(Result); // SKIP OPI_Tools.Pause(5); // SKIP - - VariantID = Result["response"]["variant_id"]; // SKIP + + VariantID = Result["response"]["variant_id"]; // SKIP ParameterName = "VK_PropVarID" + String(Counter); // SKIP - + OPI_TestDataRetrieval.WriteParameter(ParameterName, VariantID); // SKIP FunctionParameters.Insert(ParameterName, VariantID); Counter = Counter + 1; // SKIP - - EndDo; - + + EndDo; + // END - + EndProcedure Procedure VK_EditProductPropertyVariant(FunctionParameters) - + Parameters = GetVKParameters(); - + Property = FunctionParameters["VK_PropID"]; - Option = FunctionParameters["VK_PropVarID1"]; - Value = "New variant name"; - + Option = FunctionParameters["VK_PropVarID1"]; + Value = "New variant name"; + Result = OPI_VK.EditProductPropertyVariant(Value , Property , Option , Parameters); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "EditProductPropertyVariant", "VK"); - + Check_VKTrue(Result); - + EndProcedure Procedure VK_CreateProductWithProp(FunctionParameters) Parameters = GetVKParameters(); - - Image1 = FunctionParameters["Picture"]; - Image2 = FunctionParameters["Picture2"]; + + Image1 = FunctionParameters["Picture"]; + Image2 = FunctionParameters["Picture2"]; PropVariant1 = FunctionParameters["VK_PropVarID1"]; PropVariant2 = FunctionParameters["VK_PropVarID2"]; - + ImageArray = New Array; ImageArray.Add(Image1); ImageArray.Add(Image2); - + Product = New Map(); - Product.Insert("Name" , "Test product (with prop)"); - Product.Insert("Description" , "Product description"); - Product.Insert("Category" , "20173"); - Product.Insert("Price" , 1); - Product.Insert("OldPrice" , 15); - Product.Insert("MainPhoto" , Image1); - Product.Insert("URL" , "https://github.com/Bayselonarrend/OpenIntegrations"); - Product.Insert("AdditionalPhotos" , ImageArray); - Product.Insert("MainInGroup" , True); - Product.Insert("GroupNumber" , Undefined); - Product.Insert("Width" , 20); - Product.Insert("Height" , 30); - Product.Insert("Depth" , 40); - Product.Insert("Weight" , 100); - Product.Insert("SKU" , 12345); + Product.Insert("Name" , "Test product (with prop)"); + Product.Insert("Description" , "Product description"); + Product.Insert("Category" , "20173"); + Product.Insert("Price" , 1); + Product.Insert("OldPrice" , 15); + Product.Insert("MainPhoto" , Image1); + Product.Insert("URL" , "https://github.com/Bayselonarrend/OpenIntegrations"); + Product.Insert("AdditionalPhotos" , ImageArray); + Product.Insert("MainInGroup" , True); + Product.Insert("GroupNumber" , Undefined); + Product.Insert("Width" , 20); + Product.Insert("Height" , 30); + Product.Insert("Depth" , 40); + Product.Insert("Weight" , 100); + Product.Insert("SKU" , 12345); Product.Insert("AvailableBalance" , "10"); - Product.Insert("PropertyValues" , PropVariant1); - - Result = OPI_VK.AddProduct(Product, , Parameters); - + Product.Insert("PropertyValues" , PropVariant1); + + Result = OPI_VK.AddProduct(Product, , Parameters); + OPI_TestDataRetrieval.WriteLog(Result, "ProductWithProp1"); - + Check_VKProduct(Result); - + ProductID = Result["response"]["market_item_id"]; OPI_TestDataRetrieval.WriteParameter("VK_MarketItemID2", ProductID); FunctionParameters.Insert("VK_MarketItemID2", ProductID); - - Product.Insert("Name" , "Test product (another)"); + + Product.Insert("Name" , "Test product (another)"); Product.Insert("PropertyValues", PropVariant2); - Result = OPI_VK.AddProduct(Product, , Parameters); - + Result = OPI_VK.AddProduct(Product, , Parameters); + OPI_TestDataRetrieval.WriteLog(Result, "ProductWithProp2"); - + Check_VKProduct(Result); - + ProductID = Result["response"]["market_item_id"]; OPI_TestDataRetrieval.WriteParameter("VK_MarketItemID3", ProductID); FunctionParameters.Insert("VK_MarketItemID3", ProductID); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_GetProductsByID(FunctionParameters) Parameters = GetVKParameters(); - + Item1 = FunctionParameters["VK_MarketItemID2"]; Item2 = FunctionParameters["VK_MarketItemID3"]; - + ProductsArray = New Array; ProductsArray.Add(Item1); ProductsArray.Add(Item2); - + Result = OPI_VK.GetProductsByID(ProductsArray, Parameters); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetProductsByID", "VK"); - + Check_VKProductData(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_GroupProducts(FunctionParameters) - + Parameters = GetVKParameters(); - + Item1 = FunctionParameters["VK_MarketItemID2"]; Item2 = FunctionParameters["VK_MarketItemID3"]; - + ProductsArray = New Array; ProductsArray.Add(Item1); ProductsArray.Add(Item2); - + Result = OPI_VK.GroupProducts(ProductsArray, , Parameters); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GroupProducts", "VK"); - + Check_VKProductsGroup(Result); - + OPI_Tools.Pause(5); - + EndProcedure - + Procedure VK_DeleteProductPropertyVariant(FunctionParameters) Parameters = GetVKParameters(); Option = FunctionParameters["VK_PropVarID1"]; - + Result = OPI_VK.DeleteProductPropertyVariant(Option, Parameters); - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteProductPropertyVariant", "VK"); - + Check_VKTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_DeleteProductProperty(FunctionParameters) @@ -5618,93 +5618,93 @@ Procedure VK_DeleteProductProperty(FunctionParameters) Parameters = GetVKParameters(); Property = FunctionParameters["VK_PropID"]; - + Result = OPI_VK.DeleteProductProperty(Property, Parameters); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteProductProperty"); - + OPI_Tools.Pause(5); - + Check_VKTrue(Result); - + EndProcedure Procedure VK_GetProductList(FunctionParameters) - Parameters = GetVKParameters(); - Result = OPI_VK.GetProductList(, Parameters); - + Parameters = GetVKParameters(); + Result = OPI_VK.GetProductList(, Parameters); + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetProductList", "VK"); - + Check_Array(Result); OPI_Tools.Pause(5); - + EndProcedure Procedure VK_GetSelectionList(FunctionParameters) - Parameters = GetVKParameters(); - Result = OPI_VK.GetSelectionList(Parameters); - + Parameters = GetVKParameters(); + Result = OPI_VK.GetSelectionList(Parameters); + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetSelectionList", "VK"); - + Check_Array(Result); OPI_Tools.Pause(5); - + EndProcedure Procedure VK_GetPropertyList(FunctionParameters) - Parameters = GetVKParameters(); - Result = OPI_VK.GetPropertyList(Parameters); - + Parameters = GetVKParameters(); + Result = OPI_VK.GetPropertyList(Parameters); + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetPropertyList", "VK"); - + Check_Array(Result); OPI_Tools.Pause(5); - + EndProcedure Procedure VK_GetOrderList(FunctionParameters) Parameters = GetVKParameters(); - Result = OPI_VK.GetOrderList(Parameters); - + Result = OPI_VK.GetOrderList(Parameters); + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetOrderList", "VK"); - + Check_Array(Result); OPI_Tools.Pause(5); - + EndProcedure Procedure VK_UploadVideoToServer(FunctionParameters) - + Parameters = GetVKParameters(); - - Video = FunctionParameters["Video"]; - Name = "NewVideo"; + + Video = FunctionParameters["Video"]; + Name = "NewVideo"; Description = "Video description"; - + Result = OPI_VK.UploadVideoToServer(Video, Name, Description, , Parameters); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "UploadVideoToServer", "VK"); - + Check_VKVideo(Result); - + OPI_Tools.Pause(5); - + EndProcedure #EndRegion @@ -5715,554 +5715,554 @@ Procedure Dropbox_GetAuthorizationLink(FunctionParameters) AppKey = FunctionParameters["Dropbox_Appkey"]; Result = OPI_Dropbox.GetAuthorizationLink(AppKey); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetAuthorizationLink", "Dropbox"); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("String"); - + EndProcedure Procedure Dropbox_GetToken(FunctionParameters) - - AppKey = FunctionParameters["Dropbox_Appkey"]; + + AppKey = FunctionParameters["Dropbox_Appkey"]; AppSecret = FunctionParameters["Dropbox_Appsecret"]; - Code = FunctionParameters["Dropbox_Code"]; + Code = FunctionParameters["Dropbox_Code"]; Result = OPI_Dropbox.GetToken(AppKey, AppSecret, Code); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetToken"); - - Token = Result["access_token"]; + + Token = Result["access_token"]; Refresh = Result["refresh_token"]; - + If ValueIsFilled(Token) Then OPI_TestDataRetrieval.WriteParameter("Dropbox_Token", Token); EndIf; - + If ValueIsFilled(Refresh) Then OPI_TestDataRetrieval.WriteParameter("Dropbox_Refresh", Refresh); EndIf; - + EndProcedure Procedure Dropbox_UpdateToken(FunctionParameters) - AppKey = FunctionParameters["Dropbox_Appkey"]; - AppSecret = FunctionParameters["Dropbox_Appsecret"]; + AppKey = FunctionParameters["Dropbox_Appkey"]; + AppSecret = FunctionParameters["Dropbox_Appsecret"]; RefreshToken = FunctionParameters["Dropbox_Refresh"]; - + Result = OPI_Dropbox.RefreshToken(AppKey, AppSecret, RefreshToken); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "RefreshToken"); - + Token = Result["access_token"]; - + OPI_TestDataRetrieval.ExpectsThat(Token).Заполнено(); OPI_TestDataRetrieval.WriteParameter("Dropbox_Token", Token); - + EndProcedure Procedure Dropbox_GetObjectInformation(FunctionParameters) - - Path = "/New/pic.png"; + + Path = "/New/pic.png"; Token = FunctionParameters["Dropbox_Token"]; - + Result = OPI_Dropbox.GetObjectInformation(Token, Path, True); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetObjectInformation", "Dropbox"); Check_DropboxFile(Result, Path); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_GetPreview(FunctionParameters) - + Token = FunctionParameters["Dropbox_Token"]; - Path = "/New/mydoc.docx"; - + Path = "/New/mydoc.docx"; + Result = OPI_Dropbox.GetPreview(Token, Path); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetPreview", "Dropbox"); - + Check_BinaryData(Result, 120000); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_UploadFile(FunctionParameters) - Path = "/New/pic.png"; + Path = "/New/pic.png"; Token = FunctionParameters["Dropbox_Token"]; Image = FunctionParameters["Picture"]; - + ImagePath = GetTempFileName("png"); CopyFile(Image, ImagePath); - + Result = OPI_Dropbox.UploadFile(Token, ImagePath, Path, True); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "UploadFile", "Dropbox"); - + Check_DropboxFile(Result, Path); DeleteFiles(ImagePath); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_UploadFileByURL(FunctionParameters) - - Path = "/New/url_doc.docx"; + + Path = "/New/url_doc.docx"; Token = FunctionParameters["Dropbox_Token"]; - URL = FunctionParameters["Document"]; - + URL = FunctionParameters["Document"]; + Result = OPI_Dropbox.UploadFileByURL(Token, URL, Path); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "UploadFileByURL", "Dropbox"); - + Check_DropboxWork(Result); - + Work = Result["async_job_id"]; - + FunctionParameters.Insert("Dropbox_Job", Work); OPI_TestDataRetrieval.WriteParameter("Dropbox_Job", Work); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_GetUploadStatusByURL(FunctionParameters) - Token = FunctionParameters["Dropbox_Token"]; + Token = FunctionParameters["Dropbox_Token"]; WorkID = FunctionParameters["Dropbox_Job"]; - Status = "in_progress"; - - WHile Status = "in_progress" Do - + Status = "in_progress"; + + WHile Status = "in_progress" Do + Result = OPI_Dropbox.GetUploadStatusByURL(Token, WorkID); Status = Result[".tag"]; - + OPI_Tools.Pause(5); - + OPI_TestDataRetrieval.WriteLog(Result, "GetUploadStatusByURL", "Dropbox"); - + EndDo; - + // END - + Check_DropboxStatus(Result); - - Path = "/New/url_doc.docx"; + + Path = "/New/url_doc.docx"; Result = OPI_Dropbox.DeleteObject(Token, Path); - + Check_DropboxMetadata(Result, Path); - OPI_Tools.Pause(5); - + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_DeleteObject(FunctionParameters) - - Path = "/New/pic.png"; - Token = FunctionParameters["Dropbox_Token"]; - + + Path = "/New/pic.png"; + Token = FunctionParameters["Dropbox_Token"]; + Result = OPI_Dropbox.DeleteObject(Token, Path); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteObject", "Dropbox"); Check_DropboxMetadata(Result, Path); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_CopyObject(FunctionParameters) - + Original = "/New/pic.png"; - Copy = "/New/pic_copy.png"; - Token = FunctionParameters["Dropbox_Token"]; - + Copy = "/New/pic_copy.png"; + Token = FunctionParameters["Dropbox_Token"]; + Result = OPI_Dropbox.CopyObject(Token, Original, Copy); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CopyObject", "Dropbox"); - + Check_DropboxMetadata(Result, Copy); - + Result = OPI_Dropbox.DeleteObject(Token, Copy); Check_DropboxMetadata(Result, Copy); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_MoveObject(FunctionParameters) - + OriginalPath = "/New/pic.png"; - TargetPath = "/pic.png"; - Token = FunctionParameters["Dropbox_Token"]; - + TargetPath = "/pic.png"; + Token = FunctionParameters["Dropbox_Token"]; + Result = OPI_Dropbox.MoveObject(Token, OriginalPath, TargetPath); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "MoveObject", "Dropbox"); - + Check_DropboxMetadata(Result, TargetPath); - + Result = OPI_Dropbox.MoveObject(Token, TargetPath, OriginalPath); Check_DropboxMetadata(Result, OriginalPath); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_CreateFolder(FunctionParameters) - + Token = FunctionParameters["Dropbox_Token"]; - Path = "/New catalog"; - + Path = "/New catalog"; + Result = OPI_Dropbox.CreateFolder(Token, Path); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CreateFolder", "Dropbox"); - + Check_DropboxMetadata(Result, Path); - + Result = OPI_Dropbox.DeleteObject(Token, Path); Check_DropboxMetadata(Result, Path); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_DownloadFile(FunctionParameters) Token = FunctionParameters["Dropbox_Token"]; - Path = "/New/pic.png"; - + Path = "/New/pic.png"; + Result = OPI_Dropbox.DownloadFile(Token, Path); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "DownloadFile", "Dropbox"); - + Check_BinaryData(Result, 2000000); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_DownloadFolder(FunctionParameters) - + Token = FunctionParameters["Dropbox_Token"]; - Path = "/New"; - + Path = "/New"; + Result = OPI_Dropbox.DownloadFolder(Token, Path); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "DownloadFolder", "Dropbox"); - + Check_BinaryData(Result); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_GetFolderFileList(FunctionParameters) - - Path = "/New"; + + Path = "/New"; Token = FunctionParameters["Dropbox_Token"]; - + Result = OPI_Dropbox.GetListOfFolderFiles(Token, Path, True); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetListOfFolderFiles", "Dropbox"); Check_DropboxArray(Result); - + OPI_Tools.Pause(5); - -EndProcedure + +EndProcedure Procedure Dropbox_GetObjectVersionList(FunctionParameters) Token = FunctionParameters["Dropbox_Token"]; - Path = "/New/pic.png"; - + Path = "/New/pic.png"; + Result = OPI_Dropbox.GetObjectVersionList(Token, Path, 1); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetObjectVersionList", "Dropbox"); - + Check_DropboxArray(Result, 1); - + Revision = Result["entries"][0]["rev"]; - + FunctionParameters.Insert("Dropbox_FileRevision", Revision); OPI_TestDataRetrieval.WriteParameter("Dropbox_FileRevision", Revision); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_RestoreObjectToVersion(FunctionParameters) - + Version = FunctionParameters["Dropbox_FileRevision"]; - Token = FunctionParameters["Dropbox_Token"]; - Path = "/New/pic.png"; - + Token = FunctionParameters["Dropbox_Token"]; + Path = "/New/pic.png"; + Result = OPI_Dropbox.RestoreObjectToVersion(Token, Path, Version); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "RestoreObjectToVersion", "Dropbox"); - + Check_DropboxFile(Result, Path); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_GetTagList(FunctionParameters) Token = FunctionParameters["Dropbox_Token"]; - + PathsArray = New Array; PathsArray.Add("/New/Dogs.mp3"); - PathsArray.Add("/New/mydoc.docx"); - + PathsArray.Add("/New/mydoc.docx"); + Result = OPI_Dropbox.GetTagList(Token, PathsArray); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetTagList", "Dropbox"); - + Check_DropboxTags(Result, PathsArray.Count()); - + Result = OPI_Dropbox.GetTagList(Token, "/New/mydoc.docx"); - + OPI_TestDataRetrieval.WriteLog(Result, "GetTagList (single)"); - + Check_DropboxTags(Result, 1); - + HasTag = False; - + For Each Tag In Result["paths_to_tags"][0]["tags"] Do If Tag["tag_text"] = "important" Then - HasTag = True; + HasTag = True; EndIf; EndDo; - + OPI_TestDataRetrieval.ExpectsThat(HasTag).Равно(True); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_AddTag(FunctionParameters) - - Tag = "Important"; + + Tag = "Important"; Token = FunctionParameters["Dropbox_Token"]; - Path = "/New/mydoc.docx"; - + Path = "/New/mydoc.docx"; + Result = OPI_Dropbox.AddTag(Token, Path, Tag); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "AddTag", "Dropbox"); - + Check_Empty(Result); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_DeleteTag(FunctionParameters) - - Tag = "Important"; + + Tag = "Important"; Token = FunctionParameters["Dropbox_Token"]; - Path = "/New/mydoc.docx"; - + Path = "/New/mydoc.docx"; + Result = OPI_Dropbox.DeleteTag(Token, Path, Tag); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteTag", "Dropbox"); - + Check_Empty(Result); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_GetAccountInformation(FunctionParameters) - + Token = FunctionParameters["Dropbox_Token"]; - + Result = OPI_Dropbox.GetAccountInformation(Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetAccountInformation", "Dropbox"); - + Check_DropboxAccount(Result); - + Result = OPI_Dropbox.GetAccountInformation(Token, Result["account_id"]); - + OPI_TestDataRetrieval.WriteLog(Result, "GetAccountInformation (third-party)"); - + Check_DropboxAccount(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Dropbox_GetSpaceUsageData(FunctionParameters) - + Token = FunctionParameters["Dropbox_Token"]; - + Result = OPI_Dropbox.GetSpaceUsageData(Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetSpaceUsageData", "Dropbox"); - + Check_DropboxSpace(Result); - + EndProcedure Procedure Dropbox_AddUsersToFile(FunctionParameters) - + Token = FunctionParameters["Dropbox_Token"]; Email = FunctionParameters["Dropbox_OtherUser"]; - File = FunctionParameters["Dropbox_FileID"]; - + File = FunctionParameters["Dropbox_FileID"]; + Result = OPI_Dropbox.AddUsersToFile(Token, File, Email, False); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "AddUsersToFile", "Dropbox"); - + Check_DropboxMember(Result, Email, False); - + Mails = New Array; Mails.Add(Email); - + Result = OPI_Dropbox.AddUsersToFile(Token, File, Mails, True); - + OPI_TestDataRetrieval.WriteLog(Result, "AddUsersToFile (new.) "); - + Check_DropboxMember(Result, Email, True); - + EndProcedure Procedure Dropbox_PublishFolder(FunctionParameters) - + Token = FunctionParameters["Dropbox_Token"]; - Path = "/New"; - + Path = "/New"; + Result = OPI_Dropbox.PublishFolder(Token, Path); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "PublishFolder", "Dropbox"); - + Check_DropboxPublicFolder(Result); - + FolderID = Result["shared_folder_id"]; - + FunctionParameters.Insert("Dropbox_SharedFolder", FolderID); OPI_TestDataRetrieval.WriteParameter("Dropbox_SharedFolder", FolderID); - - OPI_Tools.Pause(5); + + OPI_Tools.Pause(5); EndProcedure Procedure Dropbox_CancelFolderPublication(FunctionParameters) - - Token = FunctionParameters["Dropbox_Token"]; + + Token = FunctionParameters["Dropbox_Token"]; Folder = FunctionParameters["Dropbox_SharedFolder"]; - - Result = OPI_Dropbox.CancelFolderPublication(Token, Folder); + + Result = OPI_Dropbox.CancelFolderPublication(Token, Folder); CurrentStatus = "in_progress"; - JobID = Result["async_job_id"]; - + JobID = Result["async_job_id"]; + WHile CurrentStatus = "in_progress" Do - Result = OPI_Dropbox.GetAsynchronousChangeStatus(Token, JobID); - CurrentStatus = Result[".tag"]; + Result = OPI_Dropbox.GetAsynchronousChangeStatus(Token, JobID); + CurrentStatus = Result[".tag"]; OPI_Tools.Pause(3); EndDo; - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CancelFolderPublication", "Dropbox"); - + Check_DropboxStatus(Result); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_AddUsersToFolder(FunctionParameters) - - Token = FunctionParameters["Dropbox_Token"]; - Email = FunctionParameters["Dropbox_OtherUser"]; + + Token = FunctionParameters["Dropbox_Token"]; + Email = FunctionParameters["Dropbox_OtherUser"]; Folder = FunctionParameters["Dropbox_SharedFolder"]; // shared_folder_id - + Result = OPI_Dropbox.AddUsersToFolder(Token, Folder, Email, False); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "AddUsersToFolder", "Dropbox"); - + Check_Empty(Result); - + Mails = New Array; Mails.Add(Email); - + Result = OPI_Dropbox.AddUsersToFolder(Token, Folder, Mails, True); - + Check_Empty(Result); - + EndProcedure Procedure Dropbox_CancelFilePublication(FunctionParameters) - - Token = FunctionParameters["Dropbox_Token"]; + + Token = FunctionParameters["Dropbox_Token"]; File = FunctionParameters["Dropbox_FileID"]; - + Result = OPI_Dropbox.CancelFilePublication(Token, File); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CancelFilePublication", "Dropbox"); - + Check_Empty(Result); - + EndProcedure #EndRegion @@ -6270,2230 +6270,2230 @@ EndProcedure #Region Bitrix24 Procedure Bitrix24_GetAppAuthLink(FunctionParameters) - - Domain = FunctionParameters["Bitrix24_Domain"]; + + Domain = FunctionParameters["Bitrix24_Domain"]; ClientID = FunctionParameters["Bitrix24_ClientID"]; - + Result = OPI_Bitrix24.GetAppAuthLink(Domain, ClientID); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetAppAuthLink", "Bitrix24"); - + Check_String(Result); - + OPI_TestDataRetrieval.WriteParameter("Bitrix24_AuthURL", Result); EndProcedure Procedure Bitrix24_GetToken(FunctionParameters) - - ClientID = FunctionParameters["Bitrix24_ClientID"]; + + ClientID = FunctionParameters["Bitrix24_ClientID"]; ClientSecret = FunctionParameters["Bitrix24_ClientSecret"]; - Code = FunctionParameters["Bitrix24_Code"]; - + Code = FunctionParameters["Bitrix24_Code"]; + Result = OPI_Bitrix24.GetToken(ClientID, ClientSecret, Code); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetToken", "Bitrix24"); - + If ValueIsFilled(Result["access_token"]) And ValueIsFilled(Result["refresh_token"]) Then - OPI_TestDataRetrieval.WriteParameter("Bitrix24_Token" , Result["access_token"]); + OPI_TestDataRetrieval.WriteParameter("Bitrix24_Token" , Result["access_token"]); OPI_TestDataRetrieval.WriteParameter("Bitrix24_Refresh", Result["refresh_token"]); EndIf; - + EndProcedure Procedure Bitrix24_RefreshToken(FunctionParameters) - - ClientID = FunctionParameters["Bitrix24_ClientID"]; + + ClientID = FunctionParameters["Bitrix24_ClientID"]; ClientSecret = FunctionParameters["Bitrix24_ClientSecret"]; - Refresh = FunctionParameters["Bitrix24_Refresh"]; - + Refresh = FunctionParameters["Bitrix24_Refresh"]; + Result = OPI_Bitrix24.RefreshToken(ClientID, ClientSecret, Refresh); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "RefreshToken", "Bitrix24"); - + Check_BitrixAuth(Result); - + If ValueIsFilled(Result["access_token"]) And ValueIsFilled(Result["refresh_token"]) Then - OPI_TestDataRetrieval.WriteParameter("Bitrix24_Token" , Result["access_token"]); + OPI_TestDataRetrieval.WriteParameter("Bitrix24_Token" , Result["access_token"]); OPI_TestDataRetrieval.WriteParameter("Bitrix24_Refresh", Result["refresh_token"]); EndIf; - + EndProcedure Procedure Bitrix24_ServerTime(FunctionParameters) - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.ServerTime(URL); - + OPI_TestDataRetrieval.WriteLog(Result, "ServerTime (wh)", "Bitrix24"); - + Check_BitrixTime(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.ServerTime(URL, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "ServerTime", "Bitrix24"); - - Check_BitrixTime(Result); - + + Check_BitrixTime(Result); + EndProcedure Procedure Bitrix24_CreatePost(FunctionParameters) - - Text = "Text of post"; - Title = "Post title"; + + Text = "Text of post"; + Title = "Post title"; Image1 = FunctionParameters["Picture"]; // URL, Path or Binary Data Image2 = FunctionParameters["Picture2"]; // URL, Path or Binary Data - + Files = New Map; Files.Insert("1.png", Image1); Files.Insert("2.png", Image2); - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.CreatePost(URL, Text, , Files, Title, True); - + OPI_TestDataRetrieval.WriteLog(Result, "CreatePost (wh)", "Bitrix24"); - + Check_BitrixNumber(Result); // SKIP - + PostID = Result["result"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookPostID", PostID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookPostID", PostID); // SKIP FunctionParameters.Insert("Bitrix24_HookPostID", PostID); // SKIP - URL = FunctionParameters["Bitrix24_Domain"]; + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.CreatePost(URL, Text, , Files, Title, , Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CreatePost", "Bitrix24"); - - Check_BitrixNumber(Result); - + + Check_BitrixNumber(Result); + PostID = Result["result"]; - - OPI_TestDataRetrieval.WriteParameter("Bitrix24_PostID", PostID); + + OPI_TestDataRetrieval.WriteParameter("Bitrix24_PostID", PostID); FunctionParameters.Insert("Bitrix24_PostID", PostID); - + EndProcedure Procedure Bitrix24_UpdatePost(FunctionParameters) - - Text = "New post text"; - Title = "New post title"; + + Text = "New post text"; + Title = "New post title"; Image1 = FunctionParameters["Picture"]; // URL, Path or Binary Data PostID = FunctionParameters["Bitrix24_PostID"]; - + Files = New Map; Files.Insert("1.png", Image1); - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.UpdatePost(URL, PostID, Text, , Files, Title); - + OPI_TestDataRetrieval.WriteLog(Result, "UpdatePost (wh)", "Bitrix24"); - + Check_BitrixNumber(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; PostID = FunctionParameters["Bitrix24_HookPostID"]; - + Result = OPI_Bitrix24.UpdatePost(URL, PostID, Text, , Files, Title, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "UpdatePost", "Bitrix24"); - - Check_BitrixNumber(Result); - + + Check_BitrixNumber(Result); + EndProcedure Procedure Bitrix24_DeletePost(FunctionParameters) - - PostID = FunctionParameters["Bitrix24_HookPostID"]; - URL = FunctionParameters["Bitrix24_URL"]; - + + PostID = FunctionParameters["Bitrix24_HookPostID"]; + URL = FunctionParameters["Bitrix24_URL"]; + Result = OPI_Bitrix24.DeletePost(URL, PostID); - + OPI_TestDataRetrieval.WriteLog(Result, "DeletePost (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - + PostID = FunctionParameters["Bitrix24_PostID"]; - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; - + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; + Result = OPI_Bitrix24.DeletePost(URL, PostID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "DeletePost", "Bitrix24"); - - Check_BitrixTrue(Result); - + + Check_BitrixTrue(Result); + EndProcedure Procedure Bitrix24_GetImportantPostViewers(FunctionParameters) - - PostID = FunctionParameters["Bitrix24_HookPostID"]; - URL = FunctionParameters["Bitrix24_URL"]; - + + PostID = FunctionParameters["Bitrix24_HookPostID"]; + URL = FunctionParameters["Bitrix24_URL"]; + Result = OPI_Bitrix24.GetImportantPostViewers(URL, PostID); - + OPI_TestDataRetrieval.WriteLog(Result, "GetImportantPostViewers (wh)", "Bitrix24"); - + Check_BitrixArray(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetImportantPostViewers(URL, PostID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetImportantPostViewers", "Bitrix24"); - - Check_BitrixArray(Result); - + + Check_BitrixArray(Result); + EndProcedure Procedure Bitrix24_GetPosts(FunctionParameters) - - PostID = FunctionParameters["Bitrix24_PostID"]; - URL = FunctionParameters["Bitrix24_URL"]; - + + PostID = FunctionParameters["Bitrix24_PostID"]; + URL = FunctionParameters["Bitrix24_URL"]; + Result = OPI_Bitrix24.GetPosts(URL, PostID); - + OPI_TestDataRetrieval.WriteLog(Result, "GetPosts (wh)", "Bitrix24"); - + Check_BitrixObjectsArray(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetPosts(URL, PostID, , Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetPosts", "Bitrix24"); - - Check_BitrixObjectsArray(Result); - + + Check_BitrixObjectsArray(Result); + EndProcedure Procedure Bitrix24_AddPostComment(FunctionParameters) - - Text = "Comment for post"; - PostID = FunctionParameters["Bitrix24_PostID"]; - URL = FunctionParameters["Bitrix24_URL"]; - + + Text = "Comment for post"; + PostID = FunctionParameters["Bitrix24_PostID"]; + URL = FunctionParameters["Bitrix24_URL"]; + Result = OPI_Bitrix24.AddPostComment(URL, PostID, Text); - + OPI_TestDataRetrieval.WriteLog(Result, "AddPostComment (wh)", "Bitrix24"); - + Check_BitrixNumber(Result); // SKIP - - Text = "Another comment"; - URL = FunctionParameters["Bitrix24_Domain"]; + + Text = "Another comment"; + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.AddPostComment(URL, PostID, Text, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "AddPostComment", "Bitrix24"); - - Check_BitrixNumber(Result); - + + Check_BitrixNumber(Result); + EndProcedure Procedure Bitrix_AddPostRecipients(FunctionParameters) - + Visibility = "UA"; - PostID = FunctionParameters["Bitrix24_PostID"]; - URL = FunctionParameters["Bitrix24_URL"]; - + PostID = FunctionParameters["Bitrix24_PostID"]; + URL = FunctionParameters["Bitrix24_URL"]; + Result = OPI_Bitrix24.AddPostRecipients(URL, PostID, Visibility); - + OPI_TestDataRetrieval.WriteLog(Result, "AddPostRecipients (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.AddPostRecipients(URL, PostID, Visibility, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "AddPostRecipients", "Bitrix24"); - - Check_BitrixTrue(Result); - + + Check_BitrixTrue(Result); + EndProcedure Procedure Bitrix24_GetTaskFieldsStructure(FunctionParameters) - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.GetTaskFieldsStructure(URL); - + OPI_TestDataRetrieval.WriteLog(Result, "GetTaskFieldsStructure (wh)", "Bitrix24"); - + Check_BitrixFields(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetTaskFieldsStructure(URL, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetTaskFieldsStructure", "Bitrix24"); - - Check_BitrixFields(Result); - + + Check_BitrixFields(Result); + EndProcedure Procedure Bitrix24_CreateTask(FunctionParameters) - + // The complete structure of the fields can be obtained by the GetTaskFieldsStructure() function() - + CurrentDate = OPI_Tools.GetCurrentDate(); - Hour = 3600; - Day = 24; + Hour = 3600; + Day = 24; Responsible = 1; - + TaskData = New Structure; - TaskData.Insert("TITLE" , "New task"); - TaskData.Insert("DESCRIPTION" , "New task description"); - TaskData.Insert("PRIORITY" , "2"); - TaskData.Insert("DEADLINE" , CurrentDate + Hour * Day); + TaskData.Insert("TITLE" , "New task"); + TaskData.Insert("DESCRIPTION" , "New task description"); + TaskData.Insert("PRIORITY" , "2"); + TaskData.Insert("DEADLINE" , CurrentDate + Hour * Day); TaskData.Insert("RESPONSIBLE_ID", Responsible); - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.CreateTask(URL, TaskData); - + OPI_TestDataRetrieval.WriteLog(Result, "CreateTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - + TaskID = Result["result"]["task"]["id"]; // SKIP - - OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookTaskID", TaskID); // SKIP + + OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookTaskID", TaskID); // SKIP FunctionParameters.Insert("Bitrix24_HookTaskID", TaskID); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.CreateTask(URL, TaskData, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CreateTask", "Bitrix24"); - - Check_BitrixTask(Result); - + + Check_BitrixTask(Result); + TaskID = Result["result"]["task"]["id"]; - - OPI_TestDataRetrieval.WriteParameter("Bitrix24_TaskID", TaskID); + + OPI_TestDataRetrieval.WriteParameter("Bitrix24_TaskID", TaskID); FunctionParameters.Insert("Bitrix24_TaskID", TaskID); - + OPI_Tools.Pause(5); EndProcedure Procedure Bitrix24_UpdateTask(FunctionParameters) - + // The complete structure of the fields can be obtained by the GetTaskFieldsStructure() function() - + TaskData = New Structure; - TaskData.Insert("TITLE", "Another task title"); + TaskData.Insert("TITLE" , "Another task title"); TaskData.Insert("DESCRIPTION", "Another task description"); - TaskData.Insert("PRIORITY", "1"); - - URL = FunctionParameters["Bitrix24_URL"]; + TaskData.Insert("PRIORITY" , "1"); + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.UpdateTask(URL, TaskID, TaskData); - + OPI_TestDataRetrieval.WriteLog(Result, "UpdateTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.UpdateTask(URL, TaskID, TaskData, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "UpdateTask", "Bitrix24"); - - Check_BitrixTask(Result); - + + Check_BitrixTask(Result); + EndProcedure Procedure Bitrix24_GetTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.GetTask(URL, TaskID); - + OPI_TestDataRetrieval.WriteLog(Result, "GetTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.GetTask(URL, TaskID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetTask", "Bitrix24"); - + Check_BitrixTask(Result); - + EndProcedure Procedure Bitrix24_ApproveTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.ApproveTask(URL, TaskID); - + OPI_TestDataRetrieval.WriteLog(Result, "ApproveTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.ApproveTask(URL, TaskID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "ApproveTask", "Bitrix24"); - + Check_BitrixTask(Result); - + EndProcedure Procedure Bitrix24_DisapproveTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.DisapproveTask(URL, TaskID); - + Check_Map(Result); // SKIP - + OPI_TestDataRetrieval.WriteLog(Result, "DisapproveTask (wh)", "Bitrix24"); - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.DisapproveTask(URL, TaskID, Token); - + // END - + Check_Map(Result); - + OPI_TestDataRetrieval.WriteLog(Result, "DisapproveTask", "Bitrix24"); - + EndProcedure Procedure Bitrix24_CompleteTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.CompleteTask(URL, TaskID); - + OPI_TestDataRetrieval.WriteLog(Result, "CompleteTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.CompleteTask(URL, TaskID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CompleteTask", "Bitrix24"); - + Check_BitrixTask(Result); - + EndProcedure Procedure Bitrix24_RenewTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.RenewTask(URL, TaskID); - + OPI_TestDataRetrieval.WriteLog(Result, "RenewTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.RenewTask(URL, TaskID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "RenewTask", "Bitrix24"); - + Check_BitrixTask(Result); - + EndProcedure Procedure Bitrix24_DeferTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.DeferTask(URL, TaskID); - + OPI_TestDataRetrieval.WriteLog(Result, "DeferTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.DeferTask(URL, TaskID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "DeferTask", "Bitrix24"); - + Check_BitrixTask(Result); - + EndProcedure Procedure Bitrix24_StartTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.StartTask(URL, TaskID); - + OPI_TestDataRetrieval.WriteLog(Result, "StartTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.StartTask(URL, TaskID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "StartTask", "Bitrix24"); - + Check_BitrixTask(Result); - + EndProcedure Procedure Bitrix24_StartWatchingTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.StartWatchingTask(URL, TaskID); - + OPI_TestDataRetrieval.WriteLog(Result, "StartWatchingTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.StartWatchingTask(URL, TaskID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "StartWatchingTask", "Bitrix24"); - + Check_BitrixTask(Result); - + EndProcedure Procedure Bitrix24_StopWatchingTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.StopWatchingTask(URL, TaskID); - + OPI_TestDataRetrieval.WriteLog(Result, "StopWatchingTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.StopWatchingTask(URL, TaskID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "StopWatchingTask", "Bitrix24"); - + Check_BitrixTask(Result); - + EndProcedure Procedure Bitrix24_PauseTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.PauseTask(URL, TaskID); - + OPI_TestDataRetrieval.WriteLog(Result, "PauseTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.PauseTask(URL, TaskID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "PauseTask", "Bitrix24"); - + Check_BitrixTask(Result); - + EndProcedure Procedure Bitrix24_DeleteTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.DeleteTask(URL, TaskID); - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.DeleteTask(URL, TaskID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteTask", "Bitrix24"); - + Check_BitrixTask(Result); - + EndProcedure Procedure Bitrix24_DelegateTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; UserID = FunctionParameters["Bitrix24_UserID"]; - + Result = OPI_Bitrix24.DelegateTask(URL, TaskID, UserID); - + OPI_TestDataRetrieval.WriteLog(Result, "DelegateTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.DelegateTask(URL, TaskID, UserID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "DelegateTask", "Bitrix24"); - + Check_BitrixTask(Result); - + EndProcedure Procedure Bitrix24_AddTaskToFavorites(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.AddTaskToFavorites(URL, TaskID); - + OPI_TestDataRetrieval.WriteLog(Result, "StopWatchingTask (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.AddTaskToFavorites(URL, TaskID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "AddTaskToFavorites", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_RemoveTaskFromFavorites(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.RemoveTaskFromFavorites(URL, TaskID); - + OPI_TestDataRetrieval.WriteLog(Result, "RemoveTaskFromFavorites (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.RemoveTaskFromFavorites(URL, TaskID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "RemoveTaskFromFavorites", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_GetTaskHistory(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.GetTaskHistory(URL, TaskID); - + OPI_TestDataRetrieval.WriteLog(Result, "GetTaskHistory (wh)", "Bitrix24"); - + Check_BitrixList(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.GetTaskHistory(URL, TaskID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetTaskHistory", "Bitrix24"); - + Check_BitrixList(Result); - + EndProcedure Procedure Bitrix24_GetTasksList(FunctionParameters) - + // Full filter structer you can find at GetTasksFilterStructure method Filter = New Structure; Filter.Insert("CREATED_BY" , 1); Filter.Insert("RESPONSIBLE_ID", 10); - + Indent = 1; - URL = FunctionParameters["Bitrix24_URL"]; - + URL = FunctionParameters["Bitrix24_URL"]; + Result = OPI_Bitrix24.GetTasksList(URL, Filter); - + OPI_TestDataRetrieval.WriteLog(Result, "GetTasksList (wh)", "Bitrix24"); - + Check_BitrixTasksList(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetTasksList(URL, , Indent, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetTasksList", "Bitrix24"); - + Check_BitrixTasksList(Result); - + EndProcedure Procedure Bitrix24_GetStoragesList(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; Result = OPI_Bitrix24.GetStoragesList(URL); - + OPI_TestDataRetrieval.WriteLog(Result, "GetStoragesList (wh)", "Bitrix24"); - + Check_BitrixStorage(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetStoragesList(URL, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetStoragesList", "Bitrix24"); - + Check_BitrixStorage(Result); - + EndProcedure Procedure Bitrix24_GetAppStorage(FunctionParameters) - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetAppSotrage(URL, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetAppSotrage", "Bitrix24"); - + Check_BitrixObject(Result); - + StorageID = Result["result"]["ID"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_StorageID", StorageID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_StorageID", StorageID); // SKIP FunctionParameters.Insert("Bitrix24_StorageID", StorageID); // SKIP - + EndProcedure Procedure Bitrix24_UploadFileToStorage(FunctionParameters) - - Filename2 = "Picture2.jpg"; - Name = "Picture1.jpg"; - + + Filename2 = "Picture2.jpg"; + Name = "Picture1.jpg"; + Image2 = FunctionParameters["Picture"]; // Local path, URL or Binary Data - Image = FunctionParameters["Picture2"]; // Local path, URL or Binary Data - + Image = FunctionParameters["Picture2"]; // Local path, URL or Binary Data + DestinationID = 3; - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.UploadFileToStorage(URL, Filename2, Image2, DestinationID); - + OPI_TestDataRetrieval.WriteLog(Result, "UploadFileToStorage (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - + FileID = Result["result"]["ID"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookFileID", FileID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookFileID", FileID); // SKIP FunctionParameters.Insert("Bitrix24_HookFileID", FileID); // SKIP - URL = FunctionParameters["Bitrix24_Domain"]; + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.UploadFileToStorage(URL, Name, Image, DestinationID, , Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "UploadFileToStorage", "Bitrix24"); - - Check_BitrixObject(Result); - - FileID = Result["result"]["ID"]; - OPI_TestDataRetrieval.WriteParameter("Bitrix24_FileID", FileID); - FunctionParameters.Insert("Bitrix24_FileID", FileID); - + + Check_BitrixObject(Result); + + FileID = Result["result"]["ID"]; + OPI_TestDataRetrieval.WriteParameter("Bitrix24_FileID", FileID); + FunctionParameters.Insert("Bitrix24_FileID", FileID); + EndProcedure Procedure Bitrix24_DeleteFile(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; FileID = FunctionParameters["Bitrix24_HookFileID"]; - + Result = OPI_Bitrix24.DeleteFile(URL, FileID); - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteFile (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; FileID = FunctionParameters["Bitrix24_FileID"]; - + Result = OPI_Bitrix24.DeleteFile(URL, FileID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteFile", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_CreateStorageFolder(FunctionParameters) - + StorageID = 3; - Name = "New catalog"; + Name = "New catalog"; Filename2 = "New folder 2"; - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.CreateStorageFolder(URL, StorageID, Filename2); - + OPI_TestDataRetrieval.WriteLog(Result, "CreateStorageFolder (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - + FolderID = Result["result"]["ID"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookFolderID", FolderID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookFolderID", FolderID); // SKIP FunctionParameters.Insert("Bitrix24_HookFolderID", FolderID); // SKIP - URL = FunctionParameters["Bitrix24_Domain"]; + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.CreateStorageFolder(URL, StorageID, Name, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CreateStorageFolder", "Bitrix24"); - - Check_BitrixObject(Result); - + + Check_BitrixObject(Result); + FolderID = Result["result"]["ID"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_FolderID", FolderID); // SKIP - FunctionParameters.Insert("Bitrix24_FolderID", FolderID); // SKIP - + OPI_TestDataRetrieval.WriteParameter("Bitrix24_FolderID", FolderID); // SKIP + FunctionParameters.Insert("Bitrix24_FolderID", FolderID); // SKIP + EndProcedure Procedure Bitrix24_DeleteFolder(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; FolderID = FunctionParameters["Bitrix24_HookFolderID"]; - + Result = OPI_Bitrix24.DeleteFolder(URL, FolderID); - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteFolder (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; FolderID = FunctionParameters["Bitrix24_FolderID"]; - + Result = OPI_Bitrix24.DeleteFolder(URL, FolderID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteFolder", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_GetStorage(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; StorageID = 3; - + Result = OPI_Bitrix24.GetStorage(URL, StorageID); - + OPI_TestDataRetrieval.WriteLog(Result, "GetStorage (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetStorage(URL, StorageID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetStorage", "Bitrix24"); - + Check_BitrixObject(Result); - + EndProcedure Procedure Bitrix24_GetStorageObjects(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - StorageID = 3; - + + URL = FunctionParameters["Bitrix24_URL"]; + StorageID = 3; + Result = OPI_Bitrix24.GetStorageObjects(URL, StorageID); - + OPI_TestDataRetrieval.WriteLog(Result, "GetStorageObjects (wh)", "Bitrix24"); - + Check_BitrixArray(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetStorageObjects(URL, StorageID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetStorageObjects", "Bitrix24"); - + Check_BitrixArray(Result); - + EndProcedure Procedure Bitrix24_RenameStorage(FunctionParameters) - - Name = "New storage name"; - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + Name = "New storage name"; + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; StorageID = FunctionParameters["Bitrix24_StorageID"]; - + Result = OPI_Bitrix24.RenameStorage(URL, StorageID, Name, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "RenameStorage", "Bitrix24"); - + Check_BitrixObject(Result); - + EndProcedure Procedure Bitrix24_GetFolderInformation(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; FolderID = FunctionParameters["Bitrix24_FolderID"]; - + Result = OPI_Bitrix24.GetFolderInformation(URL, FolderID); - + OPI_TestDataRetrieval.WriteLog(Result, "GetFolderInformation (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetFolderInformation(URL, FolderID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetFolderInformation", "Bitrix24"); - + Check_BitrixObject(Result); - + EndProcedure Procedure Bitrix24_CreateSubfolder(FunctionParameters) - - FolderID = FunctionParameters["Bitrix24_FolderID"]; - Name = "New subfolder"; + + FolderID = FunctionParameters["Bitrix24_FolderID"]; + Name = "New subfolder"; Filename2 = "New subfolder 2"; - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.CreateSubfolder(URL, FolderID, Filename2); - + OPI_TestDataRetrieval.WriteLog(Result, "CreateSubfolder (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - + SubfolderID = Result["result"]["ID"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookSubfolderID", SubfolderID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookSubfolderID", SubfolderID); // SKIP FunctionParameters.Insert("Bitrix24_HookSubfolderID", SubfolderID); // SKIP - URL = FunctionParameters["Bitrix24_Domain"]; + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.CreateSubfolder(URL, FolderID, Name, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CreateSubfolder", "Bitrix24"); - - Check_BitrixObject(Result); - + + Check_BitrixObject(Result); + SubfolderID = Result["result"]["ID"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_SubfolderID", SubfolderID); // SKIP - FunctionParameters.Insert("Bitrix24_SubfolderID", SubfolderID); // SKIP - + OPI_TestDataRetrieval.WriteParameter("Bitrix24_SubfolderID", SubfolderID); // SKIP + FunctionParameters.Insert("Bitrix24_SubfolderID", SubfolderID); // SKIP + EndProcedure Procedure Bitrxi24_MakeFolderCopy(FunctionParameters) - - DestinationID = FunctionParameters["Bitrix24_HookSubfolderID"]; - FolderID = FunctionParameters["Bitrix24_SubfolderID"]; - - URL = FunctionParameters["Bitrix24_URL"]; - - Result = OPI_Bitrix24.MakeFolderCopy(URL, FolderID, DestinationID); - - OPI_TestDataRetrieval.WriteLog(Result, "MakeFolderCopy (wh)", "Bitrix24"); - - Check_BitrixObject(Result); // SKIP - - DestinationID = FunctionParameters["Bitrix24_SubfolderID"]; - FolderID = FunctionParameters["Bitrix24_HookSubfolderID"]; - URL = FunctionParameters["Bitrix24_Domain"]; + DestinationID = FunctionParameters["Bitrix24_HookSubfolderID"]; + FolderID = FunctionParameters["Bitrix24_SubfolderID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + + Result = OPI_Bitrix24.MakeFolderCopy(URL, FolderID, DestinationID); + + OPI_TestDataRetrieval.WriteLog(Result, "MakeFolderCopy (wh)", "Bitrix24"); + + Check_BitrixObject(Result); // SKIP + + DestinationID = FunctionParameters["Bitrix24_SubfolderID"]; + FolderID = FunctionParameters["Bitrix24_HookSubfolderID"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.MakeFolderCopy(URL, FolderID, DestinationID, Token); - + OPI_TestDataRetrieval.WriteLog(Result, "MakeFolderCopy", "Bitrix24"); - - Check_BitrixObject(Result); - + + Check_BitrixObject(Result); + EndProcedure Procedure Bitrix24_GetFolderExternalLink(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; FolderID = FunctionParameters["Bitrix24_FolderID"]; - + Result = OPI_Bitrix24.GetFolderExternalLink(URL, FolderID); - + OPI_TestDataRetrieval.WriteLog(Result, "GetFolderExternalLink (wh)", "Bitrix24"); - + Check_BitrixString(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetFolderExternalLink(URL, FolderID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetFolderExternalLink", "Bitrix24"); - + Check_BitrixString(Result); - + EndProcedure Procedure Bitrix24_GetFolderFilterStructure(FunctionParameters) - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.GetFolderFilterStructure(URL); - + OPI_TestDataRetrieval.WriteLog(Result, "GetFolderFilterStructure (wh)", "Bitrix24"); - + Check_Structure(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetFolderFilterStructure(URL, True, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetFolderFilterStructure", "Bitrix24"); - + Check_Structure(Result); - + EndProcedure Procedure Bitrix24_GetFolderItems(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; FolderID = FunctionParameters["Bitrix24_FolderID"]; - + Result = OPI_Bitrix24.GetFolderItems(URL, FolderID); - + OPI_TestDataRetrieval.WriteLog(Result, "GetFolderItems (wh)", "Bitrix24"); - + Check_BitrixArray(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetFolderItems(URL, FolderID, , Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetFolderItems", "Bitrix24"); - + Check_BitrixArray(Result); - + EndProcedure Procedure Bitrxi24_MarkFolderAsDeleted(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; FolderID = FunctionParameters["Bitrix24_FolderID"]; - + Result = OPI_Bitrix24.MarkFolderAsDeleted(URL, FolderID); - + OPI_TestDataRetrieval.WriteLog(Result, "MarkFolderAsDeleted (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.MarkFolderAsDeleted(URL, FolderID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "MarkFolderAsDeleted", "Bitrix24"); - + Check_BitrixObject(Result); - + EndProcedure Procedure Bitrix24_RestoreFolder(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; FolderID = FunctionParameters["Bitrix24_FolderID"]; - + Result = OPI_Bitrix24.RestoreFolder(URL, FolderID); - + OPI_TestDataRetrieval.WriteLog(Result, "RestoreFolder (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.RestoreFolder(URL, FolderID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "RestoreFolder", "Bitrix24"); - + Check_BitrixObject(Result); - + EndProcedure Procedure Bitrix24_MoveFolder(FunctionParameters) - + DestinationID = FunctionParameters["Bitrix24_HookfolderID"]; - FolderID = FunctionParameters["Bitrix24_SubfolderID"]; - + FolderID = FunctionParameters["Bitrix24_SubfolderID"]; + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.MoveFolder(URL, FolderID, DestinationID); - + OPI_TestDataRetrieval.WriteLog(Result, "MoveFolder (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - + FolderID = FunctionParameters["Bitrix24_HookSubfolderID"]; - URL = FunctionParameters["Bitrix24_Domain"]; + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.MoveFolder(URL, FolderID, DestinationID, Token); - + OPI_TestDataRetrieval.WriteLog(Result, "MoveFolder", "Bitrix24"); - - Check_BitrixObject(Result); - + + Check_BitrixObject(Result); + EndProcedure Procedure Bitrix24_RenameFolder(FunctionParameters) - - Name = "New catalog"; + + Name = "New catalog"; Filename2 = "New folder 2"; - + FolderID2 = FunctionParameters["Bitrix24_HookFolderID"]; - URL = FunctionParameters["Bitrix24_URL"]; - + URL = FunctionParameters["Bitrix24_URL"]; + Result = OPI_Bitrix24.RenameFolder(URL, FolderID2, Filename2); - + OPI_TestDataRetrieval.WriteLog(Result, "RenameFolder (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP FolderID = FunctionParameters["Bitrix24_FolderID"]; - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; - + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; + Result = OPI_Bitrix24.RenameFolder(URL, FolderID, Name, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "RenameFolder", "Bitrix24"); - - Check_BitrixObject(Result); - + + Check_BitrixObject(Result); + EndProcedure Procedure Bitrxi24_UploadFileToFolder(FunctionParameters) - - Filename2 = "Picture2.jpg"; - Name = "Picture1.jpg"; - + + Filename2 = "Picture2.jpg"; + Name = "Picture1.jpg"; + Image2 = FunctionParameters["Picture"]; // Local path, URL or Binary Data - Image = FunctionParameters["Picture2"]; // Local path, URL or Binary Data - + Image = FunctionParameters["Picture2"]; // Local path, URL or Binary Data + DestinationID = FunctionParameters["Bitrix24_FolderID"]; - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.UploadFileToFolder(URL, Filename2, Image2, DestinationID); - + OPI_TestDataRetrieval.WriteLog(Result, "UploadFileToFolder (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - + FileID = Result["result"]["ID"]; // SKIP OPI_Bitrix24.DeleteFile(URL, FileID); // SKIP - URL = FunctionParameters["Bitrix24_Domain"]; + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.UploadFileToFolder(URL, Name, Image, DestinationID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "UploadFileToFolder", "Bitrix24"); - - Check_BitrixObject(Result); - + + Check_BitrixObject(Result); + FileID = Result["result"]["ID"]; - Result = OPI_Bitrix24.DeleteFile(URL, FileID, Token); - + Result = OPI_Bitrix24.DeleteFile(URL, FileID, Token); + EndProcedure Procedure Bitrix24_MakeCopyFile(FunctionParameters) - + FolderID = FunctionParameters["Bitrix24_HookFolderID"]; - FileID = FunctionParameters["Bitrix24_FileID"]; - + FileID = FunctionParameters["Bitrix24_FileID"]; + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.MakeCopyFile(URL, FileID, FolderID); - + OPI_TestDataRetrieval.WriteLog(Result, "MakeCopyFile (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - + FolderID = FunctionParameters["Bitrix24_FolderID"]; - URL = FunctionParameters["Bitrix24_Domain"]; + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.MakeCopyFile(URL, FileID, FolderID, Token); - + OPI_TestDataRetrieval.WriteLog(Result, "MakeCopyFile", "Bitrix24"); - - Check_BitrixObject(Result); - + + Check_BitrixObject(Result); + EndProcedure Procedure Bitrix24_GetFileInformation(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; FileID = FunctionParameters["Bitrix24_FileID"]; - + Result = OPI_Bitrix24.GetFileInformation(URL, FileID); - + OPI_TestDataRetrieval.WriteLog(Result, "GetFileInformation (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetFileInformation(URL, FileID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetFileInformation", "Bitrix24"); - + Check_BitrixObject(Result); - + EndProcedure Procedure Bitrix24_GetFileExternalLink(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; FileID = FunctionParameters["Bitrix24_FileID"]; - + Result = OPI_Bitrix24.GetFileExternalLink(URL, FileID); - + OPI_TestDataRetrieval.WriteLog(Result, "GetFileExternalLink (wh)", "Bitrix24"); - + Check_BitrixString(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetFileExternalLink(URL, FileID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetFileExternalLink", "Bitrix24"); - + Check_BitrixString(Result); - + EndProcedure Procedure Bitrxi24_MarkFileAsDeleted(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; FileID = FunctionParameters["Bitrix24_FileID"]; - + Result = OPI_Bitrix24.MarkFileAsDeleted(URL, FileID); - + OPI_TestDataRetrieval.WriteLog(Result, "MarkFileAsDeleted (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.MarkFileAsDeleted(URL, FileID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "MarkFileAsDeleted", "Bitrix24"); - + Check_BitrixObject(Result); - + EndProcedure Procedure Bitrix24_RestoreFile(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; FileID = FunctionParameters["Bitrix24_FileID"]; - + Result = OPI_Bitrix24.RestoreFile(URL, FileID); - + OPI_TestDataRetrieval.WriteLog(Result, "RestoreFile (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.RestoreFile(URL, FileID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "RestoreFile", "Bitrix24"); - + Check_BitrixObject(Result); - + EndProcedure Procedure Bitrix24_RenameFile(FunctionParameters) - - Name = "New file name.jpg"; + + Name = "New file name.jpg"; Filename2 = "New file name 2.jpg"; - + FileID2 = FunctionParameters["Bitrix24_HookFileID"]; - URL = FunctionParameters["Bitrix24_URL"]; - + URL = FunctionParameters["Bitrix24_URL"]; + Result = OPI_Bitrix24.RenameFile(URL, FileID2, Filename2); - + OPI_TestDataRetrieval.WriteLog(Result, "RenameFile (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP FileID = FunctionParameters["Bitrix24_FileID"]; - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; - + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; + Result = OPI_Bitrix24.RenameFile(URL, FileID, Name, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "RenameFile", "Bitrix24"); - - Check_BitrixObject(Result); - + + Check_BitrixObject(Result); + EndProcedure Procedure Bitrix24_MoveFileToFolder(FunctionParameters) - + FolderID = FunctionParameters["Bitrix24_HookSubFolderID"]; - FileID = FunctionParameters["Bitrix24_FileID"]; - + FileID = FunctionParameters["Bitrix24_FileID"]; + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.MoveFileToFolder(URL, FileID, FolderID); - + OPI_TestDataRetrieval.WriteLog(Result, "MoveFileToFolder (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - + FolderID = FunctionParameters["Bitrix24_SubFolderID"]; - URL = FunctionParameters["Bitrix24_Domain"]; + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.MoveFileToFolder(URL, FileID, FolderID, Token); - + OPI_TestDataRetrieval.WriteLog(Result, "MoveFileToFolder", "Bitrix24"); - - Check_BitrixObject(Result); - + + Check_BitrixObject(Result); + EndProcedure Procedure Bitrix24_AttachFileToTopic(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; FileID = FunctionParameters["Bitrix24_TaskFileID"]; - + Result = OPI_Bitrix24.AttachFileToTopic(URL, TaskID, FileID); - + OPI_TestDataRetrieval.WriteLog(Result, "AttachFileToTopic (wh)", "Bitrix24"); - + Check_BitrixAttachment(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.AttachFileToTopic(URL, TaskID, FileID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "AttachFileToTopic", "Bitrix24"); - + Check_BitrixAttachment(Result); - + EndProcedure Procedure Bitrix24_CheckTaskAccesses(FunctionParameters) - + ArrayOfUsers = New Array; ArrayOfUsers.Add("1"); ArrayOfUsers.Add("10"); - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.CheckTaskAccesses(URL, TaskID, ArrayOfUsers); - + OPI_TestDataRetrieval.WriteLog(Result, "CheckTaskAccesses (wh)", "Bitrix24"); - + Check_BitrixAvailableActions(Result, ArrayOfUsers.Count()); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.CheckTaskAccesses(URL, TaskID, ArrayOfUsers, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CheckTaskAccesses", "Bitrix24"); - + Check_BitrixAvailableActions(Result, ArrayOfUsers.Count()); - + EndProcedure Procedure Bitrix24_MuteTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.MuteTask(URL, TaskID); - + OPI_TestDataRetrieval.WriteLog(Result, "MuteTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.MuteTask(URL, TaskID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "MuteTask", "Bitrix24"); - + Check_BitrixTask(Result); - + EndProcedure Procedure Bitrix24_UnmuteTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.UnmuteTask(URL, TaskID); - + OPI_TestDataRetrieval.WriteLog(Result, "UnmuteTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.UnmuteTask(URL, TaskID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "UnmuteTask", "Bitrix24"); - + Check_BitrixTask(Result); - + EndProcedure Procedure Bitrix24_AddTaskComment(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_CommentsTaskID"]; - + Text = "Task impossible, let's split up"; - + Result = OPI_Bitrix24.AddTaskComment(URL, TaskID, Text); - + OPI_TestDataRetrieval.WriteLog(Result, "AddTaskComment (wh)", "Bitrix24"); - + Check_BitrixNumber(Result); // SKIP - + CommentID = Result["result"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookCommentID", CommentID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookCommentID", CommentID); // SKIP FunctionParameters.Insert("Bitrix24_HookCommentID", CommentID); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Text = "Task uninpossible, don't split up"; - + Result = OPI_Bitrix24.AddTaskComment(URL, TaskID, Text, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "AddTaskComment", "Bitrix24"); - + Check_BitrixNumber(Result); - + CommentID = Result["result"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_CommentID", CommentID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_CommentID", CommentID); // SKIP FunctionParameters.Insert("Bitrix24_CommentID", CommentID); // SKIP - + EndProcedure Procedure Bitrix24_DeleteTaskComment(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - TaskID = FunctionParameters["Bitrix24_CommentsTaskID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + TaskID = FunctionParameters["Bitrix24_CommentsTaskID"]; CommentID = FunctionParameters["Bitrix24_HookCommentID"]; - + Result = OPI_Bitrix24.DeleteTaskComment(URL, TaskID, CommentID); - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteTaskComment (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; CommentID = FunctionParameters["Bitrix24_CommentID"]; - + Result = OPI_Bitrix24.DeleteTaskComment(URL, TaskID, CommentID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteTaskComment", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_CreateResultFromComment(FunctionParameters) - URL = FunctionParameters["Bitrix24_URL"]; + URL = FunctionParameters["Bitrix24_URL"]; CommentID = FunctionParameters["Bitrix24_HookCommentID"]; - + Result = OPI_Bitrix24.CreateResultFromComment(URL, CommentID); - + OPI_TestDataRetrieval.WriteLog(Result, "CreateResultFromComment (wh)", "Bitrix24"); - + Check_BitrixResult(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; CommentID = FunctionParameters["Bitrix24_CommentID"]; - + Result = OPI_Bitrix24.CreateResultFromComment(URL, CommentID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CreateResultFromComment", "Bitrix24"); - + Check_BitrixResult(Result); - + EndProcedure Procedure Bitrix24_DeleteResultFromComment(FunctionParameters) Export - URL = FunctionParameters["Bitrix24_URL"]; + URL = FunctionParameters["Bitrix24_URL"]; CommentID = FunctionParameters["Bitrix24_HookCommentID"]; - + Result = OPI_Bitrix24.DeleteResultFromComment(URL, CommentID); - + OPI_TestDataRetrieval.WriteLog(Result, "Delete result from comment)", "Bitrix24"); - + Check_BitrixUndefined(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; CommentID = FunctionParameters["Bitrix24_CommentID"]; - + Result = OPI_Bitrix24.DeleteResultFromComment(URL, CommentID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteResultFromComment", "Bitrix24"); - + Check_BitrixUndefined(Result); - + EndProcedure Procedure Bitrix24_GetResultsList(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_CommentsTaskID"]; - + Result = OPI_Bitrix24.GetResultsList(URL, TaskID); - + OPI_TestDataRetrieval.WriteLog(Result, "GetResultsList (wh)", "Bitrix24"); - + Check_BitrixResultsList(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetResultsList(URL, TaskID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetResultsList", "Bitrix24"); - + Check_BitrixResultsList(Result); - + EndProcedure Procedure Bitrix24_GetTaskCommentsList(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_CommentsTaskID"]; - + Result = OPI_Bitrix24.GetTaskCommentsList(URL, TaskID); - + OPI_TestDataRetrieval.WriteLog(Result, "GetTaskCommentsList (wh)", "Bitrix24"); - + Check_BitrixCommentsList(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetTaskCommentsList(URL, TaskID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetTaskCommentsList", "Bitrix24"); - + Check_BitrixCommentsList(Result); - + EndProcedure Procedure Bitrix24_GetTaskComment(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; CommentID = FunctionParameters["Bitrix24_HookCommentID"]; - TaskID = FunctionParameters["Bitrix24_CommentsTaskID"]; - + TaskID = FunctionParameters["Bitrix24_CommentsTaskID"]; + Result = OPI_Bitrix24.GetTaskComment(URL, TaskID, CommentID); - + OPI_TestDataRetrieval.WriteLog(Result, "GetTaskComment (wh)", "Bitrix24"); - + Check_BitrixComment(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; CommentID = FunctionParameters["Bitrix24_CommentID"]; - + Result = OPI_Bitrix24.GetTaskComment(URL, TaskID, CommentID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetTaskComment", "Bitrix24"); - + Check_BitrixComment(Result); - + EndProcedure Procedure Bitrix24_UpdateTaskComment(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - TaskID = FunctionParameters["Bitrix24_CommentsTaskID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + TaskID = FunctionParameters["Bitrix24_CommentsTaskID"]; CommentID = FunctionParameters["Bitrix24_HookCommentID"]; - + Text = "The task has been changed, do not split up"; - + Result = OPI_Bitrix24.UpdateTaskComment(URL, TaskID, CommentID, Text); - + OPI_TestDataRetrieval.WriteLog(Result, "UpdateTaskComment (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; CommentID = FunctionParameters["Bitrix24_CommentID"]; - + Text = "The task has been changed, let's split up"; - + Result = OPI_Bitrix24.UpdateTaskComment(URL, TaskID, CommentID, Text, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "UpdateTaskComment", "Bitrix24"); - + Check_BitrixTrue(Result); EndProcedure Procedure Bitrix24_CreateTasksDependencies(FunctionParameters) - - FromID = FunctionParameters["Bitrix24_HookTaskID"]; + + FromID = FunctionParameters["Bitrix24_HookTaskID"]; DestinationID = FunctionParameters["Bitrix24_TaskID"]; - LinkType = 0; - + LinkType = 0; + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.CreateTasksDependencies(URL, FromID, DestinationID, LinkType); - + OPI_TestDataRetrieval.WriteLog(Result, "CreateTasksDependencies (wh)", "Bitrix24"); - + Check_BitrixArray(Result); // SKIP - + Result = OPI_Bitrix24.DeleteTasksDependencies(URL, FromID, DestinationID, LinkType); // SKIP - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteTasksDependencies (wh)", "Bitrix24"); - - FromID = FunctionParameters["Bitrix24_TaskID"]; + + FromID = FunctionParameters["Bitrix24_TaskID"]; DestinationID = FunctionParameters["Bitrix24_HookTaskID"]; - LinkType = 2; - - URL = FunctionParameters["Bitrix24_Domain"]; + LinkType = 2; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.CreateTasksDependencies(URL, FromID, DestinationID, LinkType, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CreateTasksDependencies", "Bitrix24"); - - Check_BitrixArray(Result); - + + Check_BitrixArray(Result); + Result = OPI_Bitrix24.DeleteTasksDependencies(URL, FromID, DestinationID, LinkType, Token); - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteTasksDependencies", "Bitrix24"); - + EndProcedure Procedure Bitrix24_AddKanbanStage(FunctionParameters) - - Name = "New stage"; + + Name = "New stage"; Color = "0026FF"; - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.AddKanbanStage(URL, Name, Color, 6); - + OPI_TestDataRetrieval.WriteLog(Result, "AddKanbanStage (wh)", "Bitrix24"); - + Check_BitrixNumber(Result); // SKIP - + PrevStageID = Result["result"]; - - OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookStageID", PrevStageID); // SKIP + + OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookStageID", PrevStageID); // SKIP FunctionParameters.Insert("Bitrix24_HookStageID", PrevStageID); // SKIP - - Name = "New stage 2"; + + Name = "New stage 2"; Color = "0026FF"; - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.AddKanbanStage(URL, Name, Color, PrevStageID, , True, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "AddKanbanStage", "Bitrix24"); - - Check_BitrixNumber(Result); - + + Check_BitrixNumber(Result); + StageID = Result["result"]; - OPI_TestDataRetrieval.WriteParameter("Bitrix24_StageID", StageID); - FunctionParameters.Insert("Bitrix24_StageID", StageID); - + OPI_TestDataRetrieval.WriteParameter("Bitrix24_StageID", StageID); + FunctionParameters.Insert("Bitrix24_StageID", StageID); + EndProcedure Procedure Bitrix24_DeleteKanbanStage(FunctionParameters) - + StageID = FunctionParameters["Bitrix24_HookStageID"]; - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.DeleteKanbanStage(URL, StageID, True); - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteKanbanStage (wh)", "Bitrix24"); - - Check_BitrixTrue(Result); // SKIP - + + Check_BitrixTrue(Result); // SKIP + StageID = FunctionParameters["Bitrix24_StageID"]; - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.DeleteKanbanStage(URL, StageID, , Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteKanbanStage", "Bitrix24"); - - Check_BitrixTrue(Result); - + + Check_BitrixTrue(Result); + EndProcedure Procedure Bitrix24_GetKanbanStages(FunctionParameters) - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.GetKanbanStages(URL, , True); - + OPI_TestDataRetrieval.WriteLog(Result, "GetKanbanStages (wh)", "Bitrix24"); - - Check_BitrixMap(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + Check_BitrixMap(Result); // SKIP + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetKanbanStages(URL, , , Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetKanbanStages", "Bitrix24"); - - Check_BitrixMap(Result); - + + Check_BitrixMap(Result); + EndProcedure Procedure Bitrix24_MoveTaskToKanbanStage(FunctionParameters) - - TaskID = FunctionParameters["Bitrix24_KanbanTaskID"]; + + TaskID = FunctionParameters["Bitrix24_KanbanTaskID"]; StageID = FunctionParameters["Bitrix24_HookStageID"]; - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.MoveTaskToKanbanStage(URL, TaskID, StageID); - + OPI_TestDataRetrieval.WriteLog(Result, "MoveTaskToKanbanStage (wh)", "Bitrix24"); - - Check_BitrixTrue(Result); // SKIP - + + Check_BitrixTrue(Result); // SKIP + StageID = FunctionParameters["Bitrix24_StageID"]; - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.MoveTaskToKanbanStage(URL, TaskID, StageID, , , Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "MoveTaskToKanbanStage", "Bitrix24"); - + Check_BitrixTrue(Result); - + OPI_Bitrix24.MoveTaskToKanbanStage(URL, TaskID, 2, , , Token); - + EndProcedure Procedure Bitrix24_UpdateKanbansStage(FunctionParameters) - - Name = "New stage name"; - Color = "000000"; + + Name = "New stage name"; + Color = "000000"; StageID = FunctionParameters["Bitrix24_HookStageID"]; - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.UpdateKanbansStage(URL, Name, StageID, Color); - + OPI_TestDataRetrieval.WriteLog(Result, "UpdateKanbansStage (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - Name = "New stage name 2"; - Color = "000000"; + + Name = "New stage name 2"; + Color = "000000"; StageID = FunctionParameters["Bitrix24_StageID"]; - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.UpdateKanbansStage(URL, Name, StageID, Color, 6, True, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "UpdateKanbansStage", "Bitrix24"); - - Check_BitrixTrue(Result); - + + Check_BitrixTrue(Result); + EndProcedure Procedure Bitrix24_AddTasksChecklistElement(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Text = "Checklist element"; - + Result = OPI_Bitrix24.AddTasksChecklistElement(URL, TaskID, Text, True); - + OPI_TestDataRetrieval.WriteLog(Result, "AddTasksChecklistElement (wh)", "Bitrix24"); - + Check_BitrixNumber(Result); // SKIP - + ElementID = Result["result"]; // SKIP - - OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookCheckElementID", ElementID); // SKIP + + OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookCheckElementID", ElementID); // SKIP FunctionParameters.Insert("Bitrix24_HookCheckElementID", ElementID); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.AddTasksChecklistElement(URL, TaskID, Text, , Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "AddTasksChecklistElement", "Bitrix24"); - + Check_BitrixNumber(Result); - - ElementID = Result["result"]; - - OPI_TestDataRetrieval.WriteParameter("Bitrix24_CheckElementID", ElementID); - FunctionParameters.Insert("Bitrix24_CheckElementID", ElementID); - + + ElementID = Result["result"]; + + OPI_TestDataRetrieval.WriteParameter("Bitrix24_CheckElementID", ElementID); + FunctionParameters.Insert("Bitrix24_CheckElementID", ElementID); + EndProcedure Procedure Bitrix24_UpdateTasksChecklistElement(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - TaskID = FunctionParameters["Bitrix24_HookTaskID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + TaskID = FunctionParameters["Bitrix24_HookTaskID"]; ElementID = FunctionParameters["Bitrix24_HookCheckElementID"]; - + Text = "New elements text"; - + Result = OPI_Bitrix24.UpdateTasksChecklistElement(URL, TaskID, ElementID, Text); - + OPI_TestDataRetrieval.WriteLog(Result, "UpdateTasksChecklistElement (wh)", "Bitrix24"); - + Check_BitrixUndefined(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; - TaskID = FunctionParameters["Bitrix24_TaskID"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; + TaskID = FunctionParameters["Bitrix24_TaskID"]; ElementID = FunctionParameters["Bitrix24_CheckElementID"]; - + Result = OPI_Bitrix24.UpdateTasksChecklistElement(URL, TaskID, ElementID, Text, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "UpdateTasksChecklistElement", "Bitrix24"); - + Check_BitrixUndefined(Result); - + EndProcedure Procedure Bitrix24_DeleteTasksChecklistElement(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - TaskID = FunctionParameters["Bitrix24_HookTaskID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + TaskID = FunctionParameters["Bitrix24_HookTaskID"]; ElementID = FunctionParameters["Bitrix24_HookCheckElementID"]; - + Result = OPI_Bitrix24.DeleteTasksChecklistElement(URL, TaskID, ElementID); - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteTasksChecklistElement (wh)", "Bitrix24"); - - Check_BitrixTrue(Result); // SKIP - - TaskID = FunctionParameters["Bitrix24_TaskID"]; + + Check_BitrixTrue(Result); // SKIP + + TaskID = FunctionParameters["Bitrix24_TaskID"]; ElementID = FunctionParameters["Bitrix24_CheckElementID"]; - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.DeleteTasksChecklistElement(URL, TaskID, ElementID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteTasksChecklistElement", "Bitrix24"); - - Check_BitrixTrue(Result); - + + Check_BitrixTrue(Result); + EndProcedure Procedure Bitrix24_GetTasksChecklist(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.GetTasksChecklist(URL, TaskID); - + OPI_TestDataRetrieval.WriteLog(Result, "GetTasksChecklist (wh)", "Bitrix24"); - + Check_BitrixArray(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.GetTasksChecklist(URL, TaskID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetTasksChecklist", "Bitrix24"); - + Check_BitrixArray(Result); EndProcedure Procedure Bitrix24_GetTasksChecklistElement(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - TaskID = FunctionParameters["Bitrix24_HookTaskID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + TaskID = FunctionParameters["Bitrix24_HookTaskID"]; ElementID = FunctionParameters["Bitrix24_HookCheckElementID"]; - + Result = OPI_Bitrix24.GetTasksChecklistElement(URL, TaskID, ElementID); - + OPI_TestDataRetrieval.WriteLog(Result, "GetTasksChecklistElement (wh)", "Bitrix24"); - - Check_BitrixObject(Result); // SKIP - - TaskID = FunctionParameters["Bitrix24_TaskID"]; + + Check_BitrixObject(Result); // SKIP + + TaskID = FunctionParameters["Bitrix24_TaskID"]; ElementID = FunctionParameters["Bitrix24_CheckElementID"]; - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetTasksChecklistElement(URL, TaskID, ElementID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetTasksChecklistElement", "Bitrix24"); - - Check_BitrixObject(Result); - + + Check_BitrixObject(Result); + EndProcedure Procedure Bitrix24_CompleteTasksChecklistElement(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - TaskID = FunctionParameters["Bitrix24_HookTaskID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + TaskID = FunctionParameters["Bitrix24_HookTaskID"]; ElementID = FunctionParameters["Bitrix24_HookCheckElementID"]; - + Result = OPI_Bitrix24.CompleteTasksChecklistElement(URL, TaskID, ElementID); - + OPI_TestDataRetrieval.WriteLog(Result, "CompleteTasksChecklistElement (wh)", "Bitrix24"); - - Check_BitrixTrue(Result); // SKIP - - TaskID = FunctionParameters["Bitrix24_TaskID"]; + + Check_BitrixTrue(Result); // SKIP + + TaskID = FunctionParameters["Bitrix24_TaskID"]; ElementID = FunctionParameters["Bitrix24_CheckElementID"]; - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.CompleteTasksChecklistElement(URL, TaskID, ElementID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CompleteTasksChecklistElement", "Bitrix24"); - - Check_BitrixTrue(Result); - + + Check_BitrixTrue(Result); + EndProcedure Procedure Bitrix24_RenewTasksChecklistElement(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - TaskID = FunctionParameters["Bitrix24_HookTaskID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + TaskID = FunctionParameters["Bitrix24_HookTaskID"]; ElementID = FunctionParameters["Bitrix24_HookCheckElementID"]; - + Result = OPI_Bitrix24.RenewTasksChecklistElement(URL, TaskID, ElementID); - + OPI_TestDataRetrieval.WriteLog(Result, "RenewTasksChecklistElement (wh)", "Bitrix24"); - - Check_BitrixTrue(Result); // SKIP - - TaskID = FunctionParameters["Bitrix24_TaskID"]; + + Check_BitrixTrue(Result); // SKIP + + TaskID = FunctionParameters["Bitrix24_TaskID"]; ElementID = FunctionParameters["Bitrix24_CheckElementID"]; - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.RenewTasksChecklistElement(URL, TaskID, ElementID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "RenewTasksChecklistElement", "Bitrix24"); - - Check_BitrixTrue(Result); - + + Check_BitrixTrue(Result); + EndProcedure Procedure Bitrix24_AddTaskTimeAccounting(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_ElapsedTaskID"]; - + Time = 3600; - + Result = OPI_Bitrix24.AddTaskTimeAccounting(URL, TaskID, Time); - + OPI_TestDataRetrieval.WriteLog(Result, "AddTaskTimeAccounting (wh)", "Bitrix24"); - + Check_BitrixNumber(Result); // SKIP - + SpendingID = Result["result"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookTimeID", SpendingID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookTimeID", SpendingID); // SKIP FunctionParameters.Insert("Bitrix24_HookTimeID", SpendingID); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - - Text = "Time spent on work"; - UserID = 10; - Time = 7200; + + Text = "Time spent on work"; + UserID = 10; + Time = 7200; SetupDate = AddMonth(OPI_Tools.GetCurrentDate(), -1); - + Result = OPI_Bitrix24.AddTaskTimeAccounting(URL , TaskID , Time @@ -8501,42 +8501,42 @@ Procedure Bitrix24_AddTaskTimeAccounting(FunctionParameters) , Text , SetupDate , Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "AddTaskTimeAccounting", "Bitrix24"); - + Check_BitrixNumber(Result); - - SpendingID = Result["result"]; - OPI_TestDataRetrieval.WriteParameter("Bitrix24_TimeID", SpendingID); - FunctionParameters.Insert("Bitrix24_TimeID", SpendingID); - + + SpendingID = Result["result"]; + OPI_TestDataRetrieval.WriteParameter("Bitrix24_TimeID", SpendingID); + FunctionParameters.Insert("Bitrix24_TimeID", SpendingID); + EndProcedure Procedure Bitrix24_UpdateTaskTimeAccounting(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - TaskID = FunctionParameters["Bitrix24_ElapsedTaskID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + TaskID = FunctionParameters["Bitrix24_ElapsedTaskID"]; RecordID = FunctionParameters["Bitrix24_HookTimeID"]; - + Text = "The text I forgot last time"; Time = 4800; - + Result = OPI_Bitrix24.UpdateTaskTimeAccounting(URL, TaskID, RecordID, Time, Text); - + OPI_TestDataRetrieval.WriteLog(Result, "UpdateTaskTimeAccounting (wh)", "Bitrix24"); - + Check_BitrixUndefined(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; RecordID = FunctionParameters["Bitrix24_TimeID"]; - - Text = "New time record"; - Time = 4800; + + Text = "New time record"; + Time = 4800; SetupDate = AddMonth(OPI_Tools.GetCurrentDate(), -1); - + Result = OPI_Bitrix24.UpdateTaskTimeAccounting(URL , TaskID , RecordID @@ -8544,994 +8544,994 @@ Procedure Bitrix24_UpdateTaskTimeAccounting(FunctionParameters) , Text , SetupDate , Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "UpdateTaskTimeAccounting", "Bitrix24"); - - Check_BitrixUndefined(Result); - + + Check_BitrixUndefined(Result); + EndProcedure Procedure Bitrix24_DeleteTaskTimeAccounting(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - TaskID = FunctionParameters["Bitrix24_ElapsedTaskID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + TaskID = FunctionParameters["Bitrix24_ElapsedTaskID"]; RecordID = FunctionParameters["Bitrix24_HookTimeID"]; - + Result = OPI_Bitrix24.DeleteTaskTimeAccounting(URL, TaskID, RecordID); - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteTaskTimeAccounting (wh)", "Bitrix24"); - + Check_BitrixUndefined(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; RecordID = FunctionParameters["Bitrix24_TimeID"]; - + Result = OPI_Bitrix24.DeleteTaskTimeAccounting(URL, TaskID, RecordID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteTaskTimeAccounting", "Bitrix24"); - + Check_BitrixUndefined(Result); - + EndProcedure Procedure Bitrix24_GetTaskTimeAccounting(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - TaskID = FunctionParameters["Bitrix24_ElapsedTaskID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + TaskID = FunctionParameters["Bitrix24_ElapsedTaskID"]; RecordID = FunctionParameters["Bitrix24_HookTimeID"]; - + Result = OPI_Bitrix24.GetTaskTimeAccounting(URL, TaskID, RecordID); - + OPI_TestDataRetrieval.WriteLog(Result, "GetTaskTimeAccounting (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; RecordID = FunctionParameters["Bitrix24_TimeID"]; - + Result = OPI_Bitrix24.GetTaskTimeAccounting(URL, TaskID, RecordID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetTaskTimeAccounting", "Bitrix24"); - + Check_BitrixObject(Result); - + EndProcedure Procedure Bitrix24_GetTaskTimeAccountingList(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_ElapsedTaskID"]; - + Result = OPI_Bitrix24.GetTaskTimeAccountingList(URL, TaskID); - + OPI_TestDataRetrieval.WriteLog(Result, "GetTaskTimeAccountingList (wh)", "Bitrix24"); - + Check_BitrixObjectsArray(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetTaskTimeAccountingList(URL, TaskID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetTaskTimeAccountingList", "Bitrix24"); - + Check_BitrixObjectsArray(Result); - + EndProcedure Procedure Bitrix24_GetDailyPlan(FunctionParameters) - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.GetDailyPlan(URL); - + OPI_TestDataRetrieval.WriteLog(Result, "GetDailyPlan (wh)", "Bitrix24"); - + Check_BitrixArray(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetDailyPlan(URL, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetDailyPlan", "Bitrix24"); - + Check_BitrixArray(Result); - + EndProcedure Procedure Bitrix24_CreateChat(FunctionParameters) - + Image = FunctionParameters["Picture"]; OPI_TypeConversion.GetBinaryData(Image); - + B64Image = GetBase64StringFromBinaryData(Image); - + MembersArray = New Array; MembersArray.Add(10); MembersArray.Add(1); - + ChatStructure = New Structure; - ChatStructure.Insert("TYPE" , "OPEN"); - ChatStructure.Insert("TITLE" , "New chat"); + ChatStructure.Insert("TYPE" , "OPEN"); + ChatStructure.Insert("TITLE" , "New chat"); ChatStructure.Insert("DESCRIPTION", "This is a new chat"); - ChatStructure.Insert("COLOR" , "GREEN"); - ChatStructure.Insert("MESSAGE" , "Welcome to new chat"); - ChatStructure.Insert("USERS" , MembersArray); - ChatStructure.Insert("AVATAR" , B64Image); - ChatStructure.Insert("OWNER_ID" , 1); - + ChatStructure.Insert("COLOR" , "GREEN"); + ChatStructure.Insert("MESSAGE" , "Welcome to new chat"); + ChatStructure.Insert("USERS" , MembersArray); + ChatStructure.Insert("AVATAR" , B64Image); + ChatStructure.Insert("OWNER_ID" , 1); + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.CreateChat(URL, ChatStructure); - + OPI_TestDataRetrieval.WriteLog(Result, "CreateChat (wh)", "Bitrix24"); - + Check_BitrixNumber(Result); // SKIP - + ChatID = Result["result"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookChatID", ChatID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookChatID", ChatID); // SKIP FunctionParameters.Insert("Bitrix24_HookChatID", ChatID); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + ChatStructure = New Structure; - ChatStructure.Insert("TYPE" , "CHAT"); + ChatStructure.Insert("TYPE" , "CHAT"); ChatStructure.Insert("TITLE" , "Private chat"); ChatStructure.Insert("USERS" , MembersArray); - + Result = OPI_Bitrix24.CreateChat(URL, ChatStructure, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CreateChat", "Bitrix24"); - + Check_BitrixNumber(Result); - + ChatID = Result["result"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_ChatID", ChatID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_ChatID", ChatID); // SKIP FunctionParameters.Insert("Bitrix24_ChatID", ChatID); // SKIP - + EndProcedure Procedure Bitrix24_GetChatUsers(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; ChatID = FunctionParameters["Bitrix24_HookChatID"]; - + Result = OPI_Bitrix24.GetChatUsers(URL, ChatID); - + OPI_TestDataRetrieval.WriteLog(Result, "GetChatUsers (wh)", "Bitrix24"); - + Check_BitrixArray(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; ChatID = FunctionParameters["Bitrix24_ChatID"]; - + Result = OPI_Bitrix24.GetChatUsers(URL, ChatID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetChatUsers", "Bitrix24"); - + Check_BitrixArray(Result); - + EndProcedure Procedure Bitrix24_LeaveChat(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; ChatID = FunctionParameters["Bitrix24_HookChatID"]; - + Result = OPI_Bitrix24.LeaveChat(URL, ChatID); - + OPI_TestDataRetrieval.WriteLog(Result, "LeaveChat (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; ChatID = FunctionParameters["Bitrix24_ChatID"]; - + Result = OPI_Bitrix24.LeaveChat(URL, ChatID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "LeaveChat", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_DeleteUserFromChat(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; ChatID = FunctionParameters["Bitrix24_HookChatID"]; - + UserID = 10; - + Result = OPI_Bitrix24.DeleteUserFromChat(URL, ChatID, UserID); - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteUserFromChat (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; ChatID = FunctionParameters["Bitrix24_ChatID"]; - + Result = OPI_Bitrix24.DeleteUserFromChat(URL, ChatID, UserID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteUserFromChat", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_AddUsersToChat(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; ChatID = FunctionParameters["Bitrix24_HookChatID"]; - + UserIDs = New Array; UserIDs.Add(10); UserIDs.Add(12); - + Result = OPI_Bitrix24.AddUsersToChat(URL, ChatID, UserIDs); OPI_TestDataRetrieval.WriteLog(Result, "AddUsersToChat (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; ChatID = FunctionParameters["Bitrix24_ChatID"]; UserID = 10; - + Result = OPI_Bitrix24.AddUsersToChat(URL, ChatID, UserID, True, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "AddUsersToChat", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_ChangeChatTitle(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; ChatID = FunctionParameters["Bitrix24_HookChatID"]; - + Title = "New chat title"; - + Result = OPI_Bitrix24.ChangeChatTitle(URL, ChatID, Title); - + OPI_TestDataRetrieval.WriteLog(Result, "ChangeChatTitle (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; ChatID = FunctionParameters["Bitrix24_ChatID"]; - + Title = "Another title"; - + Result = OPI_Bitrix24.ChangeChatTitle(URL, ChatID, Title, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "ChangeChatTitle", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_ChangeChatColor(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; ChatID = FunctionParameters["Bitrix24_HookChatID"]; - + Color = "AZURE"; - + Result = OPI_Bitrix24.ChangeChatColor(URL, ChatID, Color); - + OPI_TestDataRetrieval.WriteLog(Result, "ChangeChatColor (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; ChatID = FunctionParameters["Bitrix24_ChatID"]; - + Color = "PURPLE"; - + Result = OPI_Bitrix24.ChangeChatColor(URL, ChatID, Color, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "ChangeChatColor", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_ChangeChatPicture(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; ChatID = FunctionParameters["Bitrix24_HookChatID"]; Image = FunctionParameters["Picture2"]; - + Result = OPI_Bitrix24.ChangeChatPicture(URL, ChatID, Image); - + OPI_TestDataRetrieval.WriteLog(Result, "ChangeChatPicture (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; ChatID = FunctionParameters["Bitrix24_ChatID"]; Result = OPI_Bitrix24.ChangeChatPicture(URL, ChatID, Image, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "ChangeChatPicture", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_DisableChatNotifications(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; ChatID = FunctionParameters["Bitrix24_HookChatID"]; - + Result = OPI_Bitrix24.DisableChatNotifications(URL, ChatID); - + OPI_TestDataRetrieval.WriteLog(Result, "DisableChatNotifications (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; ChatID = FunctionParameters["Bitrix24_ChatID"]; - + Result = OPI_Bitrix24.DisableChatNotifications(URL, ChatID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "DisableChatNotifications", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_EnableChatNotifications(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; ChatID = FunctionParameters["Bitrix24_HookChatID"]; - + Result = OPI_Bitrix24.EnableChatNotifications(URL, ChatID); - + OPI_TestDataRetrieval.WriteLog(Result, "EnableChatNotifications (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; ChatID = FunctionParameters["Bitrix24_ChatID"]; - + Result = OPI_Bitrix24.EnableChatNotifications(URL, ChatID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "EnableChatNotifications", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_ChangeChatOwner(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; ChatID = FunctionParameters["Bitrix24_HookChatID"]; - + UserID = 10; - + Result = OPI_Bitrix24.ChangeChatOwner(URL, ChatID, UserID); - + OPI_TestDataRetrieval.WriteLog(Result, "ChangeChatOwner (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; ChatID = FunctionParameters["Bitrix24_ChatID"]; - + Result = OPI_Bitrix24.ChangeChatOwner(URL, ChatID, UserID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "ChangeChatOwner", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_GetChatMessagesList(FunctionParameters) - URL = FunctionParameters["Bitrix24_URL"]; - ChatID = "chat4"; - + URL = FunctionParameters["Bitrix24_URL"]; + ChatID = "chat4"; + Result = OPI_Bitrix24.GetChatMessagesList(URL, ChatID); - + OPI_TestDataRetrieval.WriteLog(Result, "GetChatMessagesList (wh)", "Bitrix24"); - + Check_BitrixMessages(Result); // SKIP - + MessageID = Result["result"]["messages"][0]["id"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_ChatMessageID", MessageID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_ChatMessageID", MessageID); // SKIP FunctionParameters.Insert("Bitrix24_ChatMessageID", MessageID); // SKIP - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; UserID = 10; - + Result = OPI_Bitrix24.GetChatMessagesList(URL, UserID, , 0, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetChatMessagesList", "Bitrix24"); - + Check_BitrixMessages(Result); - - MessageID = Result["result"]["messages"][0]["id"]; - OPI_TestDataRetrieval.WriteParameter("Bitrix24_UserMessageID", MessageID); - FunctionParameters.Insert("Bitrix24_UserMessageID", MessageID); - + + MessageID = Result["result"]["messages"][0]["id"]; + OPI_TestDataRetrieval.WriteParameter("Bitrix24_UserMessageID", MessageID); + FunctionParameters.Insert("Bitrix24_UserMessageID", MessageID); + EndProcedure Procedure Bitrix24_MarkMessageAsReaded(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - ChatID = "chat" + FunctionParameters["Bitrix24_HookChatID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + ChatID = "chat" + FunctionParameters["Bitrix24_HookChatID"]; MessageID = FunctionParameters["Bitrix24_ChatMessageID"]; - + Result = OPI_Bitrix24.MarkMessageAsReaded(URL, ChatID, MessageID); - + OPI_TestDataRetrieval.WriteLog(Result, "MarkMessageAsReaded (wh)", "Bitrix24"); - + Check_BitrixDialog(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; - UserID = 10; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; + UserID = 10; MessageID = FunctionParameters["Bitrix24_UserMessageID"]; - + Result = OPI_Bitrix24.MarkMessageAsReaded(URL, UserID, MessageID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "MarkMessageAsReaded", "Bitrix24"); - + Check_BitrixDialog(Result); - + EndProcedure Procedure Bitrix24_MarkMessageAsUnreaded(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - ChatID = "chat" + FunctionParameters["Bitrix24_HookChatID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + ChatID = "chat" + FunctionParameters["Bitrix24_HookChatID"]; MessageID = FunctionParameters["Bitrix24_ChatMessageID"]; - + Result = OPI_Bitrix24.MarkMessageAsUnreaded(URL, ChatID, MessageID); - + OPI_TestDataRetrieval.WriteLog(Result, "MarkMessageAsUnreaded)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; - UserID = 10; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; + UserID = 10; MessageID = FunctionParameters["Bitrix24_UserMessageID"]; - + Result = OPI_Bitrix24.MarkMessageAsUnreaded(URL, UserID, MessageID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "MarkMessageAsUnreaded", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_GetDialog(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - ChatID = "chat" + FunctionParameters["Bitrix24_HookChatID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + ChatID = "chat" + FunctionParameters["Bitrix24_HookChatID"]; Result = OPI_Bitrix24.GetDialog(URL, ChatID); - + OPI_TestDataRetrieval.WriteLog(Result, "GetDialog (wh)", "Bitrix24"); - + Check_BitrixMessage(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; UserID = 10; - + Result = OPI_Bitrix24.GetDialog(URL, UserID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetDialog", "Bitrix24"); - + Check_BitrixMessage(Result); - + EndProcedure Procedure Bitrix24_GetChatMembersList(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - ChatID = "chat" + FunctionParameters["Bitrix24_HookChatID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + ChatID = "chat" + FunctionParameters["Bitrix24_HookChatID"]; Result = OPI_Bitrix24.GetChatMembersList(URL, ChatID); - + OPI_TestDataRetrieval.WriteLog(Result, "GetChatMembersList)", "Bitrix24"); - + Check_BitrixArray(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; UserID = 10; - + Result = OPI_Bitrix24.GetChatMembersList(URL, UserID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetChatMembersList", "Bitrix24"); - + Check_BitrixArray(Result); - + EndProcedure Procedure Bitrix24_SendWritingNotification(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - ChatID = "chat" + FunctionParameters["Bitrix24_HookChatID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + ChatID = "chat" + FunctionParameters["Bitrix24_HookChatID"]; Result = OPI_Bitrix24.SendWritingNotification(URL, ChatID); - + OPI_TestDataRetrieval.WriteLog(Result, "SendWritingNotification (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; UserID = 10; - + Result = OPI_Bitrix24.SendWritingNotification(URL, UserID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "SendWritingNotification", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_ReadAll(FunctionParameters) - + URL = FunctionParameters["Bitrix24_URL"]; Result = OPI_Bitrix24.ReadAll(URL); - + OPI_TestDataRetrieval.WriteLog(Result, "ReadAll (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.ReadAll(URL, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "ReadAll", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_SendMessage(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - ChatID = "chat" + FunctionParameters["Bitrix24_HookChatID"]; - Text = "Message text"; - Image = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/service/test_data/picture.jpg"; - File = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; - + + URL = FunctionParameters["Bitrix24_URL"]; + ChatID = "chat" + FunctionParameters["Bitrix24_HookChatID"]; + Text = "Message text"; + Image = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/service/test_data/picture.jpg"; + File = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; + Attachments = New Array; - Attachments.Add(OPI_Bitrix24.GetPictureBlock("Image1", Image)); + Attachments.Add(OPI_Bitrix24.GetPictureBlock("Image1" , Image)); Attachments.Add(OPI_Bitrix24.GetFileBlock("File1.docx", File)); Result = OPI_Bitrix24.SendMessage(URL, ChatID, Text, Attachments); - + OPI_TestDataRetrieval.WriteLog(Result, "SendMessage)", "Bitrix24"); - + Check_BitrixNumber(Result); // SKIP - + MessageID = Result["result"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_ChatMessageID", MessageID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_ChatMessageID", MessageID); // SKIP FunctionParameters.Insert("Bitrix24_ChatMessageID", MessageID); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; UserID = 10; - + Result = OPI_Bitrix24.SendMessage(URL, UserID, Text, , Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "SendMessage", "Bitrix24"); - + Check_BitrixNumber(Result); - - MessageID = Result["result"]; - OPI_TestDataRetrieval.WriteParameter("Bitrix24_UserMessageID", MessageID); - FunctionParameters.Insert("Bitrix24_UserMessageID", MessageID); - + + MessageID = Result["result"]; + OPI_TestDataRetrieval.WriteParameter("Bitrix24_UserMessageID", MessageID); + FunctionParameters.Insert("Bitrix24_UserMessageID", MessageID); + EndProcedure Procedure Bitrix24_EditMessage(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; MessageID = FunctionParameters["Bitrix24_ChatMessageID"]; - + Text = "New message text"; Result = OPI_Bitrix24.EditMessage(URL, MessageID, Text); - + OPI_TestDataRetrieval.WriteLog(Result, "EditMessage (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; MessageID = FunctionParameters["Bitrix24_UserMessageID"]; - + Image = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/service/test_data/picture.jpg"; - File = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; - + File = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; + Attachments = New Array; - Attachments.Add(OPI_Bitrix24.GetPictureBlock("Image1", Image)); + Attachments.Add(OPI_Bitrix24.GetPictureBlock("Image1" , Image)); Attachments.Add(OPI_Bitrix24.GetFileBlock("File1.docx", File)); - + Result = OPI_Bitrix24.EditMessage(URL, MessageID, Text, Attachments, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "EditMessage", "Bitrix24"); - - Check_BitrixTrue(Result); - + + Check_BitrixTrue(Result); + EndProcedure Procedure Bitrix24_DeleteMessage(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; MessageID = FunctionParameters["Bitrix24_ChatMessageID"]; Result = OPI_Bitrix24.DeleteMessage(URL, MessageID); - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteMessage (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; MessageID = FunctionParameters["Bitrix24_UserMessageID"]; - + Result = OPI_Bitrix24.DeleteMessage(URL, MessageID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteMessage", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_SetMessageReaction(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; MessageID = FunctionParameters["Bitrix24_ChatMessageID"]; Result = OPI_Bitrix24.SetMessageReaction(URL, MessageID); - + OPI_TestDataRetrieval.WriteLog(Result, "SetMessageReaction (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; MessageID = FunctionParameters["Bitrix24_UserMessageID"]; - + Result = OPI_Bitrix24.SetMessageReaction(URL, MessageID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "SetMessageReaction", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_GetChatFilesFolder(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - ChatID = FunctionParameters["Bitrix24_HookChatID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + ChatID = FunctionParameters["Bitrix24_HookChatID"]; Result = OPI_Bitrix24.GetChatFilesFolder(URL, ChatID); - + OPI_TestDataRetrieval.WriteLog(Result, "GetChatFilesFolder)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; ChatID = FunctionParameters["Bitrix24_ChatID"]; - + Result = OPI_Bitrix24.GetChatFilesFolder(URL, ChatID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetChatFilesFolder", "Bitrix24"); - + Check_BitrixObject(Result); - + EndProcedure Procedure Bitrix24_SendFile(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - ChatID = FunctionParameters["Bitrix24_HookChatID"]; - File = FunctionParameters["Document"]; // Binary Data, URL or path to file + + URL = FunctionParameters["Bitrix24_URL"]; + ChatID = FunctionParameters["Bitrix24_HookChatID"]; + File = FunctionParameters["Document"]; // Binary Data, URL or path to file Description = "Very important file"; - + Directory = OPI_Bitrix24.GetChatFilesFolder(URL, ChatID); - FolderID = Directory["result"]["ID"]; - + FolderID = Directory["result"]["ID"]; + UploadedFile = OPI_Bitrix24.UploadFileToFolder(URL, "Imortant doc.docx", File, FolderID); - FileID = UploadedFile["result"]["ID"]; + FileID = UploadedFile["result"]["ID"]; Result = OPI_Bitrix24.SendFile(URL, ChatID, FileID, Description); - + OPI_TestDataRetrieval.WriteLog(Result, "SendFile)", "Bitrix24"); - + Check_BitrixFileMessage(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; ChatID = FunctionParameters["Bitrix24_ChatID"]; - + Directory = OPI_Bitrix24.GetChatFilesFolder(URL, ChatID, Token); - FolderID = Directory["result"]["ID"]; - + FolderID = Directory["result"]["ID"]; + UploadedFile = OPI_Bitrix24.UploadFileToFolder(URL, "Imortant doc.docx", File, FolderID, Token); - FileID = UploadedFile["result"]["ID"]; + FileID = UploadedFile["result"]["ID"]; Result = OPI_Bitrix24.SendFile(URL, ChatID, FileID, Description, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "SendFile", "Bitrix24"); - + Check_BitrixFileMessage(Result); EndProcedure Procedure Bitrix24_GetUsers(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; ArrayOfUsers = New Array; - + ArrayOfUsers.Add(1); ArrayOfUsers.Add(10); Result = OPI_Bitrix24.GetUsers(URL, ArrayOfUsers); - + OPI_TestDataRetrieval.WriteLog(Result, "GetUsers (wh)", "Bitrix24"); - + Check_BitrixMap(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; UserIDs = 10; - + Result = OPI_Bitrix24.GetUsers(URL, UserIDs, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetUsers", "Bitrix24"); - + Check_BitrixMap(Result); - + EndProcedure Procedure Bitrix24_GetUserStatus(FunctionParameters) - + URL = FunctionParameters["Bitrix24_URL"]; Result = OPI_Bitrix24.GetUserStatus(URL); - + OPI_TestDataRetrieval.WriteLog(Result, "GetUserStatus (wh)", "Bitrix24"); - + Check_BitrixString(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetUserStatus(URL, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetUserStatus", "Bitrix24"); - + Check_BitrixString(Result); - + EndProcedure Procedure Bitrix24_SetUserStatus(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; Status = "dnd"; Result = OPI_Bitrix24.SetUserStatus(URL, Status); - + OPI_TestDataRetrieval.WriteLog(Result, "SetUserStatus (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; Status = "away"; - + Result = OPI_Bitrix24.SetUserStatus(URL, Status, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "SetUserStatus", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_CreatePersonalNotification(FunctionParameters) - + UserID = 1; - - URL = FunctionParameters["Bitrix24_URL"]; - Text = "Message text"; + + URL = FunctionParameters["Bitrix24_URL"]; + Text = "Message text"; Image = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/service/test_data/picture.jpg"; - File = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; - + File = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; + Attachments = New Array; - Attachments.Add(OPI_Bitrix24.GetPictureBlock("Image1", Image)); + Attachments.Add(OPI_Bitrix24.GetPictureBlock("Image1" , Image)); Attachments.Add(OPI_Bitrix24.GetFileBlock("File1.docx", File)); Result = OPI_Bitrix24.CreatePersonalNotification(URL, UserID, Text, ,Attachments); - + OPI_TestDataRetrieval.WriteLog(Result, "CreatePersonalNotification)", "Bitrix24"); - + Check_BitrixNumber(Result); // SKIP - + MessageID = Result["result"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_PersoalHookNotifyID", MessageID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_PersoalHookNotifyID", MessageID); // SKIP FunctionParameters.Insert("Bitrix24_PersoalHookNotifyID", MessageID); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; - Tag = "New"; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; + Tag = "New"; UserID = 10; - + Result = OPI_Bitrix24.CreatePersonalNotification(URL, UserID, Text, Tag, , Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CreatePersonalNotification", "Bitrix24"); - + Check_BitrixNumber(Result); - - MessageID = Result["result"]; - OPI_TestDataRetrieval.WriteParameter("Bitrix24_PersoalNotifyID", MessageID); - FunctionParameters.Insert("Bitrix24_PersoalNotifyID", MessageID); - + + MessageID = Result["result"]; + OPI_TestDataRetrieval.WriteParameter("Bitrix24_PersoalNotifyID", MessageID); + FunctionParameters.Insert("Bitrix24_PersoalNotifyID", MessageID); + EndProcedure Procedure Bitrix24_CreateSystemNotification(FunctionParameters) - + UserID = 1; - - URL = FunctionParameters["Bitrix24_URL"]; - Text = "Message text"; + + URL = FunctionParameters["Bitrix24_URL"]; + Text = "Message text"; Image = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/service/test_data/picture.jpg"; - File = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; - + File = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; + Attachments = New Array; - Attachments.Add(OPI_Bitrix24.GetPictureBlock("Image1", Image)); + Attachments.Add(OPI_Bitrix24.GetPictureBlock("Image1" , Image)); Attachments.Add(OPI_Bitrix24.GetFileBlock("File1.docx", File)); Result = OPI_Bitrix24.CreateSystemNotification(URL, UserID, Text, ,Attachments); - + OPI_TestDataRetrieval.WriteLog(Result, "CreateSystemNotification (wh)", "Bitrix24"); - + Check_BitrixNumber(Result); // SKIP - + MessageID = Result["result"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_SystemHookNotifyID", MessageID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_SystemHookNotifyID", MessageID); // SKIP FunctionParameters.Insert("Bitrix24_SystemHookNotifyID", MessageID); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; - Tag = "New"; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; + Tag = "New"; UserID = 10; - + Result = OPI_Bitrix24.CreateSystemNotification(URL, UserID, Text, Tag, , Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CreateSystemNotification", "Bitrix24"); - + Check_BitrixNumber(Result); - - MessageID = Result["result"]; - OPI_TestDataRetrieval.WriteParameter("Bitrix24_SystemNotifyID", MessageID); - FunctionParameters.Insert("Bitrix24_SystemNotifyID", MessageID); - + + MessageID = Result["result"]; + OPI_TestDataRetrieval.WriteParameter("Bitrix24_SystemNotifyID", MessageID); + FunctionParameters.Insert("Bitrix24_SystemNotifyID", MessageID); + EndProcedure Procedure Bitrix24_DeleteNotification(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; NotificationID = FunctionParameters["Bitrix24_PersoalHookNotifyID"]; - + Result = OPI_Bitrix24.DeleteNotification(URL, NotificationID); - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteNotification", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; NotificationID = FunctionParameters["Bitrix24_PersoalNotifyID"]; - + Result = OPI_Bitrix24.DeleteNotification(URL, NotificationID, Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "DeleteNotification (app)", "Bitrix24"); - + Check_BitrixBool(Result); - + EndProcedure #EndRegion @@ -9540,36 +9540,36 @@ EndProcedure Procedure YandexDisk_GetDiskInfo(FunctionParameters) - Token = FunctionParameters["YandexDisk_Token"]; + Token = FunctionParameters["YandexDisk_Token"]; Result = OPI_YandexDisk.GetDiskInformation(Token); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "GetDiskInformation", "YandexDisk"); - + Check_YaDiskDrive(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure YandexDisk_CreateFolder(FunctionParameters) Token = FunctionParameters["YandexDisk_Token"]; - Path = "/" + String(New UUID); - + Path = "/" + String(New UUID); + Result = OPI_YandexDisk.CreateFolder(Token, Path); - + // END - + OPI_TestDataRetrieval.WriteLog(Result, "CreateFolder", "YandexDisk"); - + Check_YaDiskFolder(Result, Path); - + OPI_YandexDisk.DeleteObject(Token, Path, False); - + OPI_Tools.Pause(5); - + EndProcedure #EndRegion diff --git a/src/en/OInt/tools/Modules/OPI_TestDataRetrieval.os b/src/en/OInt/tools/Modules/OPI_TestDataRetrieval.os index b9ac6436a3..2a5de65d55 100644 --- a/src/en/OInt/tools/Modules/OPI_TestDataRetrieval.os +++ b/src/en/OInt/tools/Modules/OPI_TestDataRetrieval.os @@ -46,404 +46,404 @@ #Region Internal Function GetTestingSectionMapping() Export - + StandardDependencies = "[Decode, Build]"; - GoogleDependencies = "Testing-GoogleWorkspace"; - + GoogleDependencies = "Testing-GoogleWorkspace"; + Sections = New Structure; - Sections.Insert("Telegram" , StandardDependencies); - Sections.Insert("VK" , StandardDependencies); - Sections.Insert("Viber" , StandardDependencies); - Sections.Insert("Twitter" , StandardDependencies); - Sections.Insert("YandexDisk" , StandardDependencies); + Sections.Insert("Telegram" , StandardDependencies); + Sections.Insert("VK" , StandardDependencies); + Sections.Insert("Viber" , StandardDependencies); + Sections.Insert("Twitter" , StandardDependencies); + Sections.Insert("YandexDisk" , StandardDependencies); Sections.Insert("GoogleWorkspace", StandardDependencies); - Sections.Insert("GoogleCalendar" , GoogleDependencies); - Sections.Insert("GoogleDrive" , GoogleDependencies); - Sections.Insert("GoogleSheets" , GoogleDependencies); - Sections.Insert("Notion" , StandardDependencies); - Sections.Insert("Slack" , StandardDependencies); - Sections.Insert("Airtable" , StandardDependencies); - Sections.Insert("Dropbox" , StandardDependencies); - Sections.Insert("Bitrix24" , StandardDependencies); - + Sections.Insert("GoogleCalendar" , GoogleDependencies); + Sections.Insert("GoogleDrive" , GoogleDependencies); + Sections.Insert("GoogleSheets" , GoogleDependencies); + Sections.Insert("Notion" , StandardDependencies); + Sections.Insert("Slack" , StandardDependencies); + Sections.Insert("Airtable" , StandardDependencies); + Sections.Insert("Dropbox" , StandardDependencies); + Sections.Insert("Bitrix24" , StandardDependencies); + Return Sections; - + EndFunction Function GetTestTable() Export - - Telegram = "Telegram"; + + Telegram = "Telegram"; VKontakte = "VK"; - YDisk = "YandexDisk"; - Calendar = "GoogleCalendar"; - Twitter = "Twitter"; - Viber = "Viber"; - Drive = "GoogleDrive"; - VSpace = "GoogleWorkspace"; - Notion = "Notion"; - Slack = "Slack"; - Tables = "GoogleSheets"; - AirT = "Airtable"; - Dropbox = "Dropbox"; - Bitrix = "Bitrix24"; - + YDisk = "YandexDisk"; + Calendar = "GoogleCalendar"; + Twitter = "Twitter"; + Viber = "Viber"; + Drive = "GoogleDrive"; + VSpace = "GoogleWorkspace"; + Notion = "Notion"; + Slack = "Slack"; + Tables = "GoogleSheets"; + AirT = "Airtable"; + Dropbox = "Dropbox"; + Bitrix = "Bitrix24"; + TestTable = New ValueTable; TestTable.Columns.Add("Method"); TestTable.Columns.Add("Synonym"); TestTable.Columns.Add("Section"); - - NewTest(TestTable, "TelegramAPI_GetBotInfo" , "Get bot information" , Telegram); - NewTest(TestTable, "TelegramAPI_GetUpdates" , "Get updates" , Telegram); - NewTest(TestTable, "TelegramAPI_SetWebhook" , "Set Webhook" , Telegram); - NewTest(TestTable, "TelegramAPI_SendTextMessage" , "Send text message" , Telegram); - NewTest(TestTable, "TelegramAPI_SendImage" , "Send image" , Telegram); - NewTest(TestTable, "TelegramAPI_SendVideo" , "Send video" , Telegram); - NewTest(TestTable, "TelegramAPI_SendAudio" , "Send audio" , Telegram); - NewTest(TestTable, "TelegramAPI_SendDocument" , "Send document" , Telegram); - NewTest(TestTable, "TelegramAPI_SendGIF" , "Send GIF" , Telegram); - NewTest(TestTable, "TelegramAPI_SendMediaGroup" , "Send mediagroup" , Telegram); - NewTest(TestTable, "TelegramAPI_SendLocation" , "Send location" , Telegram); - NewTest(TestTable, "TelegramAPI_SendContact" , "Send contact" , Telegram); - NewTest(TestTable, "TelegramAPI_SendPoll" , "Send poll" , Telegram); - NewTest(TestTable, "TelegramAPI_ForwardMessage" , "Forward message" , Telegram); - NewTest(TestTable, "TelegramAPI_BanUnban" , "Ban/Unban" , Telegram); - NewTest(TestTable, "TelegramAPI_CreateInvitationLink" , "Create invitation link" , Telegram); - NewTest(TestTable, "TelegramAPI_PinUnpinMessage" , "Pin/Unpin message" , Telegram); - NewTest(TestTable, "TelegramAPI_GetMemberCount" , "Get participant count" , Telegram); - NewTest(TestTable, "TelegramAPI_GetForumAvatarsList", "Get forum avatars list", Telegram); + + NewTest(TestTable, "TelegramAPI_GetBotInfo" , "Get bot information" , Telegram); + NewTest(TestTable, "TelegramAPI_GetUpdates" , "Get updates" , Telegram); + NewTest(TestTable, "TelegramAPI_SetWebhook" , "Set Webhook" , Telegram); + NewTest(TestTable, "TelegramAPI_SendTextMessage" , "Send text message" , Telegram); + NewTest(TestTable, "TelegramAPI_SendImage" , "Send image" , Telegram); + NewTest(TestTable, "TelegramAPI_SendVideo" , "Send video" , Telegram); + NewTest(TestTable, "TelegramAPI_SendAudio" , "Send audio" , Telegram); + NewTest(TestTable, "TelegramAPI_SendDocument" , "Send document" , Telegram); + NewTest(TestTable, "TelegramAPI_SendGIF" , "Send GIF" , Telegram); + NewTest(TestTable, "TelegramAPI_SendMediaGroup" , "Send mediagroup" , Telegram); + NewTest(TestTable, "TelegramAPI_SendLocation" , "Send location" , Telegram); + NewTest(TestTable, "TelegramAPI_SendContact" , "Send contact" , Telegram); + NewTest(TestTable, "TelegramAPI_SendPoll" , "Send poll" , Telegram); + NewTest(TestTable, "TelegramAPI_ForwardMessage" , "Forward message" , Telegram); + NewTest(TestTable, "TelegramAPI_BanUnban" , "Ban/Unban" , Telegram); + NewTest(TestTable, "TelegramAPI_CreateInvitationLink" , "Create invitation link" , Telegram); + NewTest(TestTable, "TelegramAPI_PinUnpinMessage" , "Pin/Unpin message" , Telegram); + NewTest(TestTable, "TelegramAPI_GetMemberCount" , "Get participant count" , Telegram); + NewTest(TestTable, "TelegramAPI_GetForumAvatarsList" , "Get forum avatars list" , Telegram); NewTest(TestTable, "TelegramAPI_CreateDeleteForumTopic" , "Create/Delete forum topic" , Telegram); - NewTest(TestTable, "TelegramAPI_ChangeMainTopicName" , "Change main topic name" , Telegram); - NewTest(TestTable, "TelegramAPI_HideShowMainTopic" , "Hide/Show main topic" , Telegram); - - NewTest(TestTable, "VKAPI_CreateTokenLink" , "Create token retrieval link", VKontakte); - NewTest(TestTable, "VKAPI_CreateDeletePost" , "Create/Delete post" , VKontakte); - NewTest(TestTable, "VKAPI_CreateCompositePost" , "Create/Delete composite post" , VKontakte); - NewTest(TestTable, "VKAPI_CreatePoll" , "Create poll" , VKontakte); - NewTest(TestTable, "VKAPI_SaveDeleteImage" , "Add/Delete image" , VKontakte); - NewTest(TestTable, "VKAPI_CreateStory" , "Create story" , VKontakte); - NewTest(TestTable, "VKAPI_DiscussionMethods" , "Actions with discussions" , VKontakte); - NewTest(TestTable, "VKAPI_LikeRepostComment" , "Like/Repost/Comment" , VKontakte); - NewTest(TestTable, "VKAPI_GetStatistics" , "Get statistics" , VKontakte); - NewTest(TestTable, "VKAPI_GetPostStatistics" , "Get post statistics" , VKontakte); - NewTest(TestTable, "VKAPI_CreateAdCampaign" , "Create advertising campaign" , VKontakte); - NewTest(TestTable, "VKAPI_SendMessage" , "Send message" , VKontakte); - NewTest(TestTable, "VKAPI_GetProductCategories" , "Get product categories" , VKontakte); - NewTest(TestTable, "VKAPI_CreateProductSelection" , "Create product and selection" , VKontakte); + NewTest(TestTable, "TelegramAPI_ChangeMainTopicName" , "Change main topic name" , Telegram); + NewTest(TestTable, "TelegramAPI_HideShowMainTopic" , "Hide/Show main topic" , Telegram); + + NewTest(TestTable, "VKAPI_CreateTokenLink" , "Create token retrieval link" , VKontakte); + NewTest(TestTable, "VKAPI_CreateDeletePost" , "Create/Delete post" , VKontakte); + NewTest(TestTable, "VKAPI_CreateCompositePost" , "Create/Delete composite post" , VKontakte); + NewTest(TestTable, "VKAPI_CreatePoll" , "Create poll" , VKontakte); + NewTest(TestTable, "VKAPI_SaveDeleteImage" , "Add/Delete image" , VKontakte); + NewTest(TestTable, "VKAPI_CreateStory" , "Create story" , VKontakte); + NewTest(TestTable, "VKAPI_DiscussionMethods" , "Actions with discussions" , VKontakte); + NewTest(TestTable, "VKAPI_LikeRepostComment" , "Like/Repost/Comment" , VKontakte); + NewTest(TestTable, "VKAPI_GetStatistics" , "Get statistics" , VKontakte); + NewTest(TestTable, "VKAPI_GetPostStatistics" , "Get post statistics" , VKontakte); + NewTest(TestTable, "VKAPI_CreateAdCampaign" , "Create advertising campaign" , VKontakte); + NewTest(TestTable, "VKAPI_SendMessage" , "Send message" , VKontakte); + NewTest(TestTable, "VKAPI_GetProductCategories" , "Get product categories" , VKontakte); + NewTest(TestTable, "VKAPI_CreateProductSelection" , "Create product and selection" , VKontakte); NewTest(TestTable, "VKAPI_CreateProductWithProperties" , "Create product with properties" , VKontakte); - NewTest(TestTable, "VKAPI_GetProductList" , "Get product list" , VKontakte); - NewTest(TestTable, "VKAPI_GetSelectionList" , "Get selection list" , VKontakte); - NewTest(TestTable, "VKAPI_GetPropertyList" , "Get property list" , VKontakte); - NewTest(TestTable, "VKAPI_GetOrderList" , "Get order list" , VKontakte); - NewTest(TestTable, "VKAPI_UploadVideo" , "Upload video" , VKontakte); - - NewTest(TestTable, "YDisk_GetDiskInfo" , "Get disk information" , YDisk); - NewTest(TestTable, "YDisk_CreateFolder" , "Create folder" , YDisk); - NewTest(TestTable, "YDisk_UploadByUrlAndGetObject", "Upload by URL and get" , YDisk); - NewTest(TestTable, "YDisk_UploadDeleteFile" , "Upload/Delete file" , YDisk); - NewTest(TestTable, "YDisk_CreateObjectCopy" , "Create object copy" , YDisk); - NewTest(TestTable, "YDisk_GetDownloadLink" , "Get download link" , YDisk); - NewTest(TestTable, "YDisk_GetFileList" , "Get list of files" , YDisk); - NewTest(TestTable, "YDisk_MoveObject" , "Move object" , YDisk); - NewTest(TestTable, "YDisk_PublicObjectActions" , "Actions with public objects", YDisk); - NewTest(TestTable, "YDisk_GetPublishedList" , "Get published list" , YDisk); - + NewTest(TestTable, "VKAPI_GetProductList" , "Get product list" , VKontakte); + NewTest(TestTable, "VKAPI_GetSelectionList" , "Get selection list" , VKontakte); + NewTest(TestTable, "VKAPI_GetPropertyList" , "Get property list" , VKontakte); + NewTest(TestTable, "VKAPI_GetOrderList" , "Get order list" , VKontakte); + NewTest(TestTable, "VKAPI_UploadVideo" , "Upload video" , VKontakte); + + NewTest(TestTable, "YDisk_GetDiskInfo" , "Get disk information" , YDisk); + NewTest(TestTable, "YDisk_CreateFolder" , "Create folder" , YDisk); + NewTest(TestTable, "YDisk_UploadByUrlAndGetObject", "Upload by URL and get" , YDisk); + NewTest(TestTable, "YDisk_UploadDeleteFile" , "Upload/Delete file" , YDisk); + NewTest(TestTable, "YDisk_CreateObjectCopy" , "Create object copy" , YDisk); + NewTest(TestTable, "YDisk_GetDownloadLink" , "Get download link" , YDisk); + NewTest(TestTable, "YDisk_GetFileList" , "Get list of files" , YDisk); + NewTest(TestTable, "YDisk_MoveObject" , "Move object" , YDisk); + NewTest(TestTable, "YDisk_PublicObjectActions" , "Actions with public objects", YDisk); + NewTest(TestTable, "YDisk_GetPublishedList" , "Get published list" , YDisk); + NewTest(TestTable, "GV_GetAuthorizationLink" , "Get authorization link" , VSpace); - NewTest(TestTable, "GV_GetToken" , "Get token" , VSpace); - NewTest(TestTable, "GV_UpdateToken" , "Refresh token" , VSpace); - - NewTest(TestTable, "GC_GetCalendarList" , "Get list of calendars" , Calendar); + NewTest(TestTable, "GV_GetToken" , "Get token" , VSpace); + NewTest(TestTable, "GV_UpdateToken" , "Refresh token" , VSpace); + + NewTest(TestTable, "GC_GetCalendarList" , "Get list of calendars" , Calendar); NewTest(TestTable, "GC_CreateDeleteCalendar" , "Create/Delete calendar" , Calendar); - NewTest(TestTable, "GC_CreateDeleteEvent" , "Create/Delete event" , Calendar); - NewTest(TestTable, "GC_GetEventList" , "Get list of events" , Calendar); - - NewTest(TestTable, "GD_GetCatalogList" , "Get list of directories" , Drive); - NewTest(TestTable, "GD_UploadDeleteFile" , "Upload/Delete file" , Drive); - NewTest(TestTable, "GD_CreateDeleteComment" , "Create/Delete Comment" , Drive); - NewTest(TestTable, "GD_CreateCatalog" , "Create/Delete catalog" , Drive); - - NewTest(TestTable, "GT_CreateTable" , "Create table" , Tables); - NewTest(TestTable, "GT_GetTable" , "Get table" , Tables); + NewTest(TestTable, "GC_CreateDeleteEvent" , "Create/Delete event" , Calendar); + NewTest(TestTable, "GC_GetEventList" , "Get list of events" , Calendar); + + NewTest(TestTable, "GD_GetCatalogList" , "Get list of directories" , Drive); + NewTest(TestTable, "GD_UploadDeleteFile" , "Upload/Delete file" , Drive); + NewTest(TestTable, "GD_CreateDeleteComment" , "Create/Delete Comment" , Drive); + NewTest(TestTable, "GD_CreateCatalog" , "Create/Delete catalog" , Drive); + + NewTest(TestTable, "GT_CreateTable" , "Create table" , Tables); + NewTest(TestTable, "GT_GetTable" , "Get table" , Tables); NewTest(TestTable, "GT_FillClearCells" , "Fill/Clear cells" , Tables); - + NewTest(TestTable, "Twitter_GetAuthorizationLink" , "Get authorization link" , Twitter); - NewTest(TestTable, "Twitter_UpdateToken" , "Refresh token" , Twitter); - NewTest(TestTable, "Twitter_CreateTextTweet" , "Text tweet" , Twitter); - NewTest(TestTable, "Twitter_CreateTweetWithImage" , "Tweet with image" , Twitter); - NewTest(TestTable, "Twitter_CreateTweetWithVideo" , "Tweet with video" , Twitter); - NewTest(TestTable, "Twitter_CreateTweetWithGif" , "Tweet with gif" , Twitter); - NewTest(TestTable, "Twitter_CreateTweetWithPoll" , "Tweet with poll" , Twitter); - - NewTest(TestTable, "Viber_GetChannelInfo" , "Get channel info" , Viber); - NewTest(TestTable, "Viber_GetUserData" , "Get user data" , Viber); - NewTest(TestTable, "Viber_GetOnlineUsers" , "Get online users" , Viber); + NewTest(TestTable, "Twitter_UpdateToken" , "Refresh token" , Twitter); + NewTest(TestTable, "Twitter_CreateTextTweet" , "Text tweet" , Twitter); + NewTest(TestTable, "Twitter_CreateTweetWithImage" , "Tweet with image" , Twitter); + NewTest(TestTable, "Twitter_CreateTweetWithVideo" , "Tweet with video" , Twitter); + NewTest(TestTable, "Twitter_CreateTweetWithGif" , "Tweet with gif" , Twitter); + NewTest(TestTable, "Twitter_CreateTweetWithPoll" , "Tweet with poll" , Twitter); + + NewTest(TestTable, "Viber_GetChannelInfo" , "Get channel info" , Viber); + NewTest(TestTable, "Viber_GetUserData" , "Get user data" , Viber); + NewTest(TestTable, "Viber_GetOnlineUsers" , "Get online users" , Viber); NewTest(TestTable, "Viber_SendTextMessage" , "Send text message" , Viber); - NewTest(TestTable, "Viber_SendImage" , "Send image" , Viber); - NewTest(TestTable, "Viber_SendFile" , "SendFile" , Viber); - NewTest(TestTable, "Viber_SendContact" , "Send contact" , Viber); - NewTest(TestTable, "Viber_SendLocation" , "Send location" , Viber); - NewTest(TestTable, "Viber_SendLink" , "Send link" , Viber); - - NewTest(TestTable, "Notion_CreatePage" , "Create page" , Notion); - NewTest(TestTable, "Notion_CreateEditDatabase" , "Create/Edit database" , Notion); - NewTest(TestTable, "Notion_GetPageInfo" , "Get page info" , Notion); - NewTest(TestTable, "Notion_GetDatabaseInfo" , "Get database info" , Notion); + NewTest(TestTable, "Viber_SendImage" , "Send image" , Viber); + NewTest(TestTable, "Viber_SendFile" , "SendFile" , Viber); + NewTest(TestTable, "Viber_SendContact" , "Send contact" , Viber); + NewTest(TestTable, "Viber_SendLocation" , "Send location" , Viber); + NewTest(TestTable, "Viber_SendLink" , "Send link" , Viber); + + NewTest(TestTable, "Notion_CreatePage" , "Create page" , Notion); + NewTest(TestTable, "Notion_CreateEditDatabase" , "Create/Edit database" , Notion); + NewTest(TestTable, "Notion_GetPageInfo" , "Get page info" , Notion); + NewTest(TestTable, "Notion_GetDatabaseInfo" , "Get database info" , Notion); NewTest(TestTable, "Notion_CreatePageInDatabase" , "Create page in database" , Notion); - NewTest(TestTable, "Notion_EditPageProperties" , "Edit page properties" , Notion); - NewTest(TestTable, "Notion_CreateDeleteBlock" , "Create/Delete block" , Notion); - NewTest(TestTable, "Notion_GetUsers" , "Get users" , Notion); - NewTest(TestTable, "Notion_GetUserData" , "Get user data" , Notion); - - NewTest(TestTable, "Slack_GetBotInfo" , "Get bot information" , Slack); - NewTest(TestTable, "Slack_GetUserList" , "Get user list" , Slack); - NewTest(TestTable, "Slack_GetRegionList" , "Get region list" , Slack); - NewTest(TestTable, "Slack_SendDeleteMessage" , "Send/Delete message" , Slack); - NewTest(TestTable, "Slack_SendDeleteEphemeral" , "Send/Delete ephemeral" , Slack); - NewTest(TestTable, "Slack_GetScheduledMessages" , "Get scheduled messages" , Slack); - NewTest(TestTable, "Slack_CreateArchiveChannel" , "Create/Archive channel" , Slack); - NewTest(TestTable, "Slack_GetChannelList" , "Get channel list" , Slack); - NewTest(TestTable, "Slack_OpenCloseDialog" , "Open/Close dialog" , Slack); - NewTest(TestTable, "Slack_GetFileList" , "Get list of files" , Slack); - NewTest(TestTable, "Slack_UploadDeleteFile" , "Upload/Delete file" , Slack); - NewTest(TestTable, "Slack_GetExternalFileList" , "Get external file list" , Slack); + NewTest(TestTable, "Notion_EditPageProperties" , "Edit page properties" , Notion); + NewTest(TestTable, "Notion_CreateDeleteBlock" , "Create/Delete block" , Notion); + NewTest(TestTable, "Notion_GetUsers" , "Get users" , Notion); + NewTest(TestTable, "Notion_GetUserData" , "Get user data" , Notion); + + NewTest(TestTable, "Slack_GetBotInfo" , "Get bot information" , Slack); + NewTest(TestTable, "Slack_GetUserList" , "Get user list" , Slack); + NewTest(TestTable, "Slack_GetRegionList" , "Get region list" , Slack); + NewTest(TestTable, "Slack_SendDeleteMessage" , "Send/Delete message" , Slack); + NewTest(TestTable, "Slack_SendDeleteEphemeral" , "Send/Delete ephemeral" , Slack); + NewTest(TestTable, "Slack_GetScheduledMessages" , "Get scheduled messages" , Slack); + NewTest(TestTable, "Slack_CreateArchiveChannel" , "Create/Archive channel" , Slack); + NewTest(TestTable, "Slack_GetChannelList" , "Get channel list" , Slack); + NewTest(TestTable, "Slack_OpenCloseDialog" , "Open/Close dialog" , Slack); + NewTest(TestTable, "Slack_GetFileList" , "Get list of files" , Slack); + NewTest(TestTable, "Slack_UploadDeleteFile" , "Upload/Delete file" , Slack); + NewTest(TestTable, "Slack_GetExternalFileList" , "Get external file list" , Slack); NewTest(TestTable, "Slack_UploadDeleteExternalFile" , "Upload/Delete external file" , Slack); - - NewTest(TestTable, "AT_CreateDatabase" , "Create/Edit database" , AirT); - NewTest(TestTable, "AT_CreateTable" , "Create/Edit table" , AirT); - NewTest(TestTable, "AT_CreateField" , "Create/Edit field" , AirT); + + NewTest(TestTable, "AT_CreateDatabase" , "Create/Edit database" , AirT); + NewTest(TestTable, "AT_CreateTable" , "Create/Edit table" , AirT); + NewTest(TestTable, "AT_CreateField" , "Create/Edit field" , AirT); NewTest(TestTable, "AT_CreateDeleteRecords" , "Create/Delete records" , AirT); - - NewTest(TestTable, "DropboxAPI_GetUpdateToken" , "Get/Update token" , Dropbox); - NewTest(TestTable, "DropboxAPI_UploadFile" , "Upload file" , Dropbox); - NewTest(TestTable, "DropboxAPI_UploadFileByURL" , "Upload file by URL" , Dropbox); - NewTest(TestTable, "DropboxAPI_CreateFolder" , "Create folder" , Dropbox); - NewTest(TestTable, "DropboxAPI_CreateDeleteTag" , "Create/Delete tag" , Dropbox); - NewTest(TestTable, "DropboxAPI_GetAccount" , "Get account data" , Dropbox); - NewTest(TestTable, "DropboxAPI_AccessManagement" , "Access management" , Dropbox); + + NewTest(TestTable, "DropboxAPI_GetUpdateToken" , "Get/Update token" , Dropbox); + NewTest(TestTable, "DropboxAPI_UploadFile" , "Upload file" , Dropbox); + NewTest(TestTable, "DropboxAPI_UploadFileByURL" , "Upload file by URL" , Dropbox); + NewTest(TestTable, "DropboxAPI_CreateFolder" , "Create folder" , Dropbox); + NewTest(TestTable, "DropboxAPI_CreateDeleteTag" , "Create/Delete tag" , Dropbox); + NewTest(TestTable, "DropboxAPI_GetAccount" , "Get account data" , Dropbox); + NewTest(TestTable, "DropboxAPI_AccessManagement" , "Access management" , Dropbox); NewTest(TestTable, "DropboxAPI_GetFolderFileList" , "Get list of folder files" , Dropbox); - - NewTest(TestTable, "B24_TokenManagment" , "Token management" , Bitrix); - NewTest(TestTable, "B24_ServerTime" , "Server time" , Bitrix); - NewTest(TestTable, "B24_PostsManagment" , "Posts managment" , Bitrix); - NewTest(TestTable, "B24_TaskManagment" , "Tasks managment" , Bitrix); - NewTest(TestTable, "B24_CommentsManagment" , "Comments managment" , Bitrix); - NewTest(TestTable, "B24_WorkingWithDrive" , "Working with drive" , Bitrix); - NewTest(TestTable, "B24_Kanban" , "Kanban" , Bitrix); - NewTest(TestTable, "B24_Timekeeping" , "Timekeeping" , Bitrix); - NewTest(TestTable, "B24_ChatManagment" , "Chats works" , Bitrix); + + NewTest(TestTable, "B24_TokenManagment" , "Token management" , Bitrix); + NewTest(TestTable, "B24_ServerTime" , "Server time" , Bitrix); + NewTest(TestTable, "B24_PostsManagment" , "Posts managment" , Bitrix); + NewTest(TestTable, "B24_TaskManagment" , "Tasks managment" , Bitrix); + NewTest(TestTable, "B24_CommentsManagment" , "Comments managment" , Bitrix); + NewTest(TestTable, "B24_WorkingWithDrive" , "Working with drive" , Bitrix); + NewTest(TestTable, "B24_Kanban" , "Kanban" , Bitrix); + NewTest(TestTable, "B24_Timekeeping" , "Timekeeping" , Bitrix); + NewTest(TestTable, "B24_ChatManagment" , "Chats works" , Bitrix); NewTest(TestTable, "B24_NotificationsManagment" , "Notifications managment" , Bitrix); - + Return TestTable; - -EndFunction + +EndFunction Function ExpectsThat(Value) Export - + Try - - Module = GetCommonModule("ЮТест"); + + Module = GetCommonModule("ЮТест"); Ожидаем = TypeOf(Module) = Type("CommonModule"); - Return Module.ОжидаетЧто(Value); - + Return Module.ОжидаетЧто(Value); + Except Return Ожидаем.Что(Value); EndTry; - + EndFunction Function FormYAXTests() Export - - Module = GetCommonModule("ЮТТесты"); - Sections = GetTestingSectionMapping(); + + Module = GetCommonModule("ЮТТесты"); + Sections = GetTestingSectionMapping(); TestTable = GetTestTable(); - + For Each Section In Sections Do - + CurrentSection = Section.Key; - Filter = New Structure("Section", CurrentSection); - SectionTests = TestTable.FindRows(Filter); - + Filter = New Structure("Section", CurrentSection); + SectionTests = TestTable.FindRows(Filter); + Set = Module.ДобавитьТестовыйНабор(CurrentSection); - + For Each Test In SectionTests Do Set.ДобавитьСерверныйТест(Test.Method, Test.Synonym); EndDo; - + EndDo; - + Return ""; - + EndFunction Function FormAssertsTests() Export - - TestTable = GetTestTable(); + + TestTable = GetTestTable(); ArrayOfTests = New Array; - - For Each Test In TestTable Do + + For Each Test In TestTable Do ArrayOfTests.Add(Test.Method); EndDo; - + Return ArrayOfTests; - + EndFunction -Function GetParameter(Parameter) Export +Function GetParameter(Parameter) Export - Path = DataFilePath(); + Path = DataFilePath(); Return GetValueFromFile(Parameter, Path); EndFunction Function GetBinary(Parameter) Export - - Path = DataFilePath(); + + Path = DataFilePath(); LocalParameter = Parameter + "Local"; - MainValue = GetValueFromFile(Parameter , Path); - LocalValue = GetValueFromFile(LocalParameter, Path); - + MainValue = GetValueFromFile(Parameter , Path); + LocalValue = GetValueFromFile(LocalParameter, Path); + LocalFile = New File(LocalValue); - + If LocalFile.Exist() Then Value = New BinaryData(LocalValue); Else Value = MainValue; EndIf; - + If TypeOf(Value) = Type("String") Then - Value = GetFilePath(Value, LocalParameter); + Value = GetFilePath(Value, LocalParameter); EndIf; - + Return Value; - + EndFunction Function GetFilePath(Val Path, LocalParameter, Val SaveLocally = True) Export - - If StrFind(Path, "http") > 0 + + If StrFind(Path, "http") > 0 Or StrFind(Path, "www") > 0 Then - - TFN = GetTempFileName(); + + TFN = GetTempFileName(); CopyFile(Path, TFN); - Path = TFN; + Path = TFN; Binary = New BinaryData(Path); - + If SaveLocally Then WriteParameter(LocalParameter, TFN); Else DeleteFiles(TFN); EndIf; - + Else - + Binary = New BinaryData(Path); - + EndIf; - + Return Binary; - + EndFunction Procedure ParameterToCollection(Parameter, Collection) Export Value = GetParameter(Parameter); Collection.Insert(Parameter, Value); - + EndProcedure Procedure BinaryToCollection(Parameter, Collection) Export Value = GetBinary(Parameter); Collection.Insert(Parameter, Value); - + EndProcedure Procedure WriteParameter(Parameter, Value) Export - - Path = DataFilePath(); + + Path = DataFilePath(); WriteParameterToFile(Parameter, Value, Path); - + EndProcedure Procedure WriteLog(Val Result, Val Method, Val Library = "") Export - + Header = String(OPI_Tools.GetCurrentDate()) + " | " + Method; - + Try Data = OPI_Tools.JSONString(Result); Except Data = "Not JSON: " + String(Result); EndTry; - - Data = " " + Data; - + + Data = " " + Data; + Message(Header); Message(Chars.LF); Message(Data); Message(Chars.LF); Message("---------------------------------"); Message(Chars.LF); - + If ValueIsFilled(Library) Then WriteLogFile(Data, Method, Library); EndIf; - + EndProcedure #EndRegion #Region Private -Function GetValueFromFile(Parameter, Path) - - Values = OPI_Tools.ReadJSONFile(Path); +Function GetValueFromFile(Parameter, Path) + + Values = OPI_Tools.ReadJSONFile(Path); Return ?(Values.Property(Parameter), Values[Parameter], ""); - + EndFunction Function DataFilePath() - - Path = ""; + + Path = ""; PossiblePaths = New Array; PossiblePaths.Add("./data.json"); PossiblePaths.Add("C:\GDrive\Мой Диск\data.json"); PossiblePaths.Add("D:\GD\Мой Диск\data.json"); - + For Each PossiblePath In PossiblePaths Do - + RepositoryFile = New File(PossiblePath); - + If RepositoryFile.Exist() Then Path = PossiblePath; - EndIf; - + EndIf; + EndDo; - + Return Path; - + EndFunction Function GetCommonModule(Val Name) - - Module = Eval(Name); - - Return Module; + + Module = Eval(Name); + + Return Module; EndFunction Procedure NewTest(ValueTable, Val Method, Val Synonym, Val Section) - - NewTest = ValueTable.Add(); - NewTest.Method = Method; + + NewTest = ValueTable.Add(); + NewTest.Method = Method; NewTest.Synonym = Synonym; NewTest.Section = Section; - + EndProcedure Procedure WriteParameterToFile(Val Parameter, Val Value, Val Path) - + Values = OPI_Tools.ReadJSONFile(Path); Values.Insert(Parameter, Value); - Record = New JSONWriter; + Record = New JSONWriter; JSONWriterSettings = New JSONWriterSettings(JSONLineBreak.Auto, Chars.Tab); Record.OpenFile(Path, , , JSONWriterSettings); WriteJSON(Record, Values); @@ -452,37 +452,37 @@ Procedure WriteParameterToFile(Val Parameter, Val Value, Val Path) EndProcedure Procedure WriteLogFile(Val Data, Val Method, Val Library) - + Try - - LogPath = "./docs/ru/results"; + + LogPath = "./docs/ru/results"; LibraryLogPath = LogPath + "/" + Library; - + LogDirectory = New File(LogPath); - + If Not LogDirectory.Exist() Then CreateDirectory(LogPath); EndIf; - + LibraryLogCatalog = New File(LibraryLogPath); - + If Not LibraryLogCatalog.Exist() Then CreateDirectory(LibraryLogPath); EndIf; - + FilePath = LibraryLogPath + "/" + Method + ".log"; - LogFile = New File(FilePath); - + LogFile = New File(FilePath); + If Not LogFile.Exist() Then LogDocument = New TextDocument; LogDocument.SetText(Data); LogDocument.Write(FilePath); EndIf; - + Except - Message("Failed to write log file!: " + ErrorDescription()); + Message("Failed to write log file!: " + ErrorDescription()); EndTry; - + EndProcedure #EndRegion diff --git a/src/en/OInt/tools/Modules/OPI_TypeConversion.os b/src/en/OInt/tools/Modules/OPI_TypeConversion.os index a752ec1a12..5850a7f29e 100644 --- a/src/en/OInt/tools/Modules/OPI_TypeConversion.os +++ b/src/en/OInt/tools/Modules/OPI_TypeConversion.os @@ -39,268 +39,268 @@ #Region Internal Procedure GetBinaryData(Value) Export - + If Value = Undefined Then Return; EndIf; - - Try - + + Try + If TypeOf(Value) = Type("BinaryData") Then Return; Else - + File = New File(Value); - + If File.Exist() Then Value = New BinaryData(Value); - + ElsIf StrFind(Value, "//") Then - + Value = OPI_Tools.Get(Value); - + Else - + Value = Base64Value(Value); - + EndIf; - + EndIf; - + Except Raise "Error getting binary data from parameter: " + ErrorDescription(); EndTry; - + EndProcedure Procedure GetBinaryOrStream(Value) Export - + If Value = Undefined Then Return; EndIf; - + If TypeOf(Value) <> Type("String") Then GetBinaryData(Value); Return; EndIf; - + File = New File(Value); - + If File.Exist() Then - Value = New FileStream(Value, FileOpenMode.Open); + Value = New FileStream(Value, FileOpenMode.Open); Else GetBinaryData(Value); EndIf; - + EndProcedure Procedure GetCollection(Value) Export - + If Value = Undefined Then Return; EndIf; - - Try - + + Try + InitialValue = Value; - + If ThisIsCollection(Value) Then Return; Else - + If TypeOf(Value) = Type("BinaryData") Then - Value = GetStringFromBinaryData(Value); + Value = GetStringFromBinaryData(Value); Else - Value = OPI_Tools.NumberToString(Value); + Value = OPI_Tools.NumberToString(Value); EndIf; - - File = New File(Value); + + File = New File(Value); JSONReader = New JSONReader; - + If File.Exist() Then - + JSONReader.OpenFile(Value); - + ElsIf StrStartsWith(Lower(Value), "http") Then - + TFN = GetTempFileName(); CopyFile(Value, TFN); JSONReader.OpenFile(TFN); JSONReader.Read(); - + DeleteFiles(TFN); - + Else - + JSONReader.SetString(TrimAll(Value)); - + EndIf; - + Value = ReadJSON(JSONReader, True, Undefined, JSONDateFormat.ISO); JSONReader.Close(); - + If (Not ThisIsCollection(Value)) Or Not ValueIsFilled(Value) Then - + Value = InitialValue; GetArray(Value); - + EndIf; - + EndIf; - + Except - + Value = InitialValue; - GetArray(Value); - + GetArray(Value); + EndTry; - + EndProcedure Procedure GetArray(Value) Export - + If TypeOf(Value) = Type("Array") Then Return; EndIf; - - If TypeOf(Value) = Type("String") + + If TypeOf(Value) = Type("String") And StrStartsWith(Value, "[") And StrEndsWith(Value, "]") Then - + CommaInQuotes = "','"; - - Value = StrReplace(Value, "['" , ""); - Value = StrReplace(Value, "']" , ""); + + Value = StrReplace(Value, "['" , ""); + Value = StrReplace(Value, "']" , ""); Value = StrReplace(Value, "', '" , CommaInQuotes); Value = StrReplace(Value, "' , '", CommaInQuotes); Value = StrReplace(Value, "' ,'" , CommaInQuotes); - + Value = StrSplit(Value, CommaInQuotes, False); - - For N = 0 To Value.UBound() Do + + For N = 0 To Value.UBound() Do Value[N] = TrimAll(Value[N]); EndDo; - + Else - + If TypeOf(Value) = Type("Number") Then - Value = OPI_Tools.NumberToString(Value); + Value = OPI_Tools.NumberToString(Value); EndIf; - + OPI_Tools.ValueToArray(Value); - + EndIf; - + EndProcedure Procedure GetBoolean(Value) Export - + If Value = Undefined Then Return; EndIf; - - Try - + + Try + If TypeOf(Value) = Type("Boolean") Then Return; Else - Value = Boolean(Value); + Value = Boolean(Value); EndIf; - + Except Raise "Error getting boolean data from parameter"; EndTry; - + EndProcedure Procedure GetLine(Value, Val FromSource = False) Export - + If Value = Undefined Then Return; EndIf; - - Try - + + Try + If ThisIsSymbolic(Value) Then - + If Not FromSource Then Value = OPI_Tools.NumberToString(Value); - Return; + Return; EndIf; - - Value = OPI_Tools.NumberToString(Value); - File = New File(Value); - + + Value = OPI_Tools.NumberToString(Value); + File = New File(Value); + If File.Exist() Then - + TextReader = New TextReader(Value); - Value = TextReader.Read(); + Value = TextReader.Read(); TextReader.Close(); - + ElsIf StrStartsWith(Lower(Value), "http") Then - + TFN = GetTempFileName(); CopyFile(Value, TFN); - + TextReader = New TextReader(TFN); - Value = TextReader.Read(); + Value = TextReader.Read(); TextReader.Close(); - + DeleteFiles(TFN); - + Else - + Return; - + EndIf; - + ElsIf TypeOf(Value) = Type("BinaryData") Then - + Value = GetStringFromBinaryData(Value); - + ElsIf ThisIsCollection(Value) Then - - Value = OPI_Tools.JSONString(Value); - + + Value = OPI_Tools.JSONString(Value); + Else Return; EndIf; - + Except Value = String(Value); Return; EndTry; - + EndProcedure Procedure GetDate(Value) Export - + If Value = Undefined Then Return; EndIf; - + Date = "Date"; - - Try - + + Try + If TypeOf(Value) = Type(Date) Then Return; - Else - Value = XMLValue(Type(Date), Value); + Else + Value = XMLValue(Type(Date), Value); EndIf; - + Except - OOD = New TypeDescription(Date); + OOD = New TypeDescription(Date); Value = OOD.AdjustValue(Value); EndTry; - + EndProcedure Procedure GetNumber(Value) Export - + TypeDescription = New TypeDescription("Number"); - Value = TypeDescription.AdjustValue(Value); - + Value = TypeDescription.AdjustValue(Value); + EndProcedure #EndRegion @@ -308,19 +308,19 @@ EndProcedure #Region Private Function ThisIsCollection(Val Value) - - Return TypeOf(Value) = Type("Array") + + Return TypeOf(Value) = Type("Array") Or TypeOf(Value) = Type("Structure") Or TypeOf(Value) = Type("Map"); - -EndFunction + +EndFunction Function ThisIsSymbolic(Val Value) - - Return TypeOf(Value) = Type("String") - Or TypeOf(Value) = Type("Number") + + Return TypeOf(Value) = Type("String") + Or TypeOf(Value) = Type("Number") Or TypeOf(Value) = Type("Date"); - -EndFunction + +EndFunction #EndRegion diff --git a/src/en/OInt/tools/Modules/internal/Modules/OPI_Cryptography.os b/src/en/OInt/tools/Modules/internal/Modules/OPI_Cryptography.os index 9d47d3f3ec..239b800c71 100644 --- a/src/en/OInt/tools/Modules/internal/Modules/OPI_Cryptography.os +++ b/src/en/OInt/tools/Modules/internal/Modules/OPI_Cryptography.os @@ -39,75 +39,75 @@ /////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2019, LLC 1C-Soft -// All rights reserved. This program and accompanying materials are provided +// All rights reserved. This program and accompanying materials are provided // under the terms of the Attribution 4.0 International (CC BY 4.0 license) // License text available at: // https://creativecommons.org/licenses/by/4.0/legalcode /////////////////////////////////////////////////////////////////////////////////////////////////////// Function HMACSHA256(Val Key, Val Data) Export - + Return HMAC(Key, Data, HashFunction.SHA256, 64); - + EndFunction Function Hash(BinaryData, Type) Export - + Hashing = New DataHashing(Type); Hashing.Append(BinaryData); - + Return Hashing.HashSum; - + EndFunction Function HMAC(Val Key, Val Data, Type, BlockSize) Export - + Twice = 2; - + If Key.Size() > BlockSize Then Key = Hash(Key, Type); EndIf; - + If Key.Size() <= BlockSize Then - Key = GetHexStringFromBinaryData(Key); - Key = Left(Key + RepeatString("00", BlockSize), BlockSize * Twice); + Key = GetHexStringFromBinaryData(Key); + Key = Left(Key + RepeatString("00", BlockSize), BlockSize * Twice); EndIf; - + Key = GetBinaryDataBufferFromBinaryData(GetBinaryDataFromHexString(Key)); - + Ipad = GetBinaryDataBufferFromHexString(RepeatString("36", BlockSize)); Opad = GetBinaryDataBufferFromHexString(RepeatString("5c", BlockSize)); - + Ipad.WriteBitwiseXor(0, Key); Ikeypad = GetBinaryDataFromBinaryDataBuffer(ipad); - + Opad.WriteBitwiseXor(0, Key); Okeypad = GetBinaryDataFromBinaryDataBuffer(opad); - + Return Hash(UniteBinaryData(okeypad, Hash(UniteBinaryData(ikeypad, Data), Type)), Type); - + EndFunction Function UniteBinaryData(BinaryData1, BinaryData2) Export - + BinaryDataArray = New Array; BinaryDataArray.Add(BinaryData1); BinaryDataArray.Add(BinaryData2); - + Return ConcatenateBinaryData(BinaryDataArray); - + EndFunction Function RepeatString(String, Count) Export - + Parts = New Array(Count); - + For K = 1 To Count Do Parts.Add(String); EndDo; Return StrConcat(Parts, ""); - + EndFunction #EndRegion diff --git a/src/en/OInt/tools/Modules/internal/Modules/OPI_Tools.os b/src/en/OInt/tools/Modules/internal/Modules/OPI_Tools.os index c71e9a866c..28c7931a73 100644 --- a/src/en/OInt/tools/Modules/internal/Modules/OPI_Tools.os +++ b/src/en/OInt/tools/Modules/internal/Modules/OPI_Tools.os @@ -56,69 +56,69 @@ EndFunction #Region RequestsWithBody Function Post(Val URL - , Val Parameters = "" + , Val Parameters = "" , Val AdditionalHeaders = "" , Val JSON = True - , Val FullResponse = False - , Val ResponseFile = Undefined) Export - + , Val FullResponse = False + , Val ResponseFile = Undefined) Export + Return ExecuteRequestWithBody(URL, "POST", Parameters, AdditionalHeaders, JSON, FullResponse, ResponseFile); - + EndFunction Function Patch(Val URL - , Val Parameters = "" + , Val Parameters = "" , Val AdditionalHeaders = "" , Val JSON = True - , Val FullResponse = False - , Val ResponseFile = Undefined) Export - + , Val FullResponse = False + , Val ResponseFile = Undefined) Export + Return ExecuteRequestWithBody(URL, "PATCH", Parameters, AdditionalHeaders, JSON, FullResponse, ResponseFile); - + EndFunction Function Put(Val URL - , Val Parameters = "" + , Val Parameters = "" , Val AdditionalHeaders = "" , Val JSON = True - , Val FullResponse = False - , Val ResponseFile = Undefined) Export - + , Val FullResponse = False + , Val ResponseFile = Undefined) Export + Return ExecuteRequestWithBody(URL, "PUT", Parameters, AdditionalHeaders, JSON, FullResponse, ResponseFile); - + EndFunction Function PostBinary(Val URL , Val Body , Val AdditionalHeaders , Val FullResponse = False - , Val DataType = "application/octet-stream") Export - + , Val DataType = "application/octet-stream") Export + Return ExecuteRequestWithBinaryData(URL, "POST", Body, AdditionalHeaders, FullResponse, DataType); - + EndFunction -#EndRegion +#EndRegion #Region MultipartRequests Function PostMultipart(Val URL - , Val Parameters = "" - , Val Files = "" - , Val ContentType = "image/jpeg" + , Val Parameters = "" + , Val Files = "" + , Val ContentType = "image/jpeg" , Val AdditionalHeaders = "" - , Val ResponseFile = Undefined) Export + , Val ResponseFile = Undefined) Export Return ExecuteMultipartRequest(URL, "POST", Parameters, Files, ContentType, AdditionalHeaders, ResponseFile); EndFunction Function PutMultipart(Val URL - , Val Parameters = "" - , Val Files = "" - , Val ContentType = "image/jpeg" + , Val Parameters = "" + , Val Files = "" + , Val ContentType = "image/jpeg" , Val AdditionalHeaders = "" - , Val ResponseFile = Undefined) Export + , Val ResponseFile = Undefined) Export Return ExecuteMultipartRequest(URL, "PUT", Parameters, Files, ContentType, AdditionalHeaders, ResponseFile); @@ -126,99 +126,99 @@ EndFunction Function PostMultipartRelated(Val URL , Val JSON = "" - , Val Files = "" + , Val Files = "" , Val AdditionalHeaders = "" - , Val ResponseFile = Undefined) Export - + , Val ResponseFile = Undefined) Export + Return ExecuteMultipartRelatedRequest(URL, "POST", JSON, Files, AdditionalHeaders, ResponseFile); - + EndFunction Function PatchMultipartRelated(Val URL , Val JSON = "" - , Val Files = "" + , Val Files = "" , Val AdditionalHeaders = "" - , Val ResponseFile = Undefined) Export - + , Val ResponseFile = Undefined) Export + Return ExecuteMultipartRelatedRequest(URL, "PATCH", JSON, Files, AdditionalHeaders, ResponseFile); - + EndFunction #EndRegion #Region Miscellaneous -Procedure ProcessResponse(Response, Val FullResponse = False) Export - +Procedure ProcessResponse(Response, Val FullResponse = False) Export + If FullResponse Or TypeOf(Response) <> Type("HTTPResponse") Then Return; EndIf; - + BodyFile = Response.GetBodyFileName(); - + If Not BodyFile = Undefined Then - Response = BodyFile; + Response = BodyFile; Return; EndIf; - - GZip = "gzip"; - NeedsUnpacking = - Response.Headers.Get("Content-Encoding") = GZip + + GZip = "gzip"; + NeedsUnpacking = + Response.Headers.Get("Content-Encoding") = GZip Or Response.Headers.Get("content-encoding") = GZip; - + If NeedsUnpacking Then Response = UnpackResponse(Response); EndIf; - + Response = ?(TypeOf(Response) = Type("HTTPResponse"), Response.ПолучитьТелоКакДвоичныеДанные(), Response); - + If TypeOf(Response) = Type("BinaryData") Then - + Try Response = JsonToStructure(Response); Except Return; EndTry; - + EndIf; - + EndProcedure Function CreateRequest(Val Address, Val AdditionalHeaders = "", Val DataType = "") Export - + Headers = New Map; Headers.Insert("Accept-Encoding", "gzip"); - Headers.Insert("Accept" , "*/*"); - Headers.Insert("Connection" , "keep-alive"); + Headers.Insert("Accept" , "*/*"); + Headers.Insert("Connection" , "keep-alive"); Headers.Insert("Accept-Charset" , "utf-8"); - + If ValueIsFilled(DataType) Then Headers.Insert("Content-Type", DataType); EndIf; - + If TypeOf(AdditionalHeaders) = Type("Map") Then - + For Each Title In AdditionalHeaders Do Headers.Insert(Title.Key, Title.Value); EndDo; - + EndIf; - + NewRequest = New HTTPRequest(Address, Headers); - + Return NewRequest; - + EndFunction Function CreateConnection(Val Server, Val User = "", Val Password = "") Export - - Try + + Try SSL = New OpenSSLSecureConnection; Return New HTTPConnection(Server, 443, User, Password, , 3000, SSL); Except Return New HTTPConnection(Server, 443, User, Password, , 3000); EndTry; - + EndFunction #EndRegion @@ -236,12 +236,12 @@ Function RequestParametersToString(Val Parameters) Export ParameterString = "?"; For Each Parameter In Parameters Do - + ParameterValue = ConvertParameterToString(Parameter.Value); - - ParameterString = ParameterString - + Parameter.Key - + "=" + + ParameterString = ParameterString + + Parameter.Key + + " =" + ParameterValue + "&"; EndDo; @@ -255,20 +255,20 @@ EndFunction Function SplitURL(Val URL) Export URL = StrReplace(URL, "https://", ""); - URL = StrReplace(URL, "http://", ""); - URL = StrReplace(URL, ":443", ""); + URL = StrReplace(URL, "http://" , ""); + URL = StrReplace(URL, ":443" , ""); Address = Right(URL, StrLen(URL) - StrFind(URL, "/", SearchDirection.FromBegin) + 1); - Server = Left(URL, StrFind(URL, "/", SearchDirection.FromBegin) - 1); - - Try - SSL = New OpenSSLSecureConnection; + Server = Left(URL, StrFind(URL, "/", SearchDirection.FromBegin) - 1); + + Try + SSL = New OpenSSLSecureConnection; Except Server = "https://" + Server; EndTry; - + ReturnStructure = New Structure; - ReturnStructure.Insert("Server", Server); + ReturnStructure.Insert("Server" , Server); ReturnStructure.Insert("Address" , Address); Return ReturnStructure; @@ -280,7 +280,7 @@ Function JsonToStructure(Val Text) Export If Not ValueIsFilled(Text) Then Return ""; EndIf; - + Text = ?(TypeOf(Text) = Type("BinaryData"), GetStringFromBinaryData(Text), Text); JSONReader = New JSONReader; @@ -305,14 +305,14 @@ Function JSONString(Val Data, Val Escaping = "None") Export , False); Try - + JSONWriter = New JSONWriter; JSONWriter.SetString(JSONParameters); - + WriteJSON(JSONWriter, Data); Return JSONWriter.Close(); - - Except + + Except Return "NOT JSON: " + String(Data); EndTry; @@ -323,21 +323,21 @@ Function NumberToString(Val Number) Export EndFunction Function ReadJSONFile(Val Path) Export - + JSONReader = New JSONReader; - JSONReader.OpenFile(Path); - Values = ReadJSON(JSONReader); - + JSONReader.OpenFile(Path); + Values = ReadJSON(JSONReader); + JSONReader.Close(); - + Return Values; - + EndFunction Function RequestParametersToMap(Val ParameterString) Export - ReturnMapping = New Map; - NumberOfParts = 2; + ReturnMapping = New Map; + NumberOfParts = 2; ParameterArray = StrSplit(ParameterString, "&", False); For Each Parameter In ParameterArray Do @@ -355,104 +355,104 @@ Function RequestParametersToMap(Val ParameterString) Export EndFunction Function GetCurrentDate() Export - Return ToLocalTime(CurrentUniversalDate()); + Return ToLocalTime(CurrentUniversalDate()); EndFunction Function UNIXTime(Val Date) Export - - OTD = New TypeDescription("Date"); + + OTD = New TypeDescription("Date"); Date = OTD.AdjustValue(Date); - + UNIX = Format(Date - Date(1970, 1, 1, 1, 0, 0), "HC=10; HDC=0; HG=0"); - UNIX = StrReplace(UNIX, ",", ""); + UNIX = StrReplace(UNIX, "," , ""); UNIX = StrReplace(UNIX, Chars.NBSp, ""); - UNIX = StrReplace(UNIX, " ", ""); + UNIX = StrReplace(UNIX, " " , ""); UNIX = Left(UNIX, 10); - + Return UNIX; - + EndFunction Function ProgressInformation(Val Current, Val Total, Val Unit, Val Divider = 1) Export - - Whole = 100; + + Whole = 100; Current = Round(Current / Divider, 2); - Total = Round(Total / Divider, 2); + Total = Round(Total / Divider, 2); Percent = Int(Current / Total * Whole); - - StrCurrent = NumberToString(Current); - StrTotal = NumberToString(Total); + + StrCurrent = NumberToString(Current); + StrTotal = NumberToString(Total); StrPercentage = NumberToString(Percent); - + Information = StrCurrent + "/" + StrTotal + " " + Unit + " ( " + StrPercentage + "% )"; - + Return Information; - + EndFunction Function ConvertDataWithSizeRetrieval(Data, Val MinimumStreamSize = 0) Export - + Size = 0; - + If TypeOf(Data) = Type("String") Then - + FileOnDisk = New File(Data); - - If FileOnDisk.Exist() Then - Size = FileOnDisk.Size(); + + If FileOnDisk.Exist() Then + Size = FileOnDisk.Size(); Else OPI_TypeConversion.GetBinaryData(Data); Size = Data.Size(); EndIf; - + Else OPI_TypeConversion.GetBinaryData(Data); Size = Data.Size(); EndIf; - + If ValueIsFilled(MinimumStreamSize) Then If Size < MinimumStreamSize Then OPI_TypeConversion.GetBinaryData(Data); Else - OPI_TypeConversion.GetBinaryOrStream(Data); - EndIf; + OPI_TypeConversion.GetBinaryOrStream(Data); + EndIf; Else OPI_TypeConversion.GetBinaryOrStream(Data); EndIf; - + Return Size; - + EndFunction Procedure ValueToArray(Value) Export - + Value_ = New Array; Value_.Add(Value); - Value = Value_; + Value = Value_; EndProcedure Procedure ReplaceSpecialCharacters(Text, Markup = "Markdown") Export - + CharacterMapping = New Map; - + If Markup = "HTML" Then - + CharacterMapping.Insert("&", "&"); - + ElsIf Markup = "MarkdownV2" Then - + CharacterMapping.Insert("-", "\-"); CharacterMapping.Insert("+", "\+"); - CharacterMapping.Insert("#", "\#"); + CharacterMapping.Insert("#", "\#"); CharacterMapping.Insert("=", "\="); - CharacterMapping.Insert("{", "\{"); - CharacterMapping.Insert("}", "\}"); + CharacterMapping.Insert("{", "\{"); + CharacterMapping.Insert("}", "\}"); CharacterMapping.Insert(".", "\."); - + Else Return; - EndIf; + EndIf; For Each ArraySymbol In CharacterMapping Do Text = StrReplace(Text, ArraySymbol.Key, ArraySymbol.Value); @@ -461,80 +461,80 @@ Procedure ReplaceSpecialCharacters(Text, Markup = "Markdown") Export EndProcedure Procedure RemoveEmptyCollectionFields(Collection) Export - - CollectionType = TypeOf(Collection); + + CollectionType = TypeOf(Collection); OutputCollection = New(CollectionType); - + If CollectionType = Type("Map") Or CollectionType = Type("Structure") Then - + RemoveEmptyKeyValues(Collection, OutputCollection); - + ElsIf CollectionType = Type("Array") Then - + RemoveEmptyArrayItems(Collection, OutputCollection); - + Else - + OutputCollection = Collection; - + EndIf; - + Collection = OutputCollection; - + EndProcedure Procedure Pause(Val Seconds) Export - + Connection = New HTTPConnection("1C.ru", 11111, , , , Seconds); Try Connection.Get(New HTTPRequest("")); Except - Return; + Return; EndTry; - + EndProcedure Procedure AddField(Val Name, Val Value, Val Type, Collection) Export - + Filled = ValueIsFilled(Value); - + If Not Filled Then Return; EndIf; - - If Type = "Date" Then + + If Type = "Date" Then OPI_TypeConversion.GetDate(Value); Value = UNIXTime(Value); - + ElsIf Type = "DateISO" Then OPI_TypeConversion.GetDate(Value); - Value = XMLString(Value); - + Value = XMLString(Value); + ElsIf Type = "Collection" Then - OPI_TypeConversion.GetCollection(Value); - + OPI_TypeConversion.GetCollection(Value); + ElsIf Type = "Boolean" Then - OPI_TypeConversion.GetBoolean(Value); - + OPI_TypeConversion.GetBoolean(Value); + ElsIf Type = "FileString" Then OPI_TypeConversion.GetLine(Value, True); - + ElsIf Type = "Array" Then OPI_TypeConversion.GetArray(Value); - + ElsIf Type = "BinaryData" Then OPI_TypeConversion.GetBinaryData(Value); - + ElsIf Type = "Number" Then OPI_TypeConversion.GetNumber(Value); - + Else OPI_TypeConversion.GetLine(Value); - + EndIf; - + Collection.Insert(Name, Value); - + EndProcedure #EndRegion @@ -545,24 +545,24 @@ EndProcedure Function ExecuteRequestWithBody(Val URL , Val View - , Val Parameters = "" + , Val Parameters = "" , Val AdditionalHeaders = "" , Val JSON = True - , Val FullResponse = False - , Val ResponseFile = Undefined) - + , Val FullResponse = False + , Val ResponseFile = Undefined) + If Not ValueIsFilled(Parameters) Then Parameters = New Structure; EndIf; - - DataType = ?(JSON, "application/json; charset=utf-8", "application/x-www-form-urlencoded; charset=utf-8"); + + DataType = ?(JSON, "application/json; charset =utf-8", "application/x-www-form-urlencoded; charset =utf-8"); URLStructure = SplitURL(URL); - Server = URLStructure["Server"]; - Address = URLStructure["Address"]; - - Request = CreateRequest(Address, AdditionalHeaders, DataType); + Server = URLStructure["Server"]; + Address = URLStructure["Address"]; + + Request = CreateRequest(Address, AdditionalHeaders, DataType); Connection = CreateConnection(Server); - + SetRequestBody(Request, Parameters, JSON); If ValueIsFilled(ResponseFile) Then @@ -570,17 +570,17 @@ Function ExecuteRequestWithBody(Val URL Else Response = Connection.CallHTTPMethod(View, Request); EndIf; - - If ThisIsRedirection(Response) Then + + If ThisIsRedirection(Response) Then Response = ExecuteRequestWithBody(Response.Headers["Location"] , View , Parameters , AdditionalHeaders , JSON , FullResponse - , ResponseFile); - Else - ProcessResponse(Response, FullResponse); + , ResponseFile); + Else + ProcessResponse(Response, FullResponse); EndIf; Return Response; @@ -593,29 +593,29 @@ Function ExecuteRequestWithBinaryData(Val URL , Val AdditionalHeaders , Val FullResponse , Val DataType) - + URLStructure = SplitURL(URL); - Server = URLStructure["Server"]; - Address = URLStructure["Address"]; - - Request = CreateRequest(Address, AdditionalHeaders, DataType); + Server = URLStructure["Server"]; + Address = URLStructure["Address"]; + + Request = CreateRequest(Address, AdditionalHeaders, DataType); Connection = CreateConnection(Server); - + If Not Data.Size() = 0 Then Request.SetBodyFromBinary(Data); EndIf; - + Response = Connection.CallHTTPMethod(View, Request); - If ThisIsRedirection(Response) Then + If ThisIsRedirection(Response) Then Response = ExecuteRequestWithBinaryData(Response.Headers["Location"] , View , Data , AdditionalHeaders , FullResponse - , DataType); - Else - ProcessResponse(Response, FullResponse); + , DataType); + Else + ProcessResponse(Response, FullResponse); EndIf; Return Response; @@ -624,45 +624,45 @@ EndFunction Function ExecuteRequestWithoutBody(Val URL , Val View - , Val Parameters = "" + , Val Parameters = "" , Val AdditionalHeaders = "" - , Val ResponseFile = Undefined) - + , Val ResponseFile = Undefined) + If Not ValueIsFilled(Parameters) Then Parameters = New Structure; EndIf; URLStructure = SplitURL(URL); - Server = URLStructure["Server"]; - Address = URLStructure["Address"] + RequestParametersToString(Parameters); - - Request = CreateRequest(Address, AdditionalHeaders); - Connection = CreateConnection(Server); - + Server = URLStructure["Server"]; + Address = URLStructure["Address"] + RequestParametersToString(Parameters); + + Request = CreateRequest(Address, AdditionalHeaders); + Connection = CreateConnection(Server); + If ValueIsFilled(ResponseFile) Then Response = Connection.CallHTTPMethod(View, Request, ResponseFile); Else Response = Connection.CallHTTPMethod(View, Request); EndIf; - - If ThisIsRedirection(Response) Then - Response = ExecuteRequestWithoutBody(Response.Headers["Location"], View, Parameters, AdditionalHeaders, ResponseFile); - Else - ProcessResponse(Response); + + If ThisIsRedirection(Response) Then + Response = ExecuteRequestWithoutBody(Response.Headers["Location"], View, Parameters, AdditionalHeaders, ResponseFile); + Else + ProcessResponse(Response); EndIf; Return Response; - + EndFunction Function ExecuteMultipartRequest(Val URL , Val View - , Val Parameters = "" - , Val Files = "" - , Val ContentType = "image/jpeg" + , Val Parameters = "" + , Val Files = "" + , Val ContentType = "image/jpeg" , Val AdditionalHeaders = "" - , Val ResponseFile = Undefined) - + , Val ResponseFile = Undefined) + If Not ValueIsFilled(Parameters) Then Parameters = New Structure; EndIf; @@ -671,20 +671,20 @@ Function ExecuteMultipartRequest(Val URL Files = New Map; EndIf; - Redirection = 300; - Error = 400; - Boundary = StrReplace(String(New UUID), "-", ""); + Redirection = 300; + Error = 400; + Boundary = StrReplace(String(New UUID), "-", ""); LineSeparator = Chars.CR + Chars.LF; - DataType = "multipart/form-data; boundary=" + Boundary; - URLStructure = SplitURL(URL); - Server = URLStructure["Server"]; - Address = URLStructure["Address"]; - - Request = CreateRequest(Address, AdditionalHeaders, DataType); + DataType = "multipart/form-data; boundary =" + Boundary; + URLStructure = SplitURL(URL); + Server = URLStructure["Server"]; + Address = URLStructure["Address"]; + + Request = CreateRequest(Address, AdditionalHeaders, DataType); Connection = CreateConnection(Server); - + RequestBody = GetTempFileName(); - TextRecord = New DataWriter(RequestBody + TextRecord = New DataWriter(RequestBody , TextEncoding.UTF8 , ByteOrder.LittleEndian , "" @@ -694,98 +694,98 @@ Function ExecuteMultipartRequest(Val URL WriteMultipartParameters(TextRecord, Boundary, Parameters); WriteMultipartFiles(TextRecord, Boundary, ContentType, Files); - + TextRecord.WriteLine("--" + boundary + "--" + LineSeparator); TextRecord.Close(); Request.SetBodyFileName(RequestBody); - + If ValueIsFilled(ResponseFile) Then Response = Connection.CallHTTPMethod(View, Request, ResponseFile); Else Response = Connection.CallHTTPMethod(View, Request); EndIf; - + ThisIsRedirection = Response.StatusCode >= Redirection And Response.StatusCode < Error; - - If ThisIsRedirection Then + + If ThisIsRedirection Then Response = ExecuteMultipartRequest(Response.Headers["Location"] , View , Parameters , Files , ContentType , AdditionalHeaders - , ResponseFile); - Else - ProcessResponse(Response); + , ResponseFile); + Else + ProcessResponse(Response); EndIf; - - Request = Undefined; + + Request = Undefined; TextRecord = Undefined; - + DeleteFiles(RequestBody); Return Response; - + EndFunction Function ExecuteMultipartRelatedRequest(Val URL , Val View , Val JSON = "" - , Val Files = "" + , Val Files = "" , Val AdditionalHeaders = "" - , Val ResponseFile = Undefined) - - Redirection = 300; - Error = 400; - Boundary = StrReplace(String(New UUID), "-", ""); + , Val ResponseFile = Undefined) + + Redirection = 300; + Error = 400; + Boundary = StrReplace(String(New UUID), "-", ""); LineSeparator = Chars.CR + Chars.LF; - DataType = "multipart/related; boundary=" + Boundary; - URLStructure = SplitURL(URL); - Server = URLStructure["Server"]; - Address = URLStructure["Address"]; - - Request = CreateRequest(Address, AdditionalHeaders, DataType); + DataType = "multipart/related; boundary =" + Boundary; + URLStructure = SplitURL(URL); + Server = URLStructure["Server"]; + Address = URLStructure["Address"]; + + Request = CreateRequest(Address, AdditionalHeaders, DataType); Connection = CreateConnection(Server); - + RequestBody = GetTempFileName(); - TextRecord = New DataWriter(RequestBody + TextRecord = New DataWriter(RequestBody , TextEncoding.UTF8 , ByteOrder.LittleEndian , "" , False , "" , False); - + WriteJSONMultipart(TextRecord, Boundary, JSON); - WriteRelatedFiles(TextRecord, Boundary, Files); - + WriteRelatedFiles(TextRecord, Boundary, Files); + TextRecord.WriteLine("--" + boundary + "--" + LineSeparator); TextRecord.Close(); - + AddContentLength(Request); - + Request.SetBodyFileName(RequestBody); - + If ValueIsFilled(ResponseFile) Then Response = Connection.CallHTTPMethod(View, Request, ResponseFile); Else Response = Connection.CallHTTPMethod(View, Request); EndIf; - + ThisIsRedirection = Response.StatusCode >= Redirection And Response.StatusCode < Error; - - If ThisIsRedirection Then + + If ThisIsRedirection Then Response = ExecuteMultipartRelatedRequest(Response.Headers["Location"] , View , JSON , Files , AdditionalHeaders - , ResponseFile); - Else - ProcessResponse(Response); + , ResponseFile); + Else + ProcessResponse(Response); EndIf; - - Request = Undefined; + + Request = Undefined; TextRecord = Undefined; DeleteFiles(RequestBody); @@ -794,167 +794,167 @@ Function ExecuteMultipartRelatedRequest(Val URL EndFunction Function ThisIsRedirection(Val Response) - - Redirection = 300; - Error = 400; - ThisIsRedirection = Response.StatusCode >= Redirection + Redirection = 300; + Error = 400; + + ThisIsRedirection = Response.StatusCode >= Redirection And Response.StatusCode < Error And ValueIsFilled(Response.Headers["Location"]); - + Return ThisIsRedirection; - + EndFunction Function ConvertParameterToString(Val Value) If TypeOf(Value) = Type("Array") Then - Value = StrConcat(Value, ","); - Value = EncodeString(Value, StringEncodingMethod.URLInURLEncoding); - Value = "[" + Value + "]"; + Value = StrConcat(Value, ","); + Value = EncodeString(Value, StringEncodingMethod.URLInURLEncoding); + Value = "[" + Value + "]"; Else - Value = NumberToString(Value); - Value = EncodeString(Value, StringEncodingMethod.URLInURLEncoding); + Value = NumberToString(Value); + Value = EncodeString(Value, StringEncodingMethod.URLInURLEncoding); EndIf; - + Return Value; - + EndFunction Function SplitFileKey(Val FileData, Val ContentType) DotReplacement = "___"; - FileName = StrReplace(FileData, DotReplacement, "."); - NameParts = StrSplit(FileName, "|", False); - NeedParts = 2; - + FileName = StrReplace(FileData, DotReplacement, "."); + NameParts = StrSplit(FileName, "|", False); + NeedParts = 2; + If NameParts.Count() = NeedParts Then - FieldName = NameParts[0]; - FileName = NameParts[1]; + FieldName = NameParts[0]; + FileName = NameParts[1]; Else - + If ContentType = "image/jpeg" Then - FieldName = "photo"; + FieldName = "photo"; Else - FieldName = Left(FileName, StrFind(FileName, ".") - 1); - FieldName = ?(ValueIsFilled(FieldName), FieldName, StrReplace(FileData, + FieldName = Left(FileName, StrFind(FileName, ".") - 1); + FieldName = ?(ValueIsFilled(FieldName), FieldName, StrReplace(FileData, DotReplacement, ".")); EndIf; - + EndIf; - + ReturnStructure = New Structure("FieldName,FileName", FieldName, FileName); - + Return ReturnStructure; - + EndFunction Procedure SetRequestBody(Request, Val Parameters, Val JSON) - - Collection = TypeOf(Parameters) = Type("Structure") + + Collection = TypeOf(Parameters) = Type("Structure") Or TypeOf(Parameters) = Type("Map") Or TypeOf(Parameters) = Type("Array"); - + If JSON Then - Data = JSONString(Parameters); + Data = JSONString(Parameters); ElsIf Not Collection Then - Data = Parameters; + Data = Parameters; Else ParameterString = RequestParametersToString(Parameters); - Data = Right(ParameterString, StrLen(ParameterString) - 1); + Data = Right(ParameterString, StrLen(ParameterString) - 1); EndIf; - + If TypeOf(Data) = Type("String") Then Request.SetBodyFromString(Data); Else //@skip-check wrong-type-expression Request.SetBodyFromBinary(Data); EndIf; - + EndProcedure Procedure WriteMultipartParameters(TextRecord, Val Boundary, Val Parameters) - + LineSeparator = Chars.CR + Chars.LF; - + For Each Parameter In Parameters Do - - If Parameter.Value = Undefined + + If Parameter.Value = Undefined Or Parameter.Value = NULL Then Continue; EndIf; - + TextRecord.WriteLine("--" + boundary + LineSeparator); TextRecord.WriteLine("Content-Disposition: form-data; name=""" + Parameter.Key + """"); TextRecord.WriteLine(LineSeparator); TextRecord.WriteLine(LineSeparator); - - If TypeOf(Parameter.Value) = Type("String") + + If TypeOf(Parameter.Value) = Type("String") Or TypeOf(Parameter.Value) = Type("Number") Then - + ValueAsString = NumberToString(Parameter.Value); TextRecord.WriteLine(ValueAsString); - + ElsIf TypeOf(Parameter.Value) = Type("Boolean") Then - + TextRecord.WriteLine(?(Parameter.Value, "true", "false")); - + Else - + TextRecord.Write(Parameter.Value); - + EndIf; - + TextRecord.WriteLine(LineSeparator); - + EndDo; - + EndProcedure Procedure WriteMultipartFiles(TextRecord, Val Boundary, Val ContentType, Val Files) - - ContentType = TrimAll(ContentType); + + ContentType = TrimAll(ContentType); LineSeparator = Chars.CR + Chars.LF; - + For Each File In Files Do - + DataStructure = SplitFileKey(File.Key, ContentType); - + FieldName = DataStructure["FieldName"]; - FileName = DataStructure["FileName"]; - + FileName = DataStructure["FileName"]; + TextRecord.WriteLine("--" + boundary + LineSeparator); - TextRecord.WriteLine("Content-Disposition: form-data; name=""" - + FieldName - + """; filename=""" + TextRecord.WriteLine("Content-Disposition: form-data; name=""" + + FieldName + + """; filename=""" + FileName + """"); - TextRecord.WriteLine(LineSeparator); - + TextRecord.WriteLine(LineSeparator); + If ValueIsFilled(ContentType) Then TextRecord.WriteLine("Content-Type: " + ContentType); EndIf; - + TextRecord.WriteLine(LineSeparator); TextRecord.WriteLine(LineSeparator); WriteBinaryData(TextRecord, File.Value); TextRecord.WriteLine(LineSeparator); - + EndDo; EndProcedure Procedure WriteRelatedFiles(TextRecord, Val Boundary, Val Files) - + If Not ValueIsFilled(Files) Then Return; EndIf; - + LineSeparator = Chars.CR + Chars.LF; - + If TypeOf(Files) = Type("Map") Then For Each File In Files Do - + TextRecord.WriteLine("--" + boundary + LineSeparator); TextRecord.WriteLine("Content-Type: " + File.Value); TextRecord.WriteLine(LineSeparator); @@ -962,51 +962,51 @@ Procedure WriteRelatedFiles(TextRecord, Val Boundary, Val Files) WriteBinaryData(TextRecord, File.Key); TextRecord.WriteLine(LineSeparator); TextRecord.WriteLine(LineSeparator); - + EndDo; - + EndIf; EndProcedure Procedure WriteBinaryData(DataWriter, Val BinaryData) - - ChunkSize = 268435456; - BytesRead = 0; + + ChunkSize = 268435456; + BytesRead = 0; CurrentPosition = 0; - TotalSize = BinaryData.Size(); + TotalSize = BinaryData.Size(); WHile BytesRead < TotalSize Do - - DataReader = New DataReader(BinaryData); - BytesRead = DataReader.Skip(CurrentPosition); - Result = DataReader.Read(ChunkSize); + + DataReader = New DataReader(BinaryData); + BytesRead = DataReader.Skip(CurrentPosition); + Result = DataReader.Read(ChunkSize); CurrentData = Result.GetBinaryData(); CurrentSize = CurrentData.Size(); - + If Not ValueIsFilled(CurrentData) Then Break; EndIf; DataWriter.Write(CurrentData); - + FreeObject(CurrentData); RunGarbageCollection(); CurrentPosition = CurrentPosition + CurrentSize; - + EndDo; EndProcedure Procedure WriteJSONMultipart(TextRecord, Val Boundary, Val JSON) - + If Not ValueIsFilled(JSON) Then Return; EndIf; - + LineSeparator = Chars.CR + Chars.LF; - + TextRecord.WriteLine("--" + boundary + LineSeparator); TextRecord.WriteLine("Content-Type: application/json; charset=UTF-8"); TextRecord.WriteLine(LineSeparator); @@ -1018,46 +1018,46 @@ Procedure WriteJSONMultipart(TextRecord, Val Boundary, Val JSON) EndProcedure Procedure AddContentLength(Request) - + RequestBody = Request.ПолучитьТелоКакДвоичныеДанные(); - + If ValueIsFilled(RequestBody) Then - + Size = RequestBody.Size(); Request.Headers.Insert("Content-Length", NumberToString(Size)); - + EndIf; EndProcedure Procedure RemoveEmptyKeyValues(Val Collection, OutputCollection) - + For Each CollectionItem In Collection Do - + If Not CollectionItem.Value = Undefined And Not CollectionItem.Value = NULL Then OutputCollection.Insert(CollectionItem.Key, CollectionItem.Value); EndIf; - + EndDo; - + EndProcedure Procedure RemoveEmptyArrayItems(Val Collection, OutputCollection) - + For Each CollectionItem In Collection Do - + If Not CollectionItem = Undefined And Not CollectionItem = NULL Then OutputCollection.Add(CollectionItem); EndIf; - + EndDo; - + EndProcedure #Region GZip // Structure description at https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT -// Source: https://github.com/vbondarevsky/Connector +// Source: https://github.com/vbondarevsky/Connector // Connector: convenient HTTP client for 1C:Enterprise 8 // @@ -1094,24 +1094,24 @@ EndFunction Function ReadGZip(CompressedData) Export - GZipPrefixSize = 10; + GZipPrefixSize = 10; GZipPostfixSize = 8; - - SizeDD = ZipSizeDD(); + + SizeDD = ZipSizeDD(); SizeCDH = ZipSizeCDH(); SizeESD = ZipSizeEOCD(); SizeLFH = ZipSizeLFH(); - DataReader = New DataReader(CompressedData); + DataReader = New DataReader(CompressedData); DataReader.Skip(GZipPrefixSize); CompressedDataSize = DataReader.SourceStream().Size() - GZipPrefixSize - GZipPostfixSize; - ZipStream = New MemoryStream(SizeLFH - + CompressedDataSize - + SizeDD - + SizeCDH + ZipStream = New MemoryStream(SizeLFH + + CompressedDataSize + + SizeDD + + SizeCDH + SizeESD); - + DataWriter = New DataWriter(ZipStream); DataWriter.WriteBinaryDataBuffer(ZipLFH()); DataReader.CopyTo(DataWriter, CompressedDataSize); @@ -1123,7 +1123,7 @@ Function ReadGZip(CompressedData) Export UncompressedDataSize = DataReader.ReadInt32(); DataReader.Close(); - DataWriter.WriteBinaryDataBuffer(ZipDD(CRC32, CompressedDataSize, UncompressedDataSize)); + DataWriter.WriteBinaryDataBuffer(ZipDD(CRC32 , CompressedDataSize, UncompressedDataSize)); DataWriter.WriteBinaryDataBuffer(ZipCDH(CRC32, CompressedDataSize, UncompressedDataSize)); DataWriter.WriteBinaryDataBuffer(ZipEOCD(CompressedDataSize)); DataWriter.Close(); @@ -1134,9 +1134,9 @@ EndFunction Function ReadZip(CompressedData, ErrorText = Undefined) - Directory = GetTempFileName(); - ReadingZip = New ZipFileReader(CompressedData); - FileName = ReadingZip.Items[0].Name; + Directory = GetTempFileName(); + ReadingZip = New ZipFileReader(CompressedData); + FileName = ReadingZip.Items[0].Name; Try ReadingZip.Extract(ReadingZip.Items[0], Directory, ZIPRestoreFilePathsMode.DontRestore); Except @@ -1177,12 +1177,12 @@ Function ZipSizeEOCD() EndFunction Function ZipLFH() - + // Local file header Buffer = New BinaryDataBuffer(ZipSizeLFH()); Buffer.WriteInt32(0, 67324752); // signature 0x04034b50 Buffer.WriteInt16(4, 20); // version - Buffer.WriteInt16(6, 10); // bit flags + Buffer.WriteInt16(6, 10); // bit flags Buffer.WriteInt16(8, 8); // compression method Buffer.WriteInt16(10, 0); // time Buffer.WriteInt16(12, 0); // date @@ -1198,7 +1198,7 @@ Function ZipLFH() EndFunction Function ZipDD(CRC32, CompressedDataSize, UncompressedDataSize) - + // Data descriptor Buffer = New BinaryDataBuffer(ZipSizeDD()); Buffer.WriteInt32(0, 134695760); @@ -1211,7 +1211,7 @@ Function ZipDD(CRC32, CompressedDataSize, UncompressedDataSize) EndFunction Function ZipCDH(CRC32, CompressedDataSize, UncompressedDataSize) - + // Central directory header Buffer = New BinaryDataBuffer(ZipSizeCDH()); Buffer.WriteInt32(0, 33639248); // signature 0x02014b50 @@ -1238,7 +1238,7 @@ Function ZipCDH(CRC32, CompressedDataSize, UncompressedDataSize) EndFunction Function ZipEOCD(CompressedDataSize) - + // End of central directory SizeCDH = 50; Buffer = New BinaryDataBuffer(ZipSizeEOCD()); @@ -1247,7 +1247,7 @@ Function ZipEOCD(CompressedDataSize) Buffer.WriteInt16(6, 0); // number of the disk with the start of the central directory Buffer.WriteInt16(8, 1); // total number of entries in the central directory on this disk Buffer.WriteInt16(10, 1); // total number of entries in the central directory - Buffer.WriteInt32(12, SizeCDH); // size of the central directory + Buffer.WriteInt32(12, SizeCDH); // size of the central directory // offset of start of central directory with respect to the starting disk number Buffer.WriteInt32(16, ZipSizeLFH() + CompressedDataSize + ZipSizeDD()); Buffer.WriteInt16(20, 0); // the starting disk number diff --git a/src/en/OPI/src/CommonModules/OPI_Airtable/Module.bsl b/src/en/OPI/src/CommonModules/OPI_Airtable/Module.bsl index 872efb4b6b..07b1ef27cb 100644 --- a/src/en/OPI/src/CommonModules/OPI_Airtable/Module.bsl +++ b/src/en/OPI/src/CommonModules/OPI_Airtable/Module.bsl @@ -42,91 +42,91 @@ // Get list of bases // Gets the list of available bases -// +// // Parameters: // Token - String - Token - token // Indent - String - Next page identifier of the base list from the previous request - offset -// +// // Returns: -// Map Of KeyAndValue - serialized JSON response from Airtable +// Map Of KeyAndValue - serialized JSON response from Airtable Function GetListOfBases(Val Token, Val Indent = "") Export - + OPI_TypeConversion.GetLine(Indent); - - URL = "https://api.airtable.com/v0/meta/bases"; - Headers = GetAuthorizationHeader(Token); + + URL = "https://api.airtable.com/v0/meta/bases"; + Headers = GetAuthorizationHeader(Token); Parameters = New Structure; - + OPI_Tools.AddField("offset", Indent, "String", Parameters); - + Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; - + EndFunction // Get base tables // Gets the schema of base tables -// +// // Parameters: // Token - String - Token - token // Base - String - Base identifier - base -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Airtable Function GetDatabaseTables(Val Token, Val Base) Export - + OPI_TypeConversion.GetLine(Base); - - URL = "https://api.airtable.com/v0/meta/bases/" + Base + "/tables"; + + URL = "https://api.airtable.com/v0/meta/bases/" + Base + "/tables"; Headers = GetAuthorizationHeader(Token); - + Response = OPI_Tools.Get(URL, , Headers); - + Return Response; - + EndFunction // Create base // Creates a new database -// +// // Parameters: // Token - String - Token - token // Workspace - String - Workspace identifier - ws // Name - String - New base name - title // TableCollection - Map Of KeyAndValue - Table description: Key > name, Value > array of fields - tablesdata -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Airtable Function CreateDatabase(Val Token, Val Workspace, Val Name, Val TableCollection) Export - + OPI_TypeConversion.GetCollection(TableCollection); - - If Not TypeOf(TableCollection) = Type("Structure") + + If Not TypeOf(TableCollection) = Type("Structure") And Not TypeOf(TableCollection) = Type("Map") Then - + Raise "Error in table collection data"; - + EndIf; - - URL = "https://api.airtable.com/v0/meta/bases"; - Headers = GetAuthorizationHeader(Token); + + URL = "https://api.airtable.com/v0/meta/bases"; + Headers = GetAuthorizationHeader(Token); TableArray = New Array; - + For Each Table In TableCollection Do - + Description = GenerateTableDescription(Table.Key, Table.Value); TableArray.Add(Description); - + EndDo; - + Parameters = New Structure; - OPI_Tools.AddField("name" , Name , "String", Parameters); - OPI_Tools.AddField("tables" , TableArray , "Array", Parameters); - OPI_Tools.AddField("workspaceId", Workspace, "String", Parameters); - + OPI_Tools.AddField("name" , Name , "String", Parameters); + OPI_Tools.AddField("tables" , TableArray , "Array" , Parameters); + OPI_Tools.AddField("workspaceId", Workspace , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction @@ -137,56 +137,56 @@ EndFunction // Create table // Creates a new table in the base -// +// // Parameters: // Token - String - Token - token // Base - String - Base identifier - base // Name - String - New table name - title // FieldArray - Array of Structure - Array of field descriptions - fieldsdata // Description - String - Table description - description -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Airtable Function CreateTable(Val Token, Val Base, Val Name, Val FieldArray, Val Description = "") Export - + OPI_TypeConversion.GetLine(Base); - - URL = "https://api.airtable.com/v0/meta/bases/" + Base + "/tables"; - Headers = GetAuthorizationHeader(Token); - Parameters = GenerateTableDescription(Name, FieldArray, Description); - + + URL = "https://api.airtable.com/v0/meta/bases/" + Base + "/tables"; + Headers = GetAuthorizationHeader(Token); + Parameters = GenerateTableDescription(Name, FieldArray, Description); + Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction // Modify table // Changes the name and/or description of the base -// +// // Parameters: // Token - String - Token - token // Base - String - Base identifier - base // Table - String - Table identifier - table // Name - String - New name - title // Description - String - New description - description -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Airtable Function ModifyTable(Val Token, Val Base, Val Table, Val Name = "", Val Description = "") Export - + OPI_TypeConversion.GetLine(Base); OPI_TypeConversion.GetLine(Table); - - URL = "https://api.airtable.com/v0/meta/bases/" + Base + "/tables/" + Table; - Headers = GetAuthorizationHeader(Token); - Parameters = New Structure; - - OPI_Tools.AddField("name" , Name, "String", Parameters); + + URL = "https://api.airtable.com/v0/meta/bases/" + Base + "/tables/" + Table; + Headers = GetAuthorizationHeader(Token); + Parameters = New Structure; + + OPI_Tools.AddField("name" , Name , "String", Parameters); OPI_Tools.AddField("description", Description , "String", Parameters); - + Response = OPI_Tools.Patch(URL, Parameters, Headers); - + Return Response; EndFunction @@ -197,40 +197,40 @@ EndFunction // Create field // Creates a new field in the table -// +// // Parameters: // Token - String - Token - token // Base - String - Base identifier - base // Table - String - Table identifier - table // FieldStructure - Structure of KeyAndValue - Description of the new field - fielddata -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Airtable Function CreateField(Val Token, Val Base, Val Table, Val FieldStructure) Export - + OPI_TypeConversion.GetLine(Base); OPI_TypeConversion.GetLine(Table); OPI_TypeConversion.GetCollection(FieldStructure); - - If Not TypeOf(FieldStructure) = Type("Structure") + + If Not TypeOf(FieldStructure) = Type("Structure") And Not TypeOf(FieldStructure) = Type("Map") Then - + Raise "Error in field description data"; - + EndIf; - - URL = "https://api.airtable.com/v0/meta/bases/" + Base + "/tables/" + Table + "/fields"; - Headers = GetAuthorizationHeader(Token); - + + URL = "https://api.airtable.com/v0/meta/bases/" + Base + "/tables/" + Table + "/fields"; + Headers = GetAuthorizationHeader(Token); + Response = OPI_Tools.Post(URL, FieldStructure, Headers); - + Return Response; EndFunction // Modify field // Changes the name and/or description of an existing table field -// +// // Parameters: // Token - String - Token - token // Base - String - Base identifier Base - base @@ -238,152 +238,152 @@ EndFunction // Field - String - Field identifier - field // Name - String - New name - title // Description - String - New description - description -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Airtable Function ModifyField(Val Token, Val Base, Val Table, Val Field, Val Name = "", Val Description = "") Export - + OPI_TypeConversion.GetLine(Base); OPI_TypeConversion.GetLine(Table); OPI_TypeConversion.GetLine(Field); - - URL = "https://api.airtable.com/v0/meta/bases/" - + Base - + "/tables/" - + Table - + "/fields/" + + URL = "https://api.airtable.com/v0/meta/bases/" + + Base + + "/tables/" + + Table + + "/fields/" + Field; - + Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure(); - OPI_Tools.AddField("name" , Name, "String", Parameters); + OPI_Tools.AddField("name" , Name , "String", Parameters); OPI_Tools.AddField("description", Description , "String", Parameters); - + Response = OPI_Tools.Patch(URL, Parameters, Headers); - + Return Response; EndFunction // Get field (string) // Gets the description of a string field -// +// // Parameters: // Name - String - New field name - title -// +// // Returns: // Structure - Field description Function GetStringField(Val Name) Export - + Return PrimitiveFieldDescription(Name, "richText"); - + EndFunction // Get field (numeric) // Gets the description of a numeric field -// +// // Parameters: // Name - String - New field name - title // Precision - Number, String - Number of decimal places - precision -// +// // Returns: // Structure - Field description Function GetNumberField(Val Name, Val Precision = 0) Export - + OPI_TypeConversion.GetNumber(Precision); - + OptionsStructure = New Structure("precision", Precision); Return PrimitiveFieldDescription(Name, "number", OptionsStructure); - + EndFunction // Get field (file) // Gets the description of a file field -// +// // Parameters: // Name - String - Field name - title -// +// // Returns: // Structure - Field description Function GetAttachmentField(Val Name) Export - + Return PrimitiveFieldDescription(Name, "multipleAttachments"); - + EndFunction // Get field (checkbox) // Gets the description of a boolean field -// +// // Parameters: // Name - String - Field name - title -// +// // Returns: // Structure - Field description Function GetCheckboxField(Val Name) Export - + OptionsStructure = New Structure("icon,color", "check", "yellowBright"); Return PrimitiveFieldDescription(Name, "checkbox", OptionsStructure); - + EndFunction // Get field (date) // Gets the description of a date field -// +// // Parameters: // Name - String - Field name - title -// +// // Returns: // Structure - Field description Function GetDateField(Val Name) Export - - FormatStructure = New Structure("format,name", "YYYY-MM-DD", "iso"); + + FormatStructure = New Structure("format,name", "YYYY-MM-DD", "iso"); OptionsStructure = New Structure("dateFormat", FormatStructure); - + Return PrimitiveFieldDescription(Name, "date", OptionsStructure); - + EndFunction // Get field (email) // Gets the description of an email field -// +// // Parameters: // Name - String - Field name - title -// +// // Returns: // Structure - Field description Function GetEmailField(Val Name) Export - + Return PrimitiveFieldDescription(Name, "email"); - + EndFunction // Get field (phone) // Gets the description of a phone number field -// +// // Parameters: // Name - String - Field name - title -// +// // Returns: // Structure - Field description Function GetPhoneField(Val Name) Export - + Return PrimitiveFieldDescription(Name, "phoneNumber"); - + EndFunction // Get field (url) // Gets the description of a URL field -// +// // Parameters: // Name - String - Field name - title -// +// // Returns: // Structure - Field description Function GetLinkField(Val Name) Export - + Return PrimitiveFieldDescription(Name, "url"); - + EndFunction #EndRegion @@ -392,67 +392,67 @@ EndFunction // Get list of records // Gets the list of records of the selected table -// +// // Parameters: // Token - String - Token - token // Base - String - Database identifier - base // Table - String - Table identifier - table // Indent - String - Next page identifier of data from the previous request - offset -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Airtable Function GetListOfRecords(Val Token, Val Base, Val Table, Val Indent = "") Export OPI_TypeConversion.GetLine(Base); OPI_TypeConversion.GetLine(Table); - - URL = "https://api.airtable.com/v0/" + Base + "/" + Table; + + URL = "https://api.airtable.com/v0/" + Base + "/" + Table; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure(); OPI_Tools.AddField("offset", Indent, "String", Parameters); - + Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; - + EndFunction // Get record // Gets row data of the table by identifier -// +// // Parameters: // Token - String - Token - token // Base - String - Database identifier - base // Table - String - Table identifier - table // Record - String - Record identifier in the table - record -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Airtable Function GetRecord(Val Token, Val Base, Val Table, Val Record) Export - + OPI_TypeConversion.GetLine(Base); OPI_TypeConversion.GetLine(Table); OPI_TypeConversion.GetLine(Record); - - URL = "https://api.airtable.com/v0/" + Base + "/" + Table + "/" + Record; + + URL = "https://api.airtable.com/v0/" + Base + "/" + Table + "/" + Record; Headers = GetAuthorizationHeader(Token); Response = OPI_Tools.Get(URL, , Headers); - + Return Response; - + EndFunction // Create records // Creates one or an array of records by description or an array of field value descriptions -// +// // Parameters: // Token - String - Token - token // Base - String - Database identifier - base // Table - String - Table identifier - table // Data - Structure, Array of Structure - Set or array of sets of pairs Key : Value > Field : FieldValue - data -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Airtable Function CreatePosts(Val Token, Val Base, Val Table, Val Data) Export @@ -460,52 +460,52 @@ Function CreatePosts(Val Token, Val Base, Val Table, Val Data) Export OPI_TypeConversion.GetLine(Base); OPI_TypeConversion.GetLine(Table); OPI_TypeConversion.GetCollection(Data); - - Parameters = New Structure(); - AddDataDescription(Data, Parameters); - URL = "https://api.airtable.com/v0/" + Base + "/" + Table; + Parameters = New Structure(); + AddDataDescription(Data, Parameters); + + URL = "https://api.airtable.com/v0/" + Base + "/" + Table; Headers = GetAuthorizationHeader(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - - Return Response; - + + Return Response; + EndFunction // Delete records // Deletes one or an array of records by identifiers -// +// // Parameters: // Token - String - Token - token // Base - String - Database identifier - base // Table - String - Table identifier - table // Records - String, Array of String - Identifier or array of record identifiers - records -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Airtable Function DeletePosts(Val Token, Val Base, Val Table, Val Records) Export - + OPI_TypeConversion.GetLine(Base); OPI_TypeConversion.GetLine(Table); OPI_TypeConversion.GetArray(Records); - + RecordString = ""; - + For Each Record In Records Do - RecordString = RecordString + RecordString = RecordString + ?(ValueIsFilled(RecordString), "&", "?") + "records[]=" - + OPI_Tools.NumberToString(Record); + + OPI_Tools.NumberToString(Record); EndDo; - - URL = "https://api.airtable.com/v0/" + Base + "/" + Table + RecordString; + + URL = "https://api.airtable.com/v0/" + Base + "/" + Table + RecordString; Headers = GetAuthorizationHeader(Token); Response = OPI_Tools.Delete(URL, , Headers); - - Return Response; - + + Return Response; + EndFunction #EndRegion @@ -514,67 +514,67 @@ EndFunction // Get comments // Gets the list of comments for a record in the table -// +// // Parameters: // Token - String - Token - token // Base - String - Database identifier - base // Table - String - Table identifier - table // Record - String - Record identifier in the table - record // Indent - String - Next page identifier of data from the previous request - offset -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Airtable Function GetComments(Val Token, Val Base, Val Table, Val Record, Val Indent = "") Export - + OPI_TypeConversion.GetLine(Base); OPI_TypeConversion.GetLine(Table); OPI_TypeConversion.GetLine(Record); - - URL = "https://api.airtable.com/v0/" + Base + "/" + Table + "/" + Record + "/comments"; + + URL = "https://api.airtable.com/v0/" + Base + "/" + Table + "/" + Record + "/comments"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure(); OPI_Tools.AddField("offset", Indent, "String", Parameters); - + Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; - + EndFunction // Create comment // Creates a comment for a record in the table -// +// // Parameters: // Token - String - Token - token // Base - String - Database identifier - base // Table - String - Table identifier - table // Record - String - Record identifier in the table - record // Text - String - Comment text - text -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Airtable Function CreateComment(Val Token, Val Base, Val Table, Val Record, Val Text) Export - + OPI_TypeConversion.GetLine(Base); OPI_TypeConversion.GetLine(Table); OPI_TypeConversion.GetLine(Record); - - URL = "https://api.airtable.com/v0/" + Base + "/" + Table + "/" + Record + "/comments"; + + URL = "https://api.airtable.com/v0/" + Base + "/" + Table + "/" + Record + "/comments"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure(); OPI_Tools.AddField("text", Text, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Modify comment // Changes the text of an existing comment -// +// // Parameters: // Token - String - Token - token // Base - String - Database identifier - base @@ -582,54 +582,54 @@ EndFunction // Record - String - Record identifier in the table - record // Comment - String - Comment identifier - comment // Text - String - New comment text - text -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Airtable Function EditComment(Val Token, Val Base, Val Table, Val Record, Val Comment, Val Text) Export - + OPI_TypeConversion.GetLine(Base); OPI_TypeConversion.GetLine(Table); OPI_TypeConversion.GetLine(Record); OPI_TypeConversion.GetLine(Comment); - - URL = "https://api.airtable.com/v0/" + Base + "/" + Table + "/" + Record + "/comments/" + Comment; + + URL = "https://api.airtable.com/v0/" + Base + "/" + Table + "/" + Record + "/comments/" + Comment; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure(); OPI_Tools.AddField("text", Text, "String", Parameters); - + Response = OPI_Tools.Patch(URL, Parameters, Headers); - + Return Response; - + EndFunction // Delete comment // Deletes a comment for a table record -// +// // Parameters: // Token - String - Token - token // Base - String - Database identifier - base // Table - String - Table identifier - table // Record - String - Record identifier in the table - record // Comment - String - Comment identifier - comment -// +// // Returns: -// Map Of KeyAndValue - serialized JSON response from Airtable +// Map Of KeyAndValue - serialized JSON response from Airtable Function DeleteComment(Val Token, Val Base, Val Table, Val Record, Val Comment) Export OPI_TypeConversion.GetLine(Base); OPI_TypeConversion.GetLine(Table); OPI_TypeConversion.GetLine(Record); OPI_TypeConversion.GetLine(Comment); - - URL = "https://api.airtable.com/v0/" + Base + "/" + Table + "/" + Record + "/comments/" + Comment; + + URL = "https://api.airtable.com/v0/" + Base + "/" + Table + "/" + Record + "/comments/" + Comment; Headers = GetAuthorizationHeader(Token); - + Response = OPI_Tools.Delete(URL, , Headers); - + Return Response; - + EndFunction #EndRegion @@ -639,58 +639,58 @@ EndFunction #Region Private Function GetAuthorizationHeader(Val Token) - + OPI_TypeConversion.GetLine(Token); - + Headers = New Map; Headers.Insert("Authorization", "Bearer " + Token); - + Return Headers; - + EndFunction Function GenerateTableDescription(Val Name, Val FieldArray, Val Description = "") - + OPI_TypeConversion.GetLine(Name); OPI_TypeConversion.GetCollection(FieldArray); - + TableDescription = New Structure("name,fields", Name, FieldArray); - + OPI_Tools.AddField("description", Description, "String", TableDescription); - + Return TableDescription; - + EndFunction Function PrimitiveFieldDescription(Val Name, Val Type, Val Options = "") - + FieldStructure = New Structure(); - OPI_Tools.AddField("name" , Name, "String" , FieldStructure); - OPI_Tools.AddField("type" , Type , "String" , FieldStructure); + OPI_Tools.AddField("name" , Name , "String" , FieldStructure); + OPI_Tools.AddField("type" , Type , "String" , FieldStructure); OPI_Tools.AddField("options", Options , "Collection", FieldStructure); - + Return FieldStructure; EndFunction Procedure AddDataDescription(Val Data, Parameters) - + If TypeOf(Data) = Type("Array") Then - + SendArray = New Array; - + For Each RecordDescription In Data Do - SendArray.Add(New Structure("fields", RecordDescription)); + SendArray.Add(New Structure("fields", RecordDescription)); EndDo; - + OPI_Tools.AddField("records", SendArray, "Array", Parameters); - + Else - - OPI_Tools.AddField("fields", Data, "Collection", Parameters); - + + OPI_Tools.AddField("fields", Data, "Collection", Parameters); + EndIf; - + EndProcedure #EndRegion diff --git a/src/en/OPI/src/CommonModules/OPI_Bitrix24/Module.bsl b/src/en/OPI/src/CommonModules/OPI_Bitrix24/Module.bsl index 0ad1d9d953..75ed2d5a58 100644 --- a/src/en/OPI/src/CommonModules/OPI_Bitrix24/Module.bsl +++ b/src/en/OPI/src/CommonModules/OPI_Bitrix24/Module.bsl @@ -47,105 +47,105 @@ // Get app authentication link // Forms a link for authorization via the browser -// +// // Parameters: // Domain - String - Current Bitrix URL (like 'portal.bitrix24.com') - domain // ClientID - String - Client ID from app settings - clientid -// +// // Returns: // String - URL for browser transition Function GetAppAuthLink(Val Domain, Val ClientID) Export - + OPI_TypeConversion.GetLine(Domain); OPI_TypeConversion.GetLine(ClientID); - + If Not StrStartsWith(Domain, "http") Then URL = "https://" + Domain; EndIf; - + If Not StrEndsWith(URL, "/") Then URL = URL + "/"; EndIf; - + URL = URL + "oauth/authorize/?client_id=" + ClientID; - + Return URL; - + EndFunction // Get token // Get token by auth code -// +// // Parameters: // ClientID - String - Client ID from app settings - clientid // ClientSecret - String - Client secret from app settings - clientsecret // Code - String - Code from browser auth page - code -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetToken(Val ClientID, Val ClientSecret, Val Code) Export - - URL = "https://oauth.bitrix.info/oauth/token/"; + + URL = "https://oauth.bitrix.info/oauth/token/"; String_ = "String"; - + Parameters = New Structure; - OPI_Tools.AddField("grant_type" , "authorization_code", String_, Parameters); - OPI_Tools.AddField("client_id" , ClientID , String_, Parameters); - OPI_Tools.AddField("client_secret", ClientSecret , String_, Parameters); - OPI_Tools.AddField("code" , Code , String_, Parameters); - + OPI_Tools.AddField("grant_type" , "authorization_code", String_, Parameters); + OPI_Tools.AddField("client_id" , ClientID , String_, Parameters); + OPI_Tools.AddField("client_secret", ClientSecret , String_, Parameters); + OPI_Tools.AddField("code" , Code , String_, Parameters); + Response = OPI_Tools.Get(URL, Parameters); - + Return Response; - + EndFunction // Refresh token // Update token by refresh token -// +// // Parameters: // ClientID - String - Client ID from app settings - clientid // ClientSecret - String - Client secret from app settings - clientsecret // Refresh - String - Refresh token - refresh -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function RefreshToken(Val ClientID, Val ClientSecret, Val Refresh) Export - - URL = "https://oauth.bitrix.info/oauth/token/"; + + URL = "https://oauth.bitrix.info/oauth/token/"; String_ = "String"; - + Parameters = New Structure; - OPI_Tools.AddField("grant_type" , "refresh_token" , String_, Parameters); - OPI_Tools.AddField("client_id" , ClientID , String_, Parameters); - OPI_Tools.AddField("client_secret", ClientSecret , String_, Parameters); - OPI_Tools.AddField("refresh_token", Refresh , String_, Parameters); - + OPI_Tools.AddField("grant_type" , "refresh_token" , String_, Parameters); + OPI_Tools.AddField("client_id" , ClientID , String_, Parameters); + OPI_Tools.AddField("client_secret", ClientSecret , String_, Parameters); + OPI_Tools.AddField("refresh_token", Refresh , String_, Parameters); + Response = OPI_Tools.Get(URL, Parameters); - + Return Response; EndFunction // Server time // Get current server time -// +// // Note // Method at API documentation: [server_time](@dev.1c-bitrix.ru/rest_help/general/server_time.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function ServerTime(Val URL, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "server.time"); - Response = OPI_Tools.Get(URL, Parameters); - + Response = OPI_Tools.Get(URL, Parameters); + Return Response; - + EndFunction #EndRegion @@ -154,19 +154,19 @@ EndFunction // Create post // Create a new post at news feed -// +// // Note // Method at API documentation: [log.blogpost.add](@dev.1c-bitrix.ru/rest_help/log/log_blogpost_add.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Text - String - Text of post - text // Visibility - String - Array or 1 recipient: UA all, SGn w. group, Un user, DRn department, Gn group - vision // Files - Map Of KeyAndValue - Key > file name, value > path or binary data - files // Title - String - Post title - title -// Important - Boolean - Mark post as important - important +// Important - Boolean - Mark post as important - important // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function CreatePost(Val URL @@ -176,41 +176,41 @@ Function CreatePost(Val URL , Val Title = "" , Val Important = False , Val Token = "") Export - + MakeBoolean(Important); - + String_ = "String"; - + Parameters = NormalizeAuth(URL, Token, "log.blogpost.add"); - OPI_Tools.AddField("POST_MESSAGE", Text , String_, Parameters); - OPI_Tools.AddField("POST_TITLE" , Title , String_, Parameters); - OPI_Tools.AddField("DEST" , Visibility , "Array", Parameters); - OPI_Tools.AddField("IMPORTANT" , Important , String_, Parameters); - + OPI_Tools.AddField("POST_MESSAGE", Text , String_, Parameters); + OPI_Tools.AddField("POST_TITLE" , Title , String_, Parameters); + OPI_Tools.AddField("DEST" , Visibility , "Array", Parameters); + OPI_Tools.AddField("IMPORTANT" , Important , String_, Parameters); + If ValueIsFilled(Files) Then - + OPI_TypeConversion.GetCollection(Files); - + ArrayOfFiles = NormalizeFiles(Files); - + If Not ArrayOfFiles.Count() = 0 Then Parameters.Insert("FILES", ArrayOfFiles); EndIf; - + EndIf; - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Update post // Change post data -// +// // Note // Method at API documentation: [log.blogpost.update](@dev.1c-bitrix.ru/rest_help/log/log_blogpost_update.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // PostID - String, Number - Post ID - postid @@ -219,170 +219,170 @@ EndFunction // Files - Map Of KeyAndValue - Key > file name, value > path or binary data - files // Title - String - Post title - title // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function UpdatePost(Val URL - , Val PostID + , Val PostID , Val Text , Val Visibility = "UA" , Val Files = "" , Val Title = "" , Val Token = "") Export - + String_ = "String"; - + Parameters = NormalizeAuth(URL, Token, "log.blogpost.update"); - OPI_Tools.AddField("POST_MESSAGE", Text , String_, Parameters); - OPI_Tools.AddField("POST_TITLE" , Title , String_, Parameters); - OPI_Tools.AddField("DEST" , Visibility , "Array", Parameters); - OPI_Tools.AddField("POST_ID" , PostID , String_, Parameters); - + OPI_Tools.AddField("POST_MESSAGE", Text , String_, Parameters); + OPI_Tools.AddField("POST_TITLE" , Title , String_, Parameters); + OPI_Tools.AddField("DEST" , Visibility , "Array", Parameters); + OPI_Tools.AddField("POST_ID" , PostID , String_, Parameters); + If ValueIsFilled(Files) Then - + OPI_TypeConversion.GetCollection(Files); - + ArrayOfFiles = NormalizeFiles(Files); - + If Not ArrayOfFiles.Count() = 0 Then Parameters.Insert("FILES", ArrayOfFiles); EndIf; - + EndIf; - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Delete post // Remove post from a news feed -// +// // Note // Method at API documentation: [log.blogpost.delete](@dev.1c-bitrix.ru/rest_help/log/log_blogpost_delete.php) -// +// // Parameters: -// URL - String - URL of webhook or a Bitrix24 domain, when token used - url +// URL - String - URL of webhook or a Bitrix24 domain, when token used - url // PostID - String, Number - Id of post to remove - postid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeletePost(Val URL, Val PostID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "log.blogpost.delete"); OPI_Tools.AddField("POST_ID", PostID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get list of important post viewers // Return list of important post viewers ids -// +// // Note // Method at API documentation: [log.blogpost.getusers.important](@dev.1c-bitrix.ru/rest_help/log/log_blogpost_getusers_important.php) -// +// // Parameters: -// URL - String - URL of webhook or a Bitrix24 domain, when token used - url +// URL - String - URL of webhook or a Bitrix24 domain, when token used - url // PostID - String, Number - Id of important post - postid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetImportantPostViewers(Val URL, Val PostID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "log.blogpost.getusers.important"); OPI_Tools.AddField("POST_ID", PostID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get posts // Gen post or array of post with ID or rights selection -// +// // Note // Method at API documentation: [log.blogpost.get](@dev.1c-bitrix.ru/rest_help/log/log_blogpost_get.php) -// +// // Parameters: -// URL - String - URL of webhook or a Bitrix24 domain, when token used - url +// URL - String - URL of webhook or a Bitrix24 domain, when token used - url // PostID - String, Number - Id of important post - postid -// Filter - String - Post selection by rights: UA all, SGn work group, Un user, DRn depart, Gn group - sel +// Filter - String - Post selection by rights: UA all, SGn work group, Un user, DRn depart, Gn group - sel // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetPosts(Val URL, Val PostID = "", Val Filter = "UA", Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "log.blogpost.get"); - - OPI_Tools.AddField("POST_ID" , PostID, "String", Parameters); + + OPI_Tools.AddField("POST_ID" , PostID , "String", Parameters); OPI_Tools.AddField("LOG_RIGHTS", Filter , "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Add comment to post // Adds a comment to the post -// +// // Note // Method at API documentation: [log.blogcomment.add](@dev.1c-bitrix.ru/rest_help/log/log_blogcomment_add.php) -// +// // Parameters: -// URL - String - URL of webhook or a Bitrix24 domain, when token used - url +// URL - String - URL of webhook or a Bitrix24 domain, when token used - url // PostID - String, Number - Post ID - postid // Text - String - Comment text - text // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function AddPostComment(Val URL, Val PostID, Val Text, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "log.blogcomment.add"); - + OPI_Tools.AddField("POST_ID" , PostID, "String", Parameters); - OPI_Tools.AddField("TEXT" , Text , "String", Parameters); - + OPI_Tools.AddField("TEXT" , Text , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Add new recipients to a post // Adds new groups or users to the recipients -// +// // Note // Method at API documentation: [log.blogpost.share](@dev.1c-bitrix.ru/rest_help/log/log_blogpost_share.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // PostID - String, Number - Post ID - postid // Visibility - String - Array or 1 recipient: UA all, SGn w. group, Un user, DRn department, Gn group - vision // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function AddPostRecipients(Val URL, Val PostID, Val Visibility, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "log.blogpost.share"); - - OPI_Tools.AddField("POST_ID" , PostID, "String", Parameters); - OPI_Tools.AddField("DEST" , Visibility, "String", Parameters); - + + OPI_Tools.AddField("POST_ID" , PostID , "String", Parameters); + OPI_Tools.AddField("DEST" , Visibility, "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction #EndRegion @@ -391,629 +391,629 @@ EndFunction // Get task // Get task by ID -// +// // Note // Method at API documentation: [tasks.task.get](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_get.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetTask(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.get", Token); Return Response; - + EndFunction // Get tasks list // Get tasks list (50 at one response max)) -// +// // Note // Method at API documentation: [tasks.task.list](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_list.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Filter - Structure of KeyAndValue - Structure of task filter (see GetTaskFieldsStructure) - filter // Indent - Number, String - Offset of tasks list - offset // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetTasksList(Val URL, Val Filter = "", Val Indent = 0, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "tasks.task.list"); OPI_Tools.AddField("filter", Filter, "Collection", Parameters); - OPI_Tools.AddField("start" , Indent, "String" , Parameters); - + OPI_Tools.AddField("start" , Indent, "String" , Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Create task // Create new task by fields structure (see GetTaskFieldsStructure) -// +// // Note // Method at API documentation: [tasks.task.add](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_add.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FieldsStructure - Structure of KeyAndValue - Task fields structure (see GetTaskFieldsStructure) - fields // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function CreateTask(Val URL, Val FieldsStructure, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "tasks.task.add"); OPI_Tools.AddField("fields", FieldsStructure, "Collection", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; EndFunction // Update task // Update a task -// +// // Note // Method at API documentation: [tasks.task.update](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_update.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // FieldsStructure - Structure of KeyAndValue - Task fields structure - fields // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function UpdateTask(Val URL, Val TaskID, Val FieldsStructure, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "tasks.task.update"); OPI_Tools.AddField("fields", FieldsStructure, "Collection", Parameters); - OPI_Tools.AddField("taskId", TaskID , "String" , Parameters); - + OPI_Tools.AddField("taskId", TaskID , "String" , Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; EndFunction // Delete task // Delete task by ID -// +// // Note // Method at API documentation: [tasks.task.delete](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_delete.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeleteTask(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.delete", Token); Return Response; - + EndFunction // Attach file to the topic // Attaches a file to the selected task -// +// // Note // Method at API documentation: [tasks.task.files.attach](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_files_attach.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // FileID - Number, String - File ID - fileid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function AttachFileToTopic(Val URL, Val TaskID, Val FileID, Val Token = "") Export Parameters = NormalizeAuth(URL, Token, "tasks.task.files.attach"); OPI_Tools.AddField("fileId", FileID , "String", Parameters); - OPI_Tools.AddField("taskId", TaskID, "String", Parameters); - + OPI_Tools.AddField("taskId", TaskID , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Approve task // Approve task by ID -// +// // Note // Method at API documentation: [tasks.task.approve](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_approve.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function ApproveTask(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.approve", Token); Return Response; - + EndFunction // Disapprove task // Disapprove task by ID -// +// // Note // Method at API documentation: [tasks.task.disapprove](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_disapprove.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DisapproveTask(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.disapprove", Token); Return Response; - + EndFunction // Complete task // Complete task by ID -// +// // Note // Method at API documentation: [tasks.task.complete](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_complete.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function CompleteTask(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.complete", Token); Return Response; - + EndFunction // Renew task // Returns a task to work by ID -// +// // Note // Method at API documentation: [tasks.task.renew](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_renew.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function RenewTask(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.renew", Token); Return Response; - + EndFunction // Defer task // Defer task by ID -// +// // Note // Method at API documentation: [tasks.task.defer](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_defer.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeferTask(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.defer", Token); Return Response; - + EndFunction // Pause task // Pause a task by ID -// +// // Note // Method at API documentation: [tasks.task.pause](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_pause.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function PauseTask(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.pause", Token); Return Response; - + EndFunction // Start a task // Start a task by ID -// +// // Note // Method at API documentation: [tasks.task.start](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_start.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function StartTask(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.start", Token); Return Response; - + EndFunction // Start watching a task // Start watching a task by ID -// +// // Note // Method at API documentation: [tasks.task.startwatch](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_startwatch.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function StartWatchingTask(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.startwatch", Token); Return Response; - + EndFunction // Stop watching the task // Stop watching a task by ID -// +// // Note // Method at API documentation: [tasks.task.stopwatch](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_stopwatch.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function StopWatchingTask(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.stopwatch", Token); Return Response; - + EndFunction // Delegate task // Delegate task to another user -// +// // Note // Method at API documentation: [tasks.task.delegate](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_delegate.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // UserID - Number, String - ID of responsible user - user // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DelegateTask(Val URL, Val TaskID, Val UserID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "tasks.task.delegate"); OPI_Tools.AddField("taskId", TaskID , "String", Parameters); - OPI_Tools.AddField("userId", UserID, "String", Parameters); - + OPI_Tools.AddField("userId", UserID , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Add task to favorites list // Add task to favorites list -// +// // Note // Method at API documentation: [tasks.task.favorite.add](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_favorite_add.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function AddTaskToFavorites(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.favorite.add", Token); Return Response; - + EndFunction // Remove task from favorites list // Delete task from favorites list -// +// // Note // Method at API documentation: [tasks.task.favorite.remove](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_favorite_remove.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function RemoveTaskFromFavorites(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.favorite.remove", Token); Return Response; - + EndFunction // Get task history // Get history of task changing -// +// // Note // Method at API documentation: [tasks.task.history.list](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_history_list.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetTaskHistory(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.history.list", Token); Return Response; - + EndFunction // Check task acesses for users // Checks the availability of the task for users -// +// // Note // Method at API documentation: [tasks.task.getaccess](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_getaccess.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Users - Array of String - User IDs for access checking - users // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function CheckTaskAccesses(Val URL, Val TaskID, Val Users = "", Val Token = "") Export Parameters = NormalizeAuth(URL, Token, "tasks.task.getaccess"); OPI_Tools.AddField("taskId", TaskID , "String" , Parameters); - OPI_Tools.AddField("users" , Users, "Array", Parameters); - + OPI_Tools.AddField("users" , Users , "Array" , Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Mute task // Mute task by ID -// +// // Note // Method at API documentation: [tasks.task.mute](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/mute_unmute.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function MuteTask(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.mute", Token); Return Response; - + EndFunction // Unmute task // Unmute task by ID -// +// // Note // Method at API documentation: [tasks.task.unmute](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/mute_unmute.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function UnmuteTask(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.unmute", Token); Return Response; - + EndFunction // Create tasks dependencies // Creates the dependency of one task to another -// +// // Note // Method at API documentation: [task.dependence.add](@dev.1c-bitrix.ru/rest_help/tasks/task/dependence/task_dependence_add.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FromID - String, Number - From task ID - taskfrom // DestinationID - String, Number - To task ID - taskto // LinkType - String, Number - Link type: 0 start>start, 1 start>finish, 2 finish>start, 3 finish>finish - linktype // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function CreateTasksDependencies(Val URL, Val FromID, Val DestinationID, Val LinkType, Val Token = "") Export - + String_ = "String"; - + OPI_TypeConversion.GetLine(LinkType); - + Parameters = NormalizeAuth(URL, Token, "task.dependence.add"); - OPI_Tools.AddField("taskIdFrom", FromID, String_, Parameters); - OPI_Tools.AddField("taskIdTo" , DestinationID, String_, Parameters); - OPI_Tools.AddField("linkType" , LinkType , String_, Parameters); - + OPI_Tools.AddField("taskIdFrom", FromID , String_, Parameters); + OPI_Tools.AddField("taskIdTo" , DestinationID, String_, Parameters); + OPI_Tools.AddField("linkType" , LinkType , String_, Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Delete tasks dependencies // Removes the dependency of one task to another -// +// // Note // Method at API documentation: [task.dependence.delete](@dev.1c-bitrix.ru/rest_help/tasks/task/dependence/task_dependence_delete.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FromID - String, Number - From task ID - taskfrom // DestinationID - String, Number - To task ID - taskto // LinkType - String, Number - Link type: 0 start>start, 1 start>finish, 2 finish>start, 3 finish>finish - linktype // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeleteTasksDependencies(Val URL, Val FromID, Val DestinationID, Val LinkType, Val Token = "") Export - + String_ = "String"; - + OPI_TypeConversion.GetLine(LinkType); - + Parameters = NormalizeAuth(URL, Token, "task.dependence.delete"); - OPI_Tools.AddField("taskIdFrom", FromID, String_, Parameters); - OPI_Tools.AddField("taskIdTo" , DestinationID, String_, Parameters); - OPI_Tools.AddField("linkType" , LinkType , String_, Parameters); - + OPI_Tools.AddField("taskIdFrom", FromID , String_, Parameters); + OPI_Tools.AddField("taskIdTo" , DestinationID, String_, Parameters); + OPI_Tools.AddField("linkType" , LinkType , String_, Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get users daily tasks plan // Gets the task plan for the current users day -// +// // Note // Method at API documentation: [task.planner.getlist](@dev.1c-bitrix.ru/rest_help/tasks/task/planner/getlist.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetDailyPlan(Val URL, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "task.planner.getlist"); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get task fields structure // Gets a structure with a description of the fields for creating a task -// +// // Note // Method at API documentation: [tasks.task.getFields](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_getFields.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetTaskFieldsStructure(Val URL, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "tasks.task.getFields"); - Response = OPI_Tools.Get(URL, Parameters); - + Response = OPI_Tools.Get(URL, Parameters); + Return Response; - -EndFunction + +EndFunction // Get structure of tasks filter // Return filter structure for GetTasksList -// +// // Parameters: // Clear - Boolean - True > structure with empty valuse, False > field descriptions at values - empty -// +// // Returns: -// Structure of KeyAndValue - Fields structure +// Structure of KeyAndValue - Fields structure Function GetTasksFilterStructure(Val Clear = False) Export - + // More // https://dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_list.php - + OPI_TypeConversion.GetBoolean(Clear); - + FilterStructure = New Structure; - FilterStructure.Insert("ID" , ""); - FilterStructure.Insert("PARENT_ID" , ""); - FilterStructure.Insert("GROUP_ID" , ""); - FilterStructure.Insert("CREATED_BY" , ""); + FilterStructure.Insert("ID" , ""); + FilterStructure.Insert("PARENT_ID" , ""); + FilterStructure.Insert("GROUP_ID" , ""); + FilterStructure.Insert("CREATED_BY" , ""); FilterStructure.Insert("STATUS_CHANGED_BY", ""); - FilterStructure.Insert("PRIORITY" , ""); - FilterStructure.Insert("FORUM_TOPIC_ID" , ""); - FilterStructure.Insert("RESPONSIBLE_ID" , ""); - FilterStructure.Insert("TITLE" , ""); - FilterStructure.Insert("TAG" , ""); - FilterStructure.Insert("REAL_STATUS" , ""); - FilterStructure.Insert("MARK" , ""); - FilterStructure.Insert("SITE_ID" , ""); - FilterStructure.Insert("ADD_IN_REPORT" , ""); - FilterStructure.Insert("DATE_START" , ""); - FilterStructure.Insert("DEADLINE" , ""); - FilterStructure.Insert("CREATED_DATE" , ""); - FilterStructure.Insert("CLOSED_DATE" , ""); - FilterStructure.Insert("CHANGED_DATE" , ""); - FilterStructure.Insert("ACCOMPLICE" , ""); - FilterStructure.Insert("AUDITOR" , ""); - FilterStructure.Insert("DEPENDS_ON" , ""); - FilterStructure.Insert("ONLY_ROOT_TASKS" , ""); - FilterStructure.Insert("STAGE_ID" , ""); - FilterStructure.Insert("UF_CRM_TASK" , ""); + FilterStructure.Insert("PRIORITY" , ""); + FilterStructure.Insert("FORUM_TOPIC_ID" , ""); + FilterStructure.Insert("RESPONSIBLE_ID" , ""); + FilterStructure.Insert("TITLE" , ""); + FilterStructure.Insert("TAG" , ""); + FilterStructure.Insert("REAL_STATUS" , ""); + FilterStructure.Insert("MARK" , ""); + FilterStructure.Insert("SITE_ID" , ""); + FilterStructure.Insert("ADD_IN_REPORT" , ""); + FilterStructure.Insert("DATE_START" , ""); + FilterStructure.Insert("DEADLINE" , ""); + FilterStructure.Insert("CREATED_DATE" , ""); + FilterStructure.Insert("CLOSED_DATE" , ""); + FilterStructure.Insert("CHANGED_DATE" , ""); + FilterStructure.Insert("ACCOMPLICE" , ""); + FilterStructure.Insert("AUDITOR" , ""); + FilterStructure.Insert("DEPENDS_ON" , ""); + FilterStructure.Insert("ONLY_ROOT_TASKS" , ""); + FilterStructure.Insert("STAGE_ID" , ""); + FilterStructure.Insert("UF_CRM_TASK" , ""); FilterStructure.Insert("STATUS" , ""); - + If Clear Then For Each Filter In FilterStructure Do Filter.Value = ""; @@ -1022,7 +1022,7 @@ Function GetTasksFilterStructure(Val Clear = False) Export //@skip-check constructor-function-return-section Return FilterStructure; - + EndFunction #EndRegion @@ -1031,185 +1031,185 @@ EndFunction // Add tasks checklist element // Adds new element of tasks checklist -// +// // Note // Method at API documentation: [task.checklistitem.add](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/add.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Text - String - Text (title) of checklist element - text // Completed - Boolean - Mark as completed - complete // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function AddTasksChecklistElement(Val URL, Val TaskID, Val Text, Val Completed = False, Token = "") Export - + String_ = "String"; - + Parameters = NormalizeAuth(URL, Token, "task.checklistitem.add"); - Fields = New Structure; - + Fields = New Structure; + MakeBoolean(Completed); - - OPI_Tools.AddField("TITLE" , Text , String_, Fields); + + OPI_Tools.AddField("TITLE" , Text , String_, Fields); OPI_Tools.AddField("IS_COMPLETE", Completed, String_, Fields); - - OPI_Tools.AddField("TASKID", TaskID, String_ , Parameters); + + OPI_Tools.AddField("TASKID", TaskID , String_ , Parameters); OPI_Tools.AddField("FIELDS", Fields , "Collection", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Update tasks checklist element // Updates text of element of tasks checklist -// +// // Note // Method at API documentation: [task.checklistitem.update](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/update.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // ElementID - Number, String - Checklist element ID - element // Text - String - Text (title) of checklist element - text // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function UpdateTasksChecklistElement(Val URL, Val TaskID, Val ElementID, Val Text, Val Token = "") Export - + String_ = "String"; - + Parameters = NormalizeAuth(URL, Token, "task.checklistitem.update"); - Fields = New Structure; - + Fields = New Structure; + OPI_Tools.AddField("TITLE", Text, String_, Fields); - - OPI_Tools.AddField("TASKID", TaskID , String_ , Parameters); - OPI_Tools.AddField("ITEMID", ElementID, String_ , Parameters); - OPI_Tools.AddField("FIELDS", Fields , "Collection", Parameters); - + + OPI_Tools.AddField("TASKID", TaskID , String_ , Parameters); + OPI_Tools.AddField("ITEMID", ElementID, String_ , Parameters); + OPI_Tools.AddField("FIELDS", Fields , "Collection", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction - + // Delete tasks checklist element // Deletes element from tasks checklist -// +// // Note // Method at API documentation: [task.checklistitem.delete](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/delete.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // ElementID - Number, String - ID of deleted element - element // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeleteTasksChecklistElement(Val URL, Val TaskID, Val ElementID, Val Token = "") Export Response = ChecklistElementManagment(URL, TaskID, ElementID, "task.checklistitem.delete", Token); - + Return Response; - + EndFunction // Get tasks checklist // Gets the list of elements on the task checklist -// +// // Note // Method at API documentation: [task.checklistitem.getlist](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/getlist.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetTasksChecklist(Val URL, Val TaskID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "task.checklistitem.getlist"); - + OPI_Tools.AddField("TASKID", TaskID , "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get tasks checklist element // Gets tasks checklist element by ID -// +// // Note // Method at API documentation: [task.checklistitem.get](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/get.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // ElementID - Number, String - Element ID - element // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetTasksChecklistElement(Val URL, Val TaskID, Val ElementID, Val Token = "") Export - + Response = ChecklistElementManagment(URL, TaskID, ElementID, "task.checklistitem.get", Token); - + Return Response; - + EndFunction // Complete tasks checklist element // Mark an element as completed -// +// // Note // Method at API documentation: [task.checklistitem.complete](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/complete.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // ElementID - Number, String - Element ID - element // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function CompleteTasksChecklistElement(Val URL, Val TaskID, Val ElementID, Val Token = "") Export - + Response = ChecklistElementManagment(URL, TaskID, ElementID, "task.checklistitem.complete", Token); - + Return Response; - + EndFunction // Renew tasks checklist element -// Unmark an element as completed -// +// Unmark an element as completed +// // Note // Method at API documentation: [task.checklistitem.renew](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/renew.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // ElementID - Number, String - Element ID - element // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function RenewTasksChecklistElement(Val URL, Val TaskID, Val ElementID, Val Token = "") Export - + Response = ChecklistElementManagment(URL, TaskID, ElementID, "task.checklistitem.renew", Token); - + Return Response; - + EndFunction #EndRegion @@ -1218,15 +1218,15 @@ EndFunction // Get comments list for a task // Get user comments list for a task -// +// // Note // Method at API documentation: [task.commentitem.getlist](@dev.1c-bitrix.ru/rest_help/tasks/task/commentitem/getlist.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetTaskCommentsList(Val URL, Val TaskID, Val Token = "") Export @@ -1238,220 +1238,220 @@ EndFunction // Get task comment // Gets task comment data by ID -// +// // Note // Method at API documentation: [task.commentitem.get](@dev.1c-bitrix.ru/rest_help/tasks/task/commentitem/get.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // CommentID - Number, String - CommentID - comment // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetTaskComment(Val URL, Val TaskID, Val CommentID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "task.commentitem.get"); - OPI_Tools.AddField("TASKID", TaskID , "String", Parameters); + OPI_Tools.AddField("TASKID", TaskID , "String", Parameters); OPI_Tools.AddField("ITEMID", CommentID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Add comment to task // Create new comment to the task -// +// // Note // Method at API documentation: [task.commentitem.add](@dev.1c-bitrix.ru/rest_help/tasks/task/commentitem/add.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Text - String - Comment text - text // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function AddTaskComment(Val URL, Val TaskID, Val Text, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "task.commentitem.add"); - + Comment = New Structure; OPI_Tools.AddField("POST_MESSAGE", Text, "String", Comment); - - OPI_Tools.AddField("TASKID", TaskID , "String" , Parameters); + + OPI_Tools.AddField("TASKID", TaskID , "String" , Parameters); OPI_Tools.AddField("FIELDS", Comment, "Collection", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Update task comment // Changes task comment text -// +// // Note // Method at API documentation: [task.commentitem.update](@dev.1c-bitrix.ru/rest_help/tasks/task/commentitem/update.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // CommentID - Number, String - CommentID - comment // Text - String - Comment text - text // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function UpdateTaskComment(Val URL, Val TaskID, Val CommentID, Val Text, Val Token = "") Export - + String_ = "String"; - + Parameters = NormalizeAuth(URL, Token, "task.commentitem.update"); - + Comment = New Structure; OPI_Tools.AddField("POST_MESSAGE", Text, "String", Comment); - - OPI_Tools.AddField("TASKID", TaskID , String_ , Parameters); - OPI_Tools.AddField("ITEMID", CommentID, String_ , Parameters); - OPI_Tools.AddField("FIELDS", Comment , "Collection", Parameters); - + + OPI_Tools.AddField("TASKID", TaskID , String_ , Parameters); + OPI_Tools.AddField("ITEMID", CommentID, String_ , Parameters); + OPI_Tools.AddField("FIELDS", Comment , "Collection", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Delete comment // Delete task comment by ID -// +// // Note // Method at API documentation: [task.commentitem.delete](@dev.1c-bitrix.ru/rest_help/tasks/task/commentitem/delete.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // CommentID - Number, String - ID of comment to remove - comment // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeleteTaskComment(Val URL, Val TaskID, Val CommentID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "task.commentitem.delete"); - OPI_Tools.AddField("TASKID", TaskID , "String", Parameters); + OPI_Tools.AddField("TASKID", TaskID , "String", Parameters); OPI_Tools.AddField("ITEMID", CommentID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get results list // Gets results list for task -// +// // Note // Method at API documentation: [tasks.task.result.list](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_result.list.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - Number, String - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetResultsList(Val URL, Val TaskID, Val Token = "") Export - + Response = ManageTask(URL, TaskID, "tasks.task.result.list", Token); Return Response; - + EndFunction // Create result from comment // Create task result from comment -// +// // Note // Method at API documentation: [tasks.task.result.addFromComment](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_result_addFromComment.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // CommentID - Number, String - CommentID - comment // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function CreateResultFromComment(Val URL, Val CommentID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "tasks.task.result.addFromComment"); OPI_Tools.AddField("commentId", CommentID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Delete result from comment // Deletes task result, created from a comment -// +// // Note // Method at API documentation: [tasks.task.result.deleteFromComment](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_result_deleteFromComment.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // CommentID - Number, String - CommentID - comment // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeleteResultFromComment(Val URL, Val CommentID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "tasks.task.result.deleteFromComment"); OPI_Tools.AddField("commentId", CommentID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get comment structure // Get comment fields structure -// +// // Parameters: // Clear - Boolean - True > structure with empty valuse, False > field descriptions at values - empty -// +// // Returns: -// Structure of KeyAndValue - Fields structure +// Structure of KeyAndValue - Fields structure Function GetCommentStructure(Val Clear = False) Export - + // More // https://dev.1c-bitrix.ru/rest_help/tasks/task/commentitem/add.php - + OPI_TypeConversion.GetBoolean(Clear); - + FieldsStructure = New Structure; - FieldsStructure.Insert("AUTHOR_ID" , ""); - FieldsStructure.Insert("AUTHOR_NAME" , ""); - FieldsStructure.Insert("AUTHOR_EMAIL" , ""); - FieldsStructure.Insert("USE_SMILES" , "<(Y|N) - parse comments for emoticons or not>"); - FieldsStructure.Insert("POST_MESSAGE" , ""); + FieldsStructure.Insert("AUTHOR_ID" , ""); + FieldsStructure.Insert("AUTHOR_NAME" , ""); + FieldsStructure.Insert("AUTHOR_EMAIL" , ""); + FieldsStructure.Insert("USE_SMILES" , "<(Y|N) - parse comments for emoticons or not>"); + FieldsStructure.Insert("POST_MESSAGE" , ""); FieldsStructure.Insert("UF_FORUM_MESSAGE_DOC" , ""); - + If Clear Then For Each Field In FieldsStructure Do Field.Value = ""; EndDo; EndIf; - + //@skip-check constructor-function-return-section Return FieldsStructure; - + EndFunction #EndRegion @@ -1460,10 +1460,10 @@ EndFunction // Add kanban stage // Add new stage of kanban or My Plan -// +// // Note // Method at API documentation: [task.stages.add](@dev.1c-bitrix.ru/rest_help/tasks/task/kanban/task_stages_add.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Name - String - New stage name - title @@ -1472,7 +1472,7 @@ EndFunction // EntityID - String, Number - ID of kanban owner (group or user) - entityid // AsAdmin - Boolean - Allows you to add stages without checking permissions (for administrators) - admin // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function AddKanbanStage(Val URL @@ -1482,34 +1482,34 @@ Function AddKanbanStage(Val URL , Val EntityID = 0 , Val AsAdmin = False , Val Token = "") Export - + String_ = "String"; - + Parameters = NormalizeAuth(URL, Token, "task.stages.add"); - Fields = New Structure; - + Fields = New Structure; + MakeBoolean(AsAdmin); - - OPI_Tools.AddField("TITLE" , Name , String_, Fields); - OPI_Tools.AddField("COLOR" , Color , String_, Fields); + + OPI_Tools.AddField("TITLE" , Name , String_, Fields); + OPI_Tools.AddField("COLOR" , Color , String_, Fields); OPI_Tools.AddField("AFTER_ID" , PrevStageID , String_, Fields); - OPI_Tools.AddField("ENTITY_ID", EntityID , String_, Fields); - OPI_Tools.AddField("isAdmin" , AsAdmin, String_, Fields); - + OPI_Tools.AddField("ENTITY_ID", EntityID , String_, Fields); + OPI_Tools.AddField("isAdmin" , AsAdmin , String_, Fields); + Parameters.Insert("fields", Fields); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Change kanban stage // Changes the properties of the existing kanban or My plan stage -// +// // Note // Method at API documentation: [task.stages.update](@dev.1c-bitrix.ru/rest_help/tasks/task/kanban/task_stages_update.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Name - String - New stages name - title @@ -1518,7 +1518,7 @@ EndFunction // PrevStageID - String, Number - Stage ID, after which the selected stage should be inserted - prevstage // AsAdmin - Boolean - Allows you to add stages without checking permissions (for administrators) - admin // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function UpdateKanbansStage(Val URL @@ -1528,91 +1528,91 @@ Function UpdateKanbansStage(Val URL , Val PrevStageID = 0 , Val AsAdmin = False , Val Token = "") Export - + String_ = "String"; - + Parameters = NormalizeAuth(URL, Token, "task.stages.update"); - Fields = New Structure; - - OPI_Tools.AddField("TITLE" , Name , String_, Fields); - OPI_Tools.AddField("COLOR" , Color , String_, Fields); - OPI_Tools.AddField("AFTER_ID" , PrevStageID , String_, Fields); - OPI_Tools.AddField("isAdmin" , AsAdmin, "Boolean", Fields); - - OPI_Tools.AddField("id" , StageID, String_ , Parameters); + Fields = New Structure; + + OPI_Tools.AddField("TITLE" , Name , String_ , Fields); + OPI_Tools.AddField("COLOR" , Color , String_ , Fields); + OPI_Tools.AddField("AFTER_ID" , PrevStageID , String_ , Fields); + OPI_Tools.AddField("isAdmin" , AsAdmin , "Boolean", Fields); + + OPI_Tools.AddField("id" , StageID, String_ , Parameters); OPI_Tools.AddField("fields", Fields , "Collection", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // ID of the stage to be deleted // Removes a kanban (My Plan) stage, provided there are no tasks in it -// +// // Note // Method at API documentation: [task.stages.delete](@dev.1c-bitrix.ru/rest_help/tasks/task/kanban/task_stages_delete.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // StageID - String, Number - ID of stage to dele - stage // AsAdmin - Boolean - Allows you to add stages without checking permissions (for administrators) - admin // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeleteKanbanStage(Val URL, Val StageID, Val AsAdmin = False, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "task.stages.delete"); - + MakeBoolean(AsAdmin); - - OPI_Tools.AddField("id" , StageID , "String", Parameters); - OPI_Tools.AddField("isAdmin", AsAdmin, "String", Parameters); - + + OPI_Tools.AddField("id" , StageID , "String", Parameters); + OPI_Tools.AddField("isAdmin", AsAdmin , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get kanban stages // Get kanban (My Plan) stages info -// +// // Note // Method at API documentation: [task.stages.get](@dev.1c-bitrix.ru/rest_help/tasks/task/kanban/task_stages_get.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // EntityID - String, Number - ID of kanban owner (group or user) - entityid // AsAdmin - Boolean - Allows you to get stages without checking permissions (for administrators) - admin // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetKanbanStages(Val URL, Val EntityID = 0, Val AsAdmin = False, Val Token = "") Export - - EntityID = OPI_Tools.NumberToString(EntityID); + + EntityID = OPI_Tools.NumberToString(EntityID); Parameters = NormalizeAuth(URL, Token, "task.stages.get"); - + MakeBoolean(AsAdmin); - + OPI_Tools.AddField("entityId", EntityID , "String", Parameters); - OPI_Tools.AddField("isAdmin" , AsAdmin, "String", Parameters); - + OPI_Tools.AddField("isAdmin" , AsAdmin , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Move task to kanban stage // Move task to another kanban stage -// +// // Note // Method at API documentation: [task.stages.movetask](@dev.1c-bitrix.ru/rest_help/tasks/task/kanban/task_stages_movetask.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - String, Number - ID of task to move - task @@ -1620,7 +1620,7 @@ EndFunction // Prev - String, Number - ID of the task to put the selected one in front of (if After not filled) - before // After - String, Number - ID of the task to be followed by the selected (if Prev not filled) - after // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function MoveTaskToKanbanStage(Val URL @@ -1629,29 +1629,29 @@ Function MoveTaskToKanbanStage(Val URL , Val Prev = 0 , Val After = 0 , Val Token = "") Export - + String_ = "String"; - + Parameters = NormalizeAuth(URL, Token, "task.stages.movetask"); - - OPI_Tools.AddField("id" , TaskID, String_, Parameters); + + OPI_Tools.AddField("id" , TaskID , String_, Parameters); OPI_Tools.AddField("stageId", StageID, String_, Parameters); - + If ValueIsFilled(Prev) Then - + OPI_Tools.AddField("before", Prev, String_, Parameters); - + Else - + OPI_TypeConversion.GetLine(After); OPI_Tools.AddField("after", After, String_, Parameters); - + EndIf; - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction #EndRegion @@ -1660,10 +1660,10 @@ EndFunction // Add task time accounting // Adds information about the user's time spent to the task -// +// // Note // Method at API documentation: [task.elapseditem.add](@dev.1c-bitrix.ru/rest_help/tasks/task/elapseditem/add.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - String, Number - ID of task for time accounting - task @@ -1672,7 +1672,7 @@ EndFunction // Text - String - Comment text - text // SetupDate - String - Date the record was set - date // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function AddTaskTimeAccounting(Val URL @@ -1682,111 +1682,111 @@ Function AddTaskTimeAccounting(Val URL , Val Text = "" , Val SetupDate = "" , Val Token = "") Export - + String_ = "String"; - + Parameters = NormalizeAuth(URL, Token, "task.elapseditem.add"); - Fields = New Structure; - - OPI_Tools.AddField("SECONDS" , Time , String_ , Fields); - OPI_Tools.AddField("COMMENT_TEXT", Text , String_ , Fields); - OPI_Tools.AddField("USER_ID" , UserID, String_ , Fields); + Fields = New Structure; + + OPI_Tools.AddField("SECONDS" , Time , String_ , Fields); + OPI_Tools.AddField("COMMENT_TEXT", Text , String_ , Fields); + OPI_Tools.AddField("USER_ID" , UserID , String_ , Fields); OPI_Tools.AddField("CREATED_DATE", SetupDate , "DateISO", Fields); - - OPI_Tools.AddField("TASKID" , TaskID, String_ , Parameters); + + OPI_Tools.AddField("TASKID" , TaskID , String_ , Parameters); OPI_Tools.AddField("ARFIELDS", Fields , "Collection", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Delete task time accounting // Deletes record of time accounting -// +// // Note // Method at API documentation: [task.elapseditem.delete](@dev.1c-bitrix.ru/rest_help/tasks/task/elapseditem/delete.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - String, Number - ID of task for time accounting - task // RecordID - String, Number - Time record ID - record // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeleteTaskTimeAccounting(Val URL, Val TaskID, Val RecordID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "task.elapseditem.delete"); - - OPI_Tools.AddField("TASKID", TaskID, "String", Parameters); + + OPI_Tools.AddField("TASKID", TaskID , "String", Parameters); OPI_Tools.AddField("ITEMID", RecordID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get task time accounting list // Get list of time accounting records for task -// +// // Note // Method at API documentation: [task.elapseditem.getlist](@dev.1c-bitrix.ru/rest_help/tasks/task/elapseditem/getlist.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - String, Number - Task ID - task // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetTaskTimeAccountingList(Val URL, Val TaskID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "task.elapseditem.getlist"); - + OPI_Tools.AddField("TASKID", TaskID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get task time accounting // Get time accounting record data -// +// // Note // Method at API documentation: [task.elapseditem.get](@dev.1c-bitrix.ru/rest_help/tasks/task/elapseditem/get.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - String, Number - Task ID - task // RecordID - String, Number - Time record ID - record // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetTaskTimeAccounting(Val URL, Val TaskID, Val RecordID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "task.elapseditem.get"); - - OPI_Tools.AddField("TASKID", TaskID, "String", Parameters); + + OPI_Tools.AddField("TASKID", TaskID , "String", Parameters); OPI_Tools.AddField("ITEMID", RecordID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Update task time accounting // Update time accounting record data -// +// // Note // Method at API documentation: [task.elapseditem.update](@dev.1c-bitrix.ru/rest_help/tasks/task/elapseditem/update.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // TaskID - String, Number - Task ID - task @@ -1795,7 +1795,7 @@ EndFunction // Text - String - Comment text - text // SetupDate - String - Date the record was set - date // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function UpdateTaskTimeAccounting(Val URL @@ -1805,24 +1805,24 @@ Function UpdateTaskTimeAccounting(Val URL , Val Text = "" , Val SetupDate = "" , Val Token = "") Export - + String_ = "String"; - + Parameters = NormalizeAuth(URL, Token, "task.elapseditem.update"); - Fields = New Structure; - - OPI_Tools.AddField("SECONDS" , Time , String_ , Fields); - OPI_Tools.AddField("COMMENT_TEXT", Text , String_ , Fields); + Fields = New Structure; + + OPI_Tools.AddField("SECONDS" , Time , String_ , Fields); + OPI_Tools.AddField("COMMENT_TEXT", Text , String_ , Fields); OPI_Tools.AddField("CREATED_DATE", SetupDate , "DateISO", Fields); - - OPI_Tools.AddField("TASKID" , TaskID, String_ , Parameters); - OPI_Tools.AddField("ITEMID" , RecordID, String_ , Parameters); - OPI_Tools.AddField("ARFIELDS", Fields , "Collection", Parameters); - + + OPI_Tools.AddField("TASKID" , TaskID , String_ , Parameters); + OPI_Tools.AddField("ITEMID" , RecordID, String_ , Parameters); + OPI_Tools.AddField("ARFIELDS", Fields , "Collection", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction #EndRegion @@ -1831,142 +1831,142 @@ EndFunction // Get list of storages // Get list of available files storages -// +// // Note // Method at API documentation: [disk.storage.getlist](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_getlist.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetStoragesList(Val URL, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "disk.storage.getlist"); - Response = OPI_Tools.Post(URL, Parameters); - + Response = OPI_Tools.Post(URL, Parameters); + Return Response; EndFunction // Get storage for application data // Get information about storage with which the application can work to store its data -// +// // Note // Method at API documentation: [disk.storage.getforapp](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_getforapp.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetAppSotrage(Val URL, Val Token = "") Export - - Parameters = NormalizeAuth(URL, Token, "disk.storage.getforapp"); + + Parameters = NormalizeAuth(URL, Token, "disk.storage.getforapp"); Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get storage // Get information about storage -// +// // Note // Method at API documentation: [disk.storage.get](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_get.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // StorageID - String, Number - Storage ID - storageid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetStorage(Val URL, Val StorageID, Val Token = "") Export - + Response = FileManagement(URL, StorageID, "disk.storage.get", Token); Return Response; - + EndFunction // Rename storage // Change storage name (for app storage only, see. GetAppStorage) -// +// // Note // Method at API documentation: [disk.storage.rename](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_rename.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // StorageID - String, Number - Storage ID - storageid // Name - String - New storage name - title // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function RenameStorage(Val URL, Val StorageID, Val Name, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "disk.storage.rename"); - - OPI_Tools.AddField("id" , StorageID , "String", Parameters); - OPI_Tools.AddField("newName", Name, "String", Parameters); - + + OPI_Tools.AddField("id" , StorageID , "String", Parameters); + OPI_Tools.AddField("newName", Name , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get a list of child storage objects // Get a list of files and folders, located at the root of the storage -// +// // Note // Method at API documentation: [disk.storage.getchildren](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_getchildren.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // StorageID - String, Number - Storage ID - storageid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetStorageObjects(Val URL, Val StorageID, Val Token = "") Export - + Response = FileManagement(URL, StorageID, "disk.storage.getchildren", Token); Return Response; - + EndFunction // Create folder at the storage // Create new foldera at the storage -// +// // Note // Method at API documentation: [disk.storage.addfolder](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_addfolder.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // StorageID - String - Storage ID - storageid // Name - String - Folder name - title // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function CreateStorageFolder(Val URL, Val StorageID, Val Name, Val Token = "") Export - + OPI_TypeConversion.GetLine(Name); - + FolderStructure = New Structure("NAME", Name); - + Parameters = NormalizeAuth(URL, Token, "disk.storage.addfolder"); - - OPI_Tools.AddField("id" , StorageID , "String" , Parameters); + + OPI_Tools.AddField("id" , StorageID , "String" , Parameters); OPI_Tools.AddField("data", FolderStructure, "Collection", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - - Return Response; - + + Return Response; + EndFunction #EndRegion @@ -1975,279 +1975,279 @@ EndFunction // Get information about folder // Get folder information -// +// // Note // Method at API documentation: [disk.folder.get](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_get.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FolderID - String, Number - Folder identifier - folderid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetFolderInformation(Val URL, Val FolderID, Val Token = "") Export - + Response = FileManagement(URL, FolderID, "disk.folder.get", Token); Return Response; - + EndFunction // Create new subfolder // Create new folder inside another folder -// +// // Note // Method at API documentation: [disk.folder.addsubfolder](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_addsubfolder.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FolderID - String, Number - Parent folder identifier - folderid // Name - String - Name of new folder - title // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function CreateSubfolder(Val URL, Val FolderID, Val Name, Val Token = "") Export - + OPI_TypeConversion.GetLine(Name); - + FolderStructure = New Structure("NAME", Name); - + Parameters = NormalizeAuth(URL, Token, "disk.folder.addsubfolder"); - - OPI_Tools.AddField("id" , FolderID , "String" , Parameters); + + OPI_Tools.AddField("id" , FolderID , "String" , Parameters); OPI_Tools.AddField("data", FolderStructure, "Collection", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - - Return Response; - + + Return Response; + EndFunction // Copy folder // Copy one folder to another -// +// // Note // Method at API documentation: [disk.folder.copyto](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_copyto.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FolderID - String, Number - Folder identifier - folderid // DestinationID - String, Number - ID of target folder - tagetid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function MakeFolderCopy(Val URL, Val FolderID, Val DestinationID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "disk.folder.copyto"); - - OPI_Tools.AddField("id" , FolderID , "String", Parameters); + + OPI_Tools.AddField("id" , FolderID , "String", Parameters); OPI_Tools.AddField("targetFolderId", DestinationID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - - Return Response; - + + Return Response; + EndFunction // Move folder // Moves one folder inside another -// +// // Note // Method at API documentation: [disk.folder.moveto](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_moveto.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FolderID - String, Number - Folder identifier - folderid // DestinationID - String, Number - ID of target folder - tagetid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function MoveFolder(Val URL, Val FolderID, Val DestinationID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "disk.folder.moveto"); - - OPI_Tools.AddField("id" , FolderID , "String", Parameters); + + OPI_Tools.AddField("id" , FolderID , "String", Parameters); OPI_Tools.AddField("targetFolderId", DestinationID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - - Return Response; - + + Return Response; + EndFunction // Delete folder // Remove folder with subfolders -// +// // Note // Method at API documentation: [disk.folder.deletetree](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_deletetree.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FolderID - String, Number - ID of folder to be deleted - folderid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeleteFolder(Val URL, Val FolderID, Val Token = "") Export - + Response = FileManagement(URL, FolderID, "disk.folder.deletetree", Token); Return Response; - + EndFunction // Get external link for folder // Get external link to folder -// +// // Note // Method at API documentation: [disk.folder.getExternalLink](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_getexternallink.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FolderID - String, Number - Folder identifier - folderid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetFolderExternalLink(Val URL, Val FolderID, Val Token = "") Export - + Response = FileManagement(URL, FolderID, "disk.folder.getExternalLink", Token); Return Response; - + EndFunction // Get folder child elements // Get folder child elements -// +// // Note // Method at API documentation: [disk.folder.getchildren](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_getchildren.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FolderID - String, Number - Folder identifier - folderid // Filter - Structure of KeyAndValue - Items filter (see GetFolderFilterStructure) - filter // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetFolderItems(Val URL, Val FolderID, Val Filter = "", Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "disk.folder.getchildren"); - OPI_Tools.AddField("id" , FolderID, "String" , Parameters); - OPI_Tools.AddField("filter", Filter , "Collection", Parameters); - + OPI_Tools.AddField("id" , FolderID, "String" , Parameters); + OPI_Tools.AddField("filter", Filter , "Collection", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Mark folder as deleted // Move folder to recycle bin -// +// // Note // Method at API documentation: [disk.folder.markdeleted](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_markdeleted.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FolderID - String, Number - Folder identifier - folderid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function MarkFolderAsDeleted(Val URL, Val FolderID, Val Token = "") Export - + Response = FileManagement(URL, FolderID, "disk.folder.markdeleted", Token); Return Response; - + EndFunction // Restore folder // Resotre folder form recycle bin -// +// // Note // Method at API documentation: [disk.folder.restore](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_restore.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FolderID - String, Number - Folder identifier - folderid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function RestoreFolder(Val URL, Val FolderID, Val Token = "") Export - + Response = FileManagement(URL, FolderID, "disk.folder.restore", Token); - Return Response; - + Return Response; + EndFunction // Rename folder // Change folder name -// +// // Note // Method at API documentation: [disk.folder.rename](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_rename.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FolderID - String, Number - Folder identifier - folderid // Name - String - New folders name - title // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function RenameFolder(Val URL, Val FolderID, Val Name, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "disk.folder.rename"); - - OPI_Tools.AddField("id" , FolderID , "String", Parameters); - OPI_Tools.AddField("newName", Name, "String", Parameters); - + + OPI_Tools.AddField("id" , FolderID , "String", Parameters); + OPI_Tools.AddField("newName", Name , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - - Return Response; - + + Return Response; + EndFunction // Get fields structure for folder items filter // Returns filter structure for child folder items -// +// // Note // Method at API documentation: [disk.folder.getfields](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_getfields.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Clear - Boolean - True > structure with empty values, False > field types at values - empty // Token - String - Access token, when app auth method used - token -// +// // Returns: -// Structure of KeyAndValue - Fields structure +// Structure of KeyAndValue - Fields structure Function GetFolderFilterStructure(Val URL, Val Clear = False, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "disk.folder.getfields"); - Filter = New Structure; - + Filter = New Structure; + Response = OPI_Tools.Post(URL, Parameters); - Fields = Response["result"]; - + Fields = Response["result"]; + For Each Field In Fields Do - - Name = Field.Key; + + Name = Field.Key; Description = Field.Value; - + If Description["USE_IN_FILTER"] Then - - DataType = ?(Clear, "", Description["TYPE"]); + + DataType = ?(Clear, "", Description["TYPE"]); Filter.Insert(Name, DataType); - + EndIf; - + EndDo; - + Return Filter; - + EndFunction #EndRegion @@ -2256,18 +2256,18 @@ EndFunction // Upload file to a storage // Upload file to storage root -// +// // Note // Method at API documentation: [disk.storage.uploadfile](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_uploadfile.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Name - String - File name with extension - title -// File - String, BinaryData - File for upload - file +// File - String, BinaryData - File for upload - file // StorageID - String - Storage id - storageid // Rights - String - Rights array if required - rights // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function UploadFileToStorage(Val URL @@ -2276,118 +2276,118 @@ Function UploadFileToStorage(Val URL , Val StorageID , Val Rights = "" , Val Token = "") Export - + OPI_TypeConversion.GetLine(StorageID); OPI_TypeConversion.GetLine(Name); - + Method = "disk.storage.uploadfile"; - FileData = New Structure("NAME", Name); + FileData = New Structure("NAME", Name); FileContent = New Map(); FileContent.Insert(Name, File); - + Parameters = NormalizeAuth(URL, Token, Method); - OPI_Tools.AddField("data" , FileData, "Collection", Parameters); - OPI_Tools.AddField("rights", Rights , "Array" , Parameters); - OPI_Tools.AddField("id" , StorageID, "String" , Parameters); + OPI_Tools.AddField("data" , FileData , "Collection", Parameters); + OPI_Tools.AddField("rights", Rights , "Array" , Parameters); + OPI_Tools.AddField("id" , StorageID, "String" , Parameters); FileArray = NormalizeFiles(FileContent); - + If Not FileArray.Count() = 0 Then Parameters.Insert("fileContent", FileArray[0]); EndIf; - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Upload file to the folder // Upload local file to the folder -// +// // Note // Method at API documentation: [disk.folder.uploadfile](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_uploadfile.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Name - String - File name with extension - title -// File - String, BinaryData - File for upload - file +// File - String, BinaryData - File for upload - file // FolderID - String - Folder identifier - folderid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function UploadFileToFolder(Val URL, Val Name, Val File, Val FolderID, Val Token = "") Export OPI_TypeConversion.GetLine(Name); OPI_TypeConversion.GetBinaryData(File); - + Parameters = NormalizeAuth(URL, Token, "disk.folder.uploadFile"); OPI_Tools.AddField("id", FolderID, "String", Parameters); - + Response = OPI_Tools.Get(URL, Parameters); - Result = Response["result"]; - + Result = Response["result"]; + If ValueIsFilled(Result) Then - + FieldName = Result["field"]; UploadURL = Result["uploadUrl"]; - + If ValueIsFilled(FieldName) And ValueIsFilled(UploadURL) Then - + FieldName = TrimAll(FieldName); UploadURL = TrimAll(UploadURL); - FileName = FieldName + "|" + Name; - + FileName = FieldName + "|" + Name; + FileMapping = New Map; - FileMapping.Insert(FileName, File); - - Response = OPI_Tools.PostMultipart(UploadURL, , FileMapping, ""); - + FileMapping.Insert(FileName, File); + + Response = OPI_Tools.PostMultipart(UploadURL, , FileMapping, ""); + EndIf; - - EndIf; - - Return Response; - + + EndIf; + + Return Response; + EndFunction // Get information about file // Get information about file by ID -// +// // Note // Method at API documentation: [disk.file.get](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_get.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FileID - String, Number - File identifier - fileid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetFileInformation(Val URL, Val FileID, Val Token = "") Export - + Response = FileManagement(URL, FileID, "disk.file.get", Token); Return Response; - + EndFunction // Delete file // Delete file by ID -// +// // Note // Method at API documentation: [disk.file.delete](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_delete.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FileID - String, Number - ID of removing file - fileid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeleteFile(Val URL, Val FileID, Val Token = "") Export - + Response = FileManagement(URL, FileID, "disk.file.delete", Token); Return Response; @@ -2395,143 +2395,143 @@ EndFunction // Get external link for a file // Get external link to file -// +// // Note // Method at API documentation: [disk.file.getExternalLink](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_getexternallink.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FileID - String, Number - File identifier - fileid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetFileExternalLink(Val URL, Val FileID, Val Token = "") Export - + Response = FileManagement(URL, FileID, "disk.file.getExternalLink", Token); Return Response; - + EndFunction // Mark file as deleted // Move file to recycle bin -// +// // Note // Method at API documentation: [disk.file.markdeleted](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_markdeleted.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FileID - String, Number - File identifier - fileid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function MarkFileAsDeleted(Val URL, Val FileID, Val Token = "") Export - + Response = FileManagement(URL, FileID, "disk.file.markdeleted", Token); Return Response; - + EndFunction // Restore file // Restore file from recycle bin -// +// // Note // Method at API documentation: [disk.file.restore](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_restore.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FileID - String, Number - File identifier - fileid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function RestoreFile(Val URL, Val FileID, Val Token = "") Export - + Response = FileManagement(URL, FileID, "disk.file.restore", Token); Return Response; - + EndFunction // Copy file // Copy file from one destination to another -// +// // Note // Method at API documentation: [disk.file.copyto](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_copyto.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FileID - String, Number - Original file ID - fileid -// FolderID - String, Number - ID of copy destination folder - folderid +// FolderID - String, Number - ID of copy destination folder - folderid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function MakeFileCopy(Val URL, Val FileID, Val FolderID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "disk.file.copyto"); - - OPI_Tools.AddField("id" , FileID , "String", Parameters); + + OPI_Tools.AddField("id" , FileID , "String", Parameters); OPI_Tools.AddField("targetFolderId", FolderID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - - Return Response; - + + Return Response; + EndFunction // Move file // Move file from one destination to another -// +// // Note // Method at API documentation: [disk.file.moveto](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_moveto.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FileID - String, Number - File ID - fileid -// FolderID - String, Number - ID of new destination folder - folderid +// FolderID - String, Number - ID of new destination folder - folderid // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function MoveFileToFolder(Val URL, Val FileID, Val FolderID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "disk.file.moveto"); - - OPI_Tools.AddField("id" , FileID , "String", Parameters); + + OPI_Tools.AddField("id" , FileID , "String", Parameters); OPI_Tools.AddField("targetFolderId", FolderID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - - Return Response; - + + Return Response; + EndFunction // Rename file // Changes the name of an existing file -// +// // Note // Method at API documentation: [disk.file.rename](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_rename.php) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // FileID - String, Number - File identifier - fileid // Name - String - New folders name - title // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function RenameFile(Val URL, Val FileID, Val Name, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "disk.file.rename"); - - OPI_Tools.AddField("id" , FileID , "String", Parameters); - OPI_Tools.AddField("newName", Name, "String", Parameters); - + + OPI_Tools.AddField("id" , FileID , "String", Parameters); + OPI_Tools.AddField("newName", Name , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - - Return Response; - + + Return Response; + EndFunction #EndRegion @@ -2540,109 +2540,109 @@ EndFunction // Create chat // Creates a new chat based on the field structure -// +// // Note // Method at API documentation: [im.chat.add](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12093) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url -// ChatStructure - Structure of KeyAndValue - Chat fields structure. See GetChatStructure - fields +// ChatStructure - Structure of KeyAndValue - Chat fields structure. See GetChatStructure - fields // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function CreateChat(Val URL, Val ChatStructure, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.chat.add"); - + For Each Element In ChatStructure Do Parameters.Insert(Element.Key, Element.Value); EndDo; - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get chats users // Gets the list of chat users by ID -// +// // Note // Method at API documentation: [im.chat.user.list](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12095) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID - chat // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetChatUsers(Val URL, Val ChatID, Val Token = "") Export - - Response = ChatManagment(URL, ChatID, "im.chat.user.list", Token); + + Response = ChatManagment(URL, ChatID, "im.chat.user.list", Token); Return Response; - + EndFunction // Leave chat // Removes the current user from the chat room -// +// // Note // Method at API documentation: [im.chat.leave](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12101) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID - chat // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function LeaveChat(Val URL, Val ChatID, Val Token = "") Export - - Response = ChatManagment(URL, ChatID, "im.chat.leave", Token); + + Response = ChatManagment(URL, ChatID, "im.chat.leave", Token); Return Response; - + EndFunction // Get users // Get users information for dialog -// +// // Note // Method at API documentation: [im.user.list.get ](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=11493) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // UserIDs - Array of String, Number - Usesr ID or array of users IDs - users // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetUsers(Val URL, Val UserIDs, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.user.list.get"); - + OPI_Tools.AddField("ID", UserIDs, "Array", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Add users to chat // Adds users to the chat by ID array -// +// // Note // Method at API documentation: [im.chat.user.add](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12097) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID - chat // UserIDs - Array of string, number - New members IDs - users // HideHistory - Boolean - Hide old messages from new members - hide // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function AddUsersToChat(Val URL @@ -2650,213 +2650,213 @@ Function AddUsersToChat(Val URL , Val UserIDs , Val HideHistory = False , Val Token = "") Export - + MakeBoolean(HideHistory); - + Parameters = NormalizeAuth(URL, Token, "im.chat.user.add"); - - OPI_Tools.AddField("CHAT_ID" , ChatID , "String" , Parameters); - OPI_Tools.AddField("USERS" , UserIDs, "Collection", Parameters); - OPI_Tools.AddField("HIDE_HISTORY", HideHistory , "String" , Parameters); - + + OPI_Tools.AddField("CHAT_ID" , ChatID , "String" , Parameters); + OPI_Tools.AddField("USERS" , UserIDs , "Collection", Parameters); + OPI_Tools.AddField("HIDE_HISTORY", HideHistory , "String" , Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Delete user from chat // Deletes user from chat -// +// // Note // Method at API documentation: [im.chat.user.delete](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12099) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID - chat // UserID - String, Number - User ID - user // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeleteUserFromChat(Val URL, Val ChatID, Val UserID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.chat.user.delete"); - + OPI_Tools.AddField("CHAT_ID", ChatID , "String", Parameters); - OPI_Tools.AddField("USER_ID", UserID, "String", Parameters); - + OPI_Tools.AddField("USER_ID", UserID , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Change chat title // Change text of chat title -// +// // Note // Method at API documentation: [im.chat.updateTitle](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12105) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID - chat // Title - String - New title - title // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function ChangeChatTitle(Val URL, Val ChatID, Val Title, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.chat.updateTitle"); - + OPI_Tools.AddField("CHAT_ID", ChatID , "String", Parameters); - OPI_Tools.AddField("TITLE" , Title, "String", Parameters); - + OPI_Tools.AddField("TITLE" , Title , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Change chat color // Chat chat color for mobile app -// +// // Note // Method at API documentation: [im.chat.updateTitle](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12105) // Available colors: RED, GREEN, MINT, LIGHT_BLUE, DARK_BLUE, PURPLE, AQUA, PINK, LIME, BROWN, AZURE, KHAKI, SAND, MARENGO, GRAY, GRAPHITE -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID - chat // Color - String - New chat color - color // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function ChangeChatColor(Val URL, Val ChatID, Val Color, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.chat.updateColor"); - + OPI_Tools.AddField("CHAT_ID", ChatID, "String", Parameters); - OPI_Tools.AddField("COLOR" , Color , "String", Parameters); - + OPI_Tools.AddField("COLOR" , Color , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Change chat picture // Setup new chat picture -// +// // Note // Method at API documentation: [im.chat.updateAvatar](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12109) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID - chat // Image - String, BinaryData - Picture data - picture // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function ChangeChatPicture(Val URL, Val ChatID, Val Image, Val Token = "") Export - + OPI_TypeConversion.GetBinaryData(Image); - - Image = Base64String(Image); + + Image = Base64String(Image); Parameters = NormalizeAuth(URL, Token, "im.chat.updateAvatar"); - + OPI_Tools.AddField("CHAT_ID", ChatID , "String", Parameters); - OPI_Tools.AddField("AVATAR" , Image, "String", Parameters); - + OPI_Tools.AddField("AVATAR" , Image , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Change chat owner // Change chat owner -// +// // Note // Method at API documentation: [im.chat.setOwner](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12111) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID - chat // UserID - String, Number - User ID - user // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function ChangeChatOwner(Val URL, Val ChatID, Val UserID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.chat.setOwner"); - + OPI_Tools.AddField("CHAT_ID", ChatID , "String", Parameters); - OPI_Tools.AddField("USER_ID", UserID, "String", Parameters); - + OPI_Tools.AddField("USER_ID", UserID , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Disable chat notifications // Disable chat notifications -// +// // Note // Method at API documentation: [im.chat.mute](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=11473) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID - chat // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DisableChatNotifications(Val URL, Val ChatID, Val Token = "") Export - + Response = ChatNotificationsSwitch(URL, ChatID, True, Token); Return Response; - + EndFunction // Enable chat notifications // Enable chat notifications -// +// // Note // Method at API documentation: [im.chat.mute](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=11473) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID - chat // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function EnableChatNotifications(Val URL, Val ChatID, Val Token = "") Export - + Response = ChatNotificationsSwitch(URL, ChatID, False, Token); Return Response; - + EndFunction // Get chat messages list // Gets a list of 20 chat or dialog messages, depending on the FirstID and LastID specified -// +// // Note // Method at API documentation: [im.dialog.messages.get](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=11479) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID (as chatXXX) or User ID (as XXX) - chat // LastID - String, Number - Id of last message - last // FirstID - String, Number - ID of first message - first // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetChatMessagesList(Val URL @@ -2864,209 +2864,209 @@ Function GetChatMessagesList(Val URL , Val LastID = "" , Val FirstID = "" , Val Token = "") Export - + String_ = "String"; - + OPI_TypeConversion.GetLine(LastID); OPI_TypeConversion.GetLine(FirstID); - + Parameters = NormalizeAuth(URL, Token, "im.dialog.messages.get"); - - OPI_Tools.AddField("DIALOG_ID", ChatID , String_, Parameters); - OPI_Tools.AddField("LAST_ID" , LastID, String_, Parameters); + + OPI_Tools.AddField("DIALOG_ID", ChatID , String_, Parameters); + OPI_Tools.AddField("LAST_ID" , LastID , String_, Parameters); OPI_Tools.AddField("FIRST_ID" , FirstID , String_, Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get dialog // Get chat data by ID -// +// // Note // Method at API documentation: [im.dialog.get](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12886) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID (as chatXXX) or User ID (as XXX) - chat // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetDialog(Val URL, Val ChatID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.dialog.get"); - + OPI_Tools.AddField("DIALOG_ID", ChatID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get chat members list // Get chat members list -// +// // Note // Method at API documentation: [im.dialog.users.list](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=23800) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID (as chatXXX) or User ID (as XXX) - chat // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetChatMembersList(Val URL, Val ChatID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.dialog.users.list"); - + OPI_Tools.AddField("DIALOG_ID", ChatID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Send write notification // Send Writing... status to dialog... -// +// // Note // Method at API documentation: [im.dialog.writing](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=23802) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID (as chatXXX) or User ID (as XXX) - chat // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function SendWritingNotification(Val URL, Val ChatID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.dialog.writing"); - + OPI_Tools.AddField("DIALOG_ID", ChatID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Get user status // Gets the status (online) of the current user -// +// // Note // Method at API documentation: [im.user.status.get](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=11497) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetUserStatus(Val URL, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.user.status.get"); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Set user status // Sets the status (online) of the current user -// +// // Note // Method at API documentation: [im.user.status.set](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=11499) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Status - String, Number - Status value: online, dnd, away - status // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function SetUserStatus(Val URL, Val Status, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.user.status.set"); - + OPI_Tools.AddField("STATUS", Status, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Read all // Mark all message as readed -// +// // Note // Method at API documentation: [im.dialog.read.all](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=23804) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function ReadAll(Val URL, Val Token = "") Export - - Parameters = NormalizeAuth(URL, Token, "im.dialog.read.all"); - Response = OPI_Tools.Post(URL, Parameters); - + + Parameters = NormalizeAuth(URL, Token, "im.dialog.read.all"); + Response = OPI_Tools.Post(URL, Parameters); + Return Response; - + EndFunction // Get chat files folder // Get information about folder for chat files -// +// // Note // Method at API documentation: [im.disk.folder.get](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=11483) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID - chat // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function GetChatFilesFolder(Val URL, Val ChatID, Val Token = "") Export - - Response = ChatManagment(URL, ChatID, "im.disk.folder.get", Token); + + Response = ChatManagment(URL, ChatID, "im.disk.folder.get", Token); Return Response; - + EndFunction // Get chats structure // Get chat fields structure -// +// // Parameters: // Clear - Boolean - True > structure with empty values, False > field types at values - empty -// +// // Returns: -// Structure of KeyAndValue - Fields structure +// Structure of KeyAndValue - Fields structure Function GetChatStructure(Val Clear = False) Export - + OPI_TypeConversion.GetBoolean(Clear); - + ChatStructure = New Structure; - ChatStructure.Insert("TYPE" , ""); - ChatStructure.Insert("TITLE" , ""); + ChatStructure.Insert("TYPE" , ""); + ChatStructure.Insert("TITLE" , ""); ChatStructure.Insert("DESCRIPTION", ""); - ChatStructure.Insert("COLOR" , ""); - ChatStructure.Insert("MESSAGE" , ""); - ChatStructure.Insert("USERS" , ""); - ChatStructure.Insert("AVATAR" , ""); - ChatStructure.Insert("OWNER_ID" , ""); - + ChatStructure.Insert("COLOR" , ""); + ChatStructure.Insert("MESSAGE" , ""); + ChatStructure.Insert("USERS" , ""); + ChatStructure.Insert("AVATAR" , ""); + ChatStructure.Insert("OWNER_ID" , ""); + If Clear Then For Each Element In ChatStructure Do Element.Value = ""; @@ -3075,7 +3075,7 @@ Function GetChatStructure(Val Clear = False) Export //@skip-check constructor-function-return-section Return ChatStructure; - + EndFunction #EndRegion @@ -3084,253 +3084,253 @@ EndFunction // Send message // Send message to dialog -// +// // Note // Method at API documentation: [im.message.add](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12115) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID (as chatXXX) or User ID (as XXX) - chat // Text - String - Message text - text // Attachments - Array of Structure - Array of attachments - blocks // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function SendMessage(Val URL, Val ChatID, Val Text, Val Attachments = "", Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.message.add"); - - OPI_Tools.AddField("DIALOG_ID", ChatID , "String", Parameters); - OPI_Tools.AddField("MESSAGE" , Text , "String", Parameters); - OPI_Tools.AddField("ATTACH" , Attachments, "Array", Parameters); - + + OPI_Tools.AddField("DIALOG_ID", ChatID , "String", Parameters); + OPI_Tools.AddField("MESSAGE" , Text , "String", Parameters); + OPI_Tools.AddField("ATTACH" , Attachments, "Array" , Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Edit message // Edit dialog message content -// +// // Note // Method at API documentation: [im.message.update](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12117) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // MessageID - String, Number - ID of the message to be edited - message // Text - String - New message text - text // Attachments - Array of Structure - New blocks array - blocks // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function EditMessage(Val URL, Val MessageID, Val Text = "", Val Attachments = "", Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.message.update"); - - OPI_Tools.AddField("MESSAGE_ID", MessageID, "String", Parameters); - OPI_Tools.AddField("MESSAGE" , Text , "String", Parameters); - OPI_Tools.AddField("ATTACH" , Attachments , "Array", Parameters); - + + OPI_Tools.AddField("MESSAGE_ID", MessageID , "String", Parameters); + OPI_Tools.AddField("MESSAGE" , Text , "String", Parameters); + OPI_Tools.AddField("ATTACH" , Attachments , "Array" , Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Set message reaction // Set or remove reaction mark on the message -// +// // Note // Method at API documentation: [im.message.like](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12121) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // MessageID - String, Number - Message ID - message // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function SetMessageReaction(Val URL, Val MessageID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.message.like"); - + OPI_Tools.AddField("MESSAGE_ID", MessageID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Delete message // Deletes a dialog message -// +// // Note // Method at API documentation: [im.message.delete](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12119) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // MessageID - String, Number - ID of the message to be deleted - message // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeleteMessage(Val URL, Val MessageID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.message.delete"); - + OPI_Tools.AddField("MESSAGE_ID", MessageID , "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // SendFile // Send disk file to chat -// +// // Note // Method at API documentation: [im.disk.file.commit](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=11485) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID - chat // FileID - String, Number - File ID from UploadFileToFolder method - fileid // Description - String - File description - description // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function SendFile(Val URL, Val ChatID, Val FileID, Val Description = "", Val Token = "") Export - + String_ = "String"; - + Parameters = NormalizeAuth(URL, Token, "im.disk.file.commit"); - - OPI_Tools.AddField("CHAT_ID" , ChatID , String_, Parameters); - OPI_Tools.AddField("UPLOAD_ID", FileID , String_, Parameters); - OPI_Tools.AddField("MESSAGE" , Description, String_, Parameters); - + + OPI_Tools.AddField("CHAT_ID" , ChatID , String_, Parameters); + OPI_Tools.AddField("UPLOAD_ID", FileID , String_, Parameters); + OPI_Tools.AddField("MESSAGE" , Description, String_, Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Mark message as readed // Mark current and all previous messages as readed -// +// // Note // Method at API documentation: [im.dialog.read](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12053) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID (as chatXXX) or User ID (as XXX) - chat // MessageID - String, Number - Id of last readed message - message // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function MarkMessageAsReaded(Val URL, Val ChatID, Val MessageID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.dialog.read"); - - OPI_Tools.AddField("DIALOG_ID" , ChatID , "String", Parameters); + + OPI_Tools.AddField("DIALOG_ID" , ChatID , "String", Parameters); OPI_Tools.AddField("MESSAGE_ID", MessageID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Mark message as unreaded // Mark current and all messages after as unreaded -// +// // Note // Method at API documentation: [im.dialog.unread](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12055) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // ChatID - String, Number - Chat ID (as chatXXX) or User ID (as XXX) - chat // MessageID - String, Number - ID of last unreaded message - message // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function MarkMessageAsUnreaded(Val URL, Val ChatID, Val MessageID, Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.dialog.unread"); - - OPI_Tools.AddField("DIALOG_ID" , ChatID , "String", Parameters); + + OPI_Tools.AddField("DIALOG_ID" , ChatID , "String", Parameters); OPI_Tools.AddField("MESSAGE_ID", MessageID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction - + // Get picture block // Make picture block for SendMessage method -// +// // Note // Blocks at API documentation: [Link](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&CHAPTER_ID=07867) -// +// // Parameters: // Name - String - Picture name - title // URL - String - URL of sending picture - url -// +// // Returns: // Structure - PictureBlock Function GetPictureBlock(Val Name, Val URL) Export - PictureStructure = New Structure; + PictureStructure = New Structure; OPI_Tools.AddField("NAME", Name, "String", PictureStructure); OPI_Tools.AddField("LINK", URL , "String", PictureStructure); - + //@skip-check constructor-function-return-section Return New Structure("IMAGE", PictureStructure); - + EndFunction // Get file block // Make file block for SendMessage method -// +// // Note // Blocks at API documentation: [Link](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&CHAPTER_ID=07867) -// +// // Parameters: // Name - String - Picture name - title // URL - String - File URL - url -// +// // Returns: // Structure - FileBlock Function GetFileBlock(Val Name, Val URL) Export - PictureStructure = New Structure; + PictureStructure = New Structure; OPI_Tools.AddField("NAME", Name, "String", PictureStructure); OPI_Tools.AddField("LINK", URL , "String", PictureStructure); - + //@skip-check constructor-function-return-section Return New Structure("FILE", PictureStructure); - + EndFunction - + #EndRegion #Region NotificationsManagment // Create personal notification // Creates a personal notification to the user -// +// // Note // Method at API documentation: [im.notify.personal.add](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=12129) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // UserID - String, Number - User ID for sending the notification - user @@ -3338,7 +3338,7 @@ EndFunction // Tag - String - Uniqueness Tag. Id already exist - another notif. will be deleted - tag // Attachments - Array of Structure - Array of attachments - blocks // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function CreatePersonalNotification(Val URL @@ -3347,26 +3347,26 @@ Function CreatePersonalNotification(Val URL , Val Tag , Val Attachments = "" , Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.notify.personal.add"); - - OPI_Tools.AddField("USER_ID", UserID, "String", Parameters); - OPI_Tools.AddField("MESSAGE", Text , "String", Parameters); - OPI_Tools.AddField("TAG" , Tag , "String", Parameters); - OPI_Tools.AddField("ATTACH" , Attachments , "Array", Parameters); - + + OPI_Tools.AddField("USER_ID", UserID , "String", Parameters); + OPI_Tools.AddField("MESSAGE", Text , "String", Parameters); + OPI_Tools.AddField("TAG" , Tag , "String", Parameters); + OPI_Tools.AddField("ATTACH" , Attachments , "Array" , Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Create system notification // Creates a system notification to the user -// +// // Note // Method at API documentation: [im.notify.system.add](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=12131) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // UserID - String, Number - User ID for sending the notification - user @@ -3374,7 +3374,7 @@ EndFunction // Tag - String - Uniqueness Tag. Id already exist - another notif. will be deleted - tag // Attachments - Array of Structure - Array of attachments - blocks // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function CreateSystemNotification(Val URL @@ -3383,43 +3383,43 @@ Function CreateSystemNotification(Val URL , Val Tag , Val Attachments = "" , Val Token = "") Export - + Parameters = NormalizeAuth(URL, Token, "im.notify.system.add"); - - OPI_Tools.AddField("USER_ID", UserID, "String", Parameters); - OPI_Tools.AddField("MESSAGE", Text , "String", Parameters); - OPI_Tools.AddField("TAG" , Tag , "String", Parameters); - OPI_Tools.AddField("ATTACH" , Attachments , "Array", Parameters); - + + OPI_Tools.AddField("USER_ID", UserID , "String", Parameters); + OPI_Tools.AddField("MESSAGE", Text , "String", Parameters); + OPI_Tools.AddField("TAG" , Tag , "String", Parameters); + OPI_Tools.AddField("ATTACH" , Attachments , "Array" , Parameters); + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction // Delete notification // Delete notification by ID -// +// // Note // Method at API documentation: [im.notify.delete](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=12133) -// +// // Parameters: // URL - String - URL of webhook or a Bitrix24 domain, when token used - url // NotificationID - String, Number - Notification ID - notif // Token - String - Access token, when app auth method used - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON of answer from Bitrix24 API Function DeleteNotification(Val URL, Val NotificationID, Val Token = "") Export Parameters = NormalizeAuth(URL, Token, "im.notify.delete"); - + OPI_Tools.AddField("ID", NotificationID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction #EndRegion @@ -3432,137 +3432,137 @@ Procedure MakeBoolean(Value) OPI_TypeConversion.GetBoolean(Value); Value = ?(Value, "Y", "N"); - + EndProcedure Function NormalizeAuth(URL, Val Token, Val Method = "") - + OPI_TypeConversion.GetLine(URL); OPI_TypeConversion.GetLine(Token); - - Parameters = New Structure; + + Parameters = New Structure; IsTokenAuth = ValueIsFilled(Token); - + UncorrectItems = New Array; UncorrectItems.Add("https://"); UncorrectItems.Add("http://"); UncorrectItems.Add("www."); - + For Each DeletedElement In UncorrectItems Do URL = StrReplace(URL, DeletedElement, ""); EndDo; - + URL = TrimAll(URL); - + If Not StrEndsWith(URL, "/") Then URL = URL + "/"; EndIf; - + If IsTokenAuth Then - + If Not StrEndsWith(URL, "rest/") Then URL = URL + "rest/"; EndIf; - + Parameters.Insert("auth", Token); - + EndIf; - + If ValueIsFilled(Method) Then URL = URL + TrimAll(Method); EndIf; - + Return Parameters; EndFunction Function NormalizeFiles(Val Files) - + NormalizedFiles = New Array; If TypeOf(Files) = Type("Map") Then - - For Each File In Files Do - + + For Each File In Files Do + CurrentArray = New Array; - CurrentFile = File.Value; - CurrentName = File.Key; - + CurrentFile = File.Value; + CurrentName = File.Key; + OPI_TypeConversion.GetBinaryData(CurrentFile); OPI_TypeConversion.GetLine(CurrentName); - + CurrentArray.Add(CurrentName); CurrentArray.Add(Base64String(CurrentFile)); - + NormalizedFiles.Add(CurrentArray); - + EndDo; - + EndIf; - + Return NormalizedFiles; - + EndFunction Function ManageTask(Val URL, Val TaskID, Val Method, Val Token = "") - + Parameters = NormalizeAuth(URL, Token, Method); OPI_Tools.AddField("taskId", TaskID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction Function FileManagement(Val URL, Val FileID, Val Method, Val Token = "") Parameters = NormalizeAuth(URL, Token, Method); OPI_Tools.AddField("id", FileID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - - Return Response; - + + Return Response; + EndFunction -Function ChecklistElementManagment(Val URL, Val TaskID, Val ElementID, Val Method, Val Token = "") - +Function ChecklistElementManagment(Val URL, Val TaskID, Val ElementID, Val Method, Val Token = "") + Parameters = NormalizeAuth(URL, Token, Method); - - OPI_Tools.AddField("TASKID", TaskID , "String", Parameters); + + OPI_Tools.AddField("TASKID", TaskID , "String", Parameters); OPI_Tools.AddField("ITEMID", ElementID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - + Return Response; - + EndFunction Function ChatManagment(Val URL, Val ChatID, Val Method, Val Token = "") Parameters = NormalizeAuth(URL, Token, Method); OPI_Tools.AddField("CHAT_ID", ChatID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters); - - Return Response; - + + Return Response; + EndFunction Function ChatNotificationsSwitch(Val URL, Val ChatID, Val Off, Val Token = "") MakeBoolean(Off); - + Parameters = NormalizeAuth(URL, Token, "im.chat.mute"); - + OPI_Tools.AddField("CHAT_ID", ChatID , "String", Parameters); - OPI_Tools.AddField("MUTE" , Off, "String", Parameters); - + OPI_Tools.AddField("MUTE" , Off , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters); - - Return Response; - + + Return Response; + EndFunction #EndRegion diff --git a/src/en/OPI/src/CommonModules/OPI_Cryptography/Module.bsl b/src/en/OPI/src/CommonModules/OPI_Cryptography/Module.bsl index c19c9b31cf..b641bee99b 100644 --- a/src/en/OPI/src/CommonModules/OPI_Cryptography/Module.bsl +++ b/src/en/OPI/src/CommonModules/OPI_Cryptography/Module.bsl @@ -39,75 +39,75 @@ /////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2019, LLC 1C-Soft -// All rights reserved. This program and accompanying materials are provided +// All rights reserved. This program and accompanying materials are provided // under the terms of the Attribution 4.0 International (CC BY 4.0 license) // License text available at: // https://creativecommons.org/licenses/by/4.0/legalcode /////////////////////////////////////////////////////////////////////////////////////////////////////// Function HMACSHA256(Val Key, Val Data) Export - + Return HMAC(Key, Data, HashFunction.SHA256, 64); - + EndFunction Function Hash(BinaryData, Type) Export - + Hashing = New DataHashing(Type); Hashing.Append(BinaryData); - + Return Hashing.HashSum; - + EndFunction Function HMAC(Val Key, Val Data, Type, BlockSize) Export - + Twice = 2; - + If Key.Size() > BlockSize Then Key = Hash(Key, Type); EndIf; - + If Key.Size() <= BlockSize Then - Key = GetHexStringFromBinaryData(Key); - Key = Left(Key + RepeatString("00", BlockSize), BlockSize * Twice); + Key = GetHexStringFromBinaryData(Key); + Key = Left(Key + RepeatString("00", BlockSize), BlockSize * Twice); EndIf; - + Key = GetBinaryDataBufferFromBinaryData(GetBinaryDataFromHexString(Key)); - + Ipad = GetBinaryDataBufferFromHexString(RepeatString("36", BlockSize)); Opad = GetBinaryDataBufferFromHexString(RepeatString("5c", BlockSize)); - + Ipad.WriteBitwiseXor(0, Key); Ikeypad = GetBinaryDataFromBinaryDataBuffer(ipad); - + Opad.WriteBitwiseXor(0, Key); Okeypad = GetBinaryDataFromBinaryDataBuffer(opad); - + Return Hash(UniteBinaryData(okeypad, Hash(UniteBinaryData(ikeypad, Data), Type)), Type); - + EndFunction Function UniteBinaryData(BinaryData1, BinaryData2) Export - + BinaryDataArray = New Array; BinaryDataArray.Add(BinaryData1); BinaryDataArray.Add(BinaryData2); - + Return ConcatBinaryData(BinaryDataArray); - + EndFunction Function RepeatString(String, Count) Export - + Parts = New Array(Count); - + For K = 1 To Count Do Parts.Add(String); EndDo; Return StrConcat(Parts, ""); - + EndFunction #EndRegion diff --git a/src/en/OPI/src/CommonModules/OPI_Dropbox/Module.bsl b/src/en/OPI/src/CommonModules/OPI_Dropbox/Module.bsl index 192833dce4..908e95e140 100644 --- a/src/en/OPI/src/CommonModules/OPI_Dropbox/Module.bsl +++ b/src/en/OPI/src/CommonModules/OPI_Dropbox/Module.bsl @@ -42,128 +42,128 @@ // Get authorization link // Generates an authorization link for browser transition -// +// // Parameters: // AppKey - String - Application key - appkey -// +// // Returns: // String - URL for browser transition Function GetAuthorizationLink(Val AppKey) Export - + OPI_TypeConversion.GetLine(AppKey); - Return "https://www.dropbox.com/oauth2/authorize?client_id=" - + AppKey + Return "https://www.dropbox.com/oauth2/authorize?client_id=" + + AppKey + "&response_type=code&token_access_type=offline"; - + EndFunction // Get token // Gets token based on the code from the GetAuthorizationLink page -// +// // Parameters: // AppKey - String - Application key - appkey // AppSecret - String - Application secret - appsecret // Code - String - Code from the authorization page - code -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function GetToken(Val AppKey, Val AppSecret, Val Code) Export - - URL = "https://api.dropbox.com/oauth2/token"; + + URL = "https://api.dropbox.com/oauth2/token"; DataType = "application/x-www-form-urlencoded; charset=utf-8"; - - Parameters = New Structure; - OPI_Tools.AddField("code" , Code , "String", Parameters); + + Parameters = New Structure; + OPI_Tools.AddField("code" , Code , "String", Parameters); OPI_Tools.AddField("grant_type", "authorization_code", "String", Parameters); - + URLStructure = OPI_Tools.SplitURL(URL); - Server = URLStructure["Server"]; - Address = URLStructure["Address"]; - - Request = OPI_Tools.CreateRequest(Address, , DataType); + Server = URLStructure["Server"]; + Address = URLStructure["Address"]; + + Request = OPI_Tools.CreateRequest(Address, , DataType); Connection = OPI_Tools.CreateConnection(Server, AppKey, AppSecret); ParameterString = OPI_Tools.RequestParametersToString(Parameters); - Data = Right(ParameterString, StrLen(ParameterString) - 1); + Data = Right(ParameterString, StrLen(ParameterString) - 1); Request.SetBodyFromString(Data); - + Response = Connection.CallHTTPMethod("POST", Request); OPI_Tools.ProcessResponse(Response); - + Return Response; - + EndFunction // Refresh token // Gets a new token based on the refresh token -// +// // Parameters: // AppKey - String - Application key - appkey // AppSecret - String - Application secret - appsecret // RefreshToken - String - Refresh token - refresh -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function RefreshToken(Val AppKey, Val AppSecret, Val RefreshToken) Export - + String_ = "String"; - URL = "https://api.dropbox.com/oauth2/token"; - + URL = "https://api.dropbox.com/oauth2/token"; + Parameters = New Structure; - OPI_Tools.AddField("refresh_token", RefreshToken , String_, Parameters); - OPI_Tools.AddField("grant_type" , "refresh_token" , String_, Parameters); - OPI_Tools.AddField("client_id" , AppKey , String_, Parameters); - OPI_Tools.AddField("client_secret", AppSecret, String_, Parameters); - + OPI_Tools.AddField("refresh_token", RefreshToken , String_, Parameters); + OPI_Tools.AddField("grant_type" , "refresh_token" , String_, Parameters); + OPI_Tools.AddField("client_id" , AppKey , String_, Parameters); + OPI_Tools.AddField("client_secret", AppSecret , String_, Parameters); + Response = OPI_Tools.Post(URL, Parameters, , False); - + Return Response; - + EndFunction // Get account information // Gets account information -// +// // Parameters: // Token - String - Token - token // Account - String - Account ID. Current token account if not filled - account -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function GetAccountInformation(Val Token, Val Account = "") Export - + If ValueIsFilled(Account) Then Result = GetAccount(Token, Account); Else Result = GetOwnAccount(Token); EndIf; - + Return Result; - + EndFunction // Get space usage data // Gets information on the amount of used disk space -// +// // Parameters: -// Token - String - Token - token -// +// Token - String - Token - token +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function GetSpaceUsageData(Val Token) Export - - URL = "https://api.dropboxapi.com/2/users/get_space_usage"; + + URL = "https://api.dropboxapi.com/2/users/get_space_usage"; Headers = GetRequestHeaders(Token); - + Response = OPI_Tools.PostBinary(URL , GetBinaryDataFromString("null") , Headers - , - , "text/plain; charset=dropbox-cors-hack"); - + , + , "text/plain; charset=dropbox-cors-hack"); + Return Response; - + EndFunction #EndRegion @@ -172,344 +172,344 @@ EndFunction // Get object information // Gets information about a file or directory -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the object - path -// Detailed - Boolean - Add information fields for mediafiles - detail -// +// Detailed - Boolean - Add information fields for mediafiles - detail +// // Returns: -// Map Of KeyAndValue - serialized JSON response from Dropbox +// Map Of KeyAndValue - serialized JSON response from Dropbox Function GetObjectInformation(Val Token, Val Path, Val Detailed = False) Export - - URL = "https://api.dropboxapi.com/2/files/get_metadata"; - + + URL = "https://api.dropboxapi.com/2/files/get_metadata"; + Parameters = New Structure; - OPI_Tools.AddField("path" , Path , "String", Parameters); + OPI_Tools.AddField("path" , Path , "String" , Parameters); OPI_Tools.AddField("include_media_info", Detailed, "Boolean", Parameters); - - Headers = GetRequestHeaders(Token); + + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Get list of folder files // Gets the list of the first files in the directory or continues getting the next ones when the cursor is specified -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the directory. Optional if the cursor is specified - path // Detailed - Boolean - Add information fields for mediafiles - detail // Cursor - String - Cursor from the previous request to get the next set of files - cursor -// +// // Returns: // HTTPResponse - Get list of folder files Function GetListOfFolderFiles(Val Token, Val Path = "", Val Detailed = False, Val Cursor = "") Export - + If Not ValueIsFilled(Cursor) Then - + URL = "https://api.dropboxapi.com/2/files/list_folder"; - + Parameters = New Structure; - OPI_Tools.AddField("path" , Path , "String", Parameters); + OPI_Tools.AddField("path" , Path , "String" , Parameters); OPI_Tools.AddField("include_media_info", Detailed , "Boolean", Parameters); - + Else - + URL = "https://api.dropboxapi.com/2/files/list_folder/continue"; - + Parameters = New Structure; - OPI_Tools.AddField("cursor", Cursor, "String", Parameters); - + OPI_Tools.AddField("cursor", Cursor, "String", Parameters); + EndIf; - + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Get preview // Gets PDF or HTML preview of the object (for documents only) -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the object - path -// +// // Returns: -// BinaryData - document preview +// BinaryData - document preview Function GetPreview(Val Token, Val Path) Export - - URL = "https://content.dropboxapi.com/2/files/get_preview"; + + URL = "https://content.dropboxapi.com/2/files/get_preview"; Response = ProcessObject(Token, URL, Path, True); - + Return Response; - + EndFunction // Upload file // Uploads a file to the cloud drive -// +// // Parameters: // Token - String - Token - token // File - String, BinaryData - Data file for upload - file // Path - String - Save path on Dropbox - path // Overwrite - Boolean - Overwrite file in case of path conflicts - overwrite -// +// // Returns: -// Map Of KeyAndValue - serialized JSON response from Dropbox +// Map Of KeyAndValue - serialized JSON response from Dropbox Function UploadFile(Val Token, Val File, Val Path, Val Overwrite = False) Export - + OPI_TypeConversion.GetBinaryData(File); OPI_TypeConversion.GetBoolean(Overwrite); OPI_TypeConversion.GetLine(Path); - - Mode = ?(Overwrite, "overwrite", "add"); - Size = File.Size(); + + Mode = ?(Overwrite, "overwrite", "add"); + Size = File.Size(); Border = 100000000; - + If Size > Border Then Response = UploadLargeFile(Token, File, Path, Mode); Else Response = UploadSmallFile(Token, File, Path, Mode); EndIf; - + Return Response; - + EndFunction // Upload file by URL -// Uploads a file to the cloud drive by fetching it from the specified URL -// +// Uploads a file to the cloud drive by fetching it from the specified URL +// // Parameters: // Token - String - Token - token // FileURL - String - URL source of the file - url // Path - String - Save path on Dropbox - path -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function UploadFileByURL(Val Token, Val FileURL, Val Path) Export - - URL = "https://api.dropboxapi.com/2/files/save_url"; - + + URL = "https://api.dropboxapi.com/2/files/save_url"; + Parameters = New Structure; - OPI_Tools.AddField("path", Path , "String", Parameters); + OPI_Tools.AddField("path", Path , "String", Parameters); OPI_Tools.AddField("url" , FileURL , "String", Parameters); - - Headers = GetRequestHeaders(Token); + + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Get upload status by URL // Gets the upload status of the file by URL -// +// // Parameters: // Token - String - Token - token -// JobID - String - ID of async jsob from UploadFileByURL response - job -// +// JobID - String - ID of async jsob from UploadFileByURL response - job +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function GetUploadStatusByURL(Val Token, Val JobID) Export - - URL = "https://api.dropboxapi.com/2/files/save_url/check_job_status"; - + + URL = "https://api.dropboxapi.com/2/files/save_url/check_job_status"; + Parameters = New Structure; OPI_Tools.AddField("async_job_id", JobID, "String", Parameters); - - Headers = GetRequestHeaders(Token); + + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Delete object // Deletes an object from the cloud drive -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the object to delete - path // Irrecoverable - String - Delete object without the possibility of recovery - permanently -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function DeleteObject(Val Token, Val Path, Val Irrecoverable = False) Export - + OPI_TypeConversion.GetBoolean(Irrecoverable); - + If Irrecoverable Then URL = "https://api.dropboxapi.com/2/files/permanently_delete"; Else URL = "https://api.dropboxapi.com/2/files/delete_v2"; EndIf; - + Response = ProcessObject(Token, URL, Path); - + Return Response; EndFunction // Copy object // Copies a file or directory to the selected path -// +// // Parameters: // Token - String - Token - token // From - String - Path to the original object - form // Target - String - Target path for the new object - to -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function CopyObject(Val Token, Val From, Val Target) Export - + URL = "https://api.dropboxapi.com/2/files/copy_v2"; - + Parameters = New Structure; - OPI_Tools.AddField("from_path", From, "String", Parameters); - OPI_Tools.AddField("to_path" , Target , "String", Parameters); - + OPI_Tools.AddField("from_path", From , "String", Parameters); + OPI_Tools.AddField("to_path" , Target , "String", Parameters); + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Move object // Moves an object to the selected path -// +// // Parameters: // Token - String - Token - token // From - String - Path to the original object - form // Target - String - Target path for the new object - to -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function MoveObject(Val Token, Val From, Val Target) Export URL = "https://api.dropboxapi.com/2/files/move_v2"; - + Parameters = New Structure; - OPI_Tools.AddField("from_path", From, "String", Parameters); - OPI_Tools.AddField("to_path" , Target , "String", Parameters); - + OPI_Tools.AddField("from_path", From , "String", Parameters); + OPI_Tools.AddField("to_path" , Target , "String", Parameters); + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Create folder // Creates an empty directory at the selected path -// +// // Parameters: // Token - String - Token - token // Path - String - Target path for creating the directory - path -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function CreateFolder(Val Token, Val Path) Export - - URL = "https://api.dropboxapi.com/2/files/create_folder_v2"; + + URL = "https://api.dropboxapi.com/2/files/create_folder_v2"; Response = ProcessObject(Token, URL, Path); - + Return Response; - + EndFunction // Download file // Downloads a file by the specified path or ID -// +// // Parameters: // Token - String - Token - token // Path - String - Path or ID of the file - path -// +// // Returns: // BinaryData - binary data of the file Function DownloadFile(Val Token, Val Path) Export - - URL = "https://content.dropboxapi.com/2/files/download"; + + URL = "https://content.dropboxapi.com/2/files/download"; Response = ProcessObject(Token, URL, Path, True); - + Return Response; - + EndFunction // Download folder // Downloads a zip archive with the contents of the specified directory -// +// // Parameters: // Token - String - Token - token // Path - String - Path or ID of the directory - path -// +// // Returns: // BinaryData - binary data of the zip archive with the contents of the directory Function DownloadFolder(Val Token, Val Path) Export - - URL = "https://content.dropboxapi.com/2/files/download_zip"; + + URL = "https://content.dropboxapi.com/2/files/download_zip"; Response = ProcessObject(Token, URL, Path, True); - + Return Response; - + EndFunction // Get list of object versions // Gets the list of versions (revisions) of the object -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the object - path // Count - String, Number - Number of the latest versions of the object to display - amount -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function GetObjectVersionList(Val Token, Val Path, Val Count = 10) Export - - URL = "https://api.dropboxapi.com/2/files/list_revisions"; - + + URL = "https://api.dropboxapi.com/2/files/list_revisions"; + Parameters = New Structure; - OPI_Tools.AddField("path" , Path , "String", Parameters); + OPI_Tools.AddField("path" , Path , "String" , Parameters); OPI_Tools.AddField("limit", Count, "Number" , Parameters); - - Headers = GetRequestHeaders(Token); + + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Restore object to version // Restores object state to required version (revision) -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the object - path // Version - String - ID of the version (revision) for restoration - rev -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function RestoreObjectToVersion(Val Token, Val Path, Val Version) Export - - URL = "https://api.dropboxapi.com/2/files/restore"; - + + URL = "https://api.dropboxapi.com/2/files/restore"; + Parameters = New Structure; - OPI_Tools.AddField("path", Path , "String", Parameters); + OPI_Tools.AddField("path", Path , "String", Parameters); OPI_Tools.AddField("rev" , Version, "String", Parameters); - - Headers = GetRequestHeaders(Token); + + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction #EndRegion @@ -518,58 +518,58 @@ EndFunction // Get list of tags // Gets the list of tags of the selected files -// +// // Parameters: // Token - String - Token - token // Paths - String, Array of String - Path or set of paths to the files - paths -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function GetTagList(Val Token, Val Paths) Export - + URL = "https://api.dropboxapi.com/2/files/tags/get"; - + Parameters = New Structure; OPI_Tools.AddField("paths", Paths, "Array", Parameters); - + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Add tag // Add new tag to file or folder -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the object for which the tag needs to be created - path // Tag - String - Tag text - tag -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function AddTag(Val Token, Val Path, Val Tag) Export - + Return ProcessTag(Token, Path, Tag); - + EndFunction // Delete tag // Deletes the text tag of a file or directory -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the object whose tag needs to be deleted - path // Tag - String - Tag text - tag -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function DeleteTag(Val Token, Val Path, Val Tag) Export - + Return ProcessTag(Token, Path, Tag, True); - + EndFunction #EndRegion @@ -578,39 +578,39 @@ EndFunction // Publish folder // Sets the directory to public access mode -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the target directory - path -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function PublishFolder(Val Token, Val Path) Export - - URL = "https://api.dropboxapi.com/2/sharing/share_folder"; + + URL = "https://api.dropboxapi.com/2/sharing/share_folder"; Response = ProcessObject(Token, URL, Path); - + Return Response; - + EndFunction // Unpublish folder // Cancels the public access mode for the directory -// +// // Parameters: // Token - String - Token - token // FolderID - String - ID of the public catalog (shared folder ID) - folder -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function CancelFolderPublication(Val Token, Val FolderID) Export - + URL = "https://api.dropboxapi.com/2/sharing/unshare_folder"; - + Parameters = New Structure; OPI_Tools.AddField("shared_folder_id", FolderID, "String", Parameters); - - Headers = GetRequestHeaders(Token); + + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); Return Response; @@ -619,121 +619,121 @@ EndFunction // Add user to file // Defines access to the file for an external user -// +// // Parameters: // Token - String - Token - token // FileID - String - ID of the file to be accessed - fileid // EmailAddresses - String, Array of String - List of email addresses of users being added - emails // ViewOnly - Boolean - Prohibits file editing for the external user - readonly -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function AddUsersToFile(Val Token, Val FileID, Val EmailAddresses, Val ViewOnly = True) Export - + String_ = "String"; - + OPI_TypeConversion.GetArray(EmailAddresses); OPI_TypeConversion.GetLine(FileID); OPI_TypeConversion.GetBoolean(ViewOnly); - + If Not StrStartsWith(FileID, "id:") Then FileID = "id:" + FileID; EndIf; - + URL = "https://api.dropboxapi.com/2/sharing/add_file_member"; - + ArrayOfUsers = New Array; - + For Each Address In EmailAddresses Do - + UserData = New Map; - OPI_Tools.AddField(".tag" , "email", String_, UserData); + OPI_Tools.AddField(".tag" , "email" , String_, UserData); OPI_Tools.AddField("email", Address , String_, UserData); - + ArrayOfUsers.Add(UserData); EndDo; - + Parameters = New Structure; - OPI_Tools.AddField("file" , FileID , String_, Parameters); + OPI_Tools.AddField("file" , FileID , String_, Parameters); OPI_Tools.AddField("members", ArrayOfUsers , "Array", Parameters); - + Mode = ?(ViewOnly, "viewer", "editor"); - + OPI_Tools.AddField("access_level", Mode , String_, Parameters); - + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Add users to folder // Grants external users access to the directory -// +// // Parameters: // Token - String - Token - token // FolderID - String - ID of the public catalog (shared folder ID) - folder // EmailAddresses - String, Array of String - List of email addresses of users being added - emails // ViewOnly - Boolean - Prohibits file editing for the external user - readonly -// +// // Returns: // Undefined - empty response Function AddUsersToFolder(Val Token, Val FolderID, Val EmailAddresses, Val ViewOnly = True) Export - + String_ = "String"; - + OPI_TypeConversion.GetArray(EmailAddresses); OPI_TypeConversion.GetBoolean(ViewOnly); Mode = ?(ViewOnly, "viewer", "editor"); - + URL = "https://api.dropboxapi.com/2/sharing/add_folder_member"; - + ArrayOfUsers = New Array; - + For Each Address In EmailAddresses Do - + UserData = New Map; - OPI_Tools.AddField(".tag" , "email", String_, UserData); + OPI_Tools.AddField(".tag" , "email" , String_, UserData); OPI_Tools.AddField("email", Address , String_, UserData); - - UserStructure = New Structure("member,access_level", UserData, Mode); - + + UserStructure = New Structure("member,access_level", UserData, Mode); + ArrayOfUsers.Add(UserStructure); EndDo; - + Parameters = New Structure; - OPI_Tools.AddField("shared_folder_id", FolderID , String_, Parameters); - OPI_Tools.AddField("members" , ArrayOfUsers , "Array", Parameters); - + OPI_Tools.AddField("shared_folder_id", FolderID , String_, Parameters); + OPI_Tools.AddField("members" , ArrayOfUsers , "Array", Parameters); + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction // Get asynchronous change status // Get async job status for access changes -// +// // Parameters: // Token - String - Token - token // JobID - String - AsynchronousJobID - job -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function GetAsynchronousChangeStatus(Val Token, Val JobID) Export - + URL = "https://api.dropboxapi.com/2/sharing/check_job_status"; - + Parameters = New Structure; OPI_Tools.AddField("async_job_id", JobID, "String", Parameters); - - Headers = GetRequestHeaders(Token); + + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); Return Response; @@ -742,31 +742,31 @@ EndFunction // Unpublish file // Prohibits access to the file for external users -// +// // Parameters: // Token - String - Token - token // FileID - String - ID of the file to be accessed - fileid -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Dropbox Function CancelFilePublication(Val Token, Val FileID) Export - + OPI_TypeConversion.GetLine(FileID); - + If Not StrStartsWith(FileID, "id:") Then FileID = "id:" + FileID; EndIf; - + URL = "https://api.dropboxapi.com/2/sharing/unshare_file"; - + Parameters = New Structure; OPI_Tools.AddField("file", FileID, "String", Parameters); - - Headers = GetRequestHeaders(Token); + + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); Return Response; - + EndFunction #EndRegion @@ -776,20 +776,20 @@ EndFunction #Region Private Function ProcessObject(Val Token, Val URL, Val Path, Val InHeaders = False) - + Parameters = New Structure; OPI_Tools.AddField("path", Path, "String", Parameters); - + If InHeaders Then - Headers = GetRequestHeaders(Token, Parameters); + Headers = GetRequestHeaders(Token, Parameters); Response = OPI_Tools.PostBinary(URL, GetBinaryDataFromString(""), Headers); Else - Headers = GetRequestHeaders(Token); + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); EndIf; - + Return Response; - + EndFunction Function ProcessTag(Val Token, Val Path, Val Tag, Val ThisIsDeletion = False) @@ -799,168 +799,168 @@ Function ProcessTag(Val Token, Val Path, Val Tag, Val ThisIsDeletion = False) Else URL = "https://api.dropboxapi.com/2/files/tags/add"; EndIf; - + Parameters = New Structure; - OPI_Tools.AddField("path" , Path, "String", Parameters); + OPI_Tools.AddField("path" , Path, "String", Parameters); OPI_Tools.AddField("tag_text" , Tag , "String", Parameters); - + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction Function GetRequestHeaders(Val Token, Val Parameters = "") - + OPI_TypeConversion.GetLine(Token); - + Headers = New Map; Headers.Insert("Authorization" , "Bearer " + Token); - + If ValueIsFilled(Parameters) Then - + JSON = OPI_Tools.JSONString(Parameters, "None"); JSON = StrReplace(JSON, Chars.CR + Chars.LF, ""); Headers.Insert("Dropbox-API-Arg", JSON); - + EndIf; - + Return Headers; - + EndFunction Function UploadLargeFile(Val Token, Val File, Val Path, Val Mode) - - URL = "https://content.dropboxapi.com/2/files/upload_session/append_v2"; - ChunkSize = 100000000; + URL = "https://content.dropboxapi.com/2/files/upload_session/append_v2"; + + ChunkSize = 100000000; CurrentPosition = 0; - BytesRead = 0; - TotalSize = File.Size(); - Session = OpenSession(Token); - + BytesRead = 0; + TotalSize = File.Size(); + Session = OpenSession(Token); + WHile BytesRead < TotalSize Do - + Indent = CurrentPosition; Cursor = New Structure("offset,session_id", Indent, Session); - + Parameters = New Structure("cursor", Cursor); - Headers = GetRequestHeaders(Token, Parameters); - - DataReader = New DataReader(File); - BytesRead = DataReader.Skip(CurrentPosition); - Result = DataReader.Read(ChunkSize); - CurrentData = Result.GetBinaryData(); - CurrentSize = CurrentData.Size(); - NextPosition = CurrentPosition + CurrentSize; - + Headers = GetRequestHeaders(Token, Parameters); + + DataReader = New DataReader(File); + BytesRead = DataReader.Skip(CurrentPosition); + Result = DataReader.Read(ChunkSize); + CurrentData = Result.GetBinaryData(); + CurrentSize = CurrentData.Size(); + NextPosition = CurrentPosition + CurrentSize; + If Not ValueIsFilled(CurrentData) Then Break; EndIf; Response = OPI_Tools.PostBinary(URL, CurrentData, Headers); - + CurrentPosition = NextPosition; - + // !OInt KB = 1024; // !OInt MB = KB * KB; // !OInt Message(OPI_Tools.ProgressInfo(CurrentPosition, TotalSize, "MB", MB)); - + // !OInt RunGarbageCollection(); // !OInt FreeObject(CurrentData); - + EndDo; - + Response = CloseSession(Token, Path, Mode, TotalSize, Session); - + Return Response; - + EndFunction Function UploadSmallFile(Val Token, Val File, Val Path, Val Mode) - + Boolean_ = "Boolean"; - String_ = "String"; - URL = "https://content.dropboxapi.com/2/files/upload"; - + String_ = "String"; + URL = "https://content.dropboxapi.com/2/files/upload"; + Parameters = New Structure; - - OPI_Tools.AddField("autorename" , False , Boolean_, Parameters); - OPI_Tools.AddField("mode" , Mode, String_, Parameters); - OPI_Tools.AddField("mute" , False , Boolean_, Parameters); - OPI_Tools.AddField("path" , Path , String_, Parameters); + + OPI_Tools.AddField("autorename" , False , Boolean_, Parameters); + OPI_Tools.AddField("mode" , Mode , String_ , Parameters); + OPI_Tools.AddField("mute" , False , Boolean_, Parameters); + OPI_Tools.AddField("path" , Path , String_ , Parameters); OPI_Tools.AddField("strict_conflict", False , Boolean_, Parameters); - + Headers = GetRequestHeaders(Token, Parameters); Response = OPI_Tools.PostBinary(URL, File, Headers); - + Return Response; - + EndFunction Function OpenSession(Val Token) - + SessionId = "session_id"; - URL = "https://content.dropboxapi.com/2/files/upload_session/start"; - Headers = GetRequestHeaders(Token); - - Response = OPI_Tools.PostBinary(URL, GetBinaryDataFromString(""), Headers); - + URL = "https://content.dropboxapi.com/2/files/upload_session/start"; + Headers = GetRequestHeaders(Token); + + Response = OPI_Tools.PostBinary(URL, GetBinaryDataFromString(""), Headers); + Return Response[SessionId]; - + EndFunction Function CloseSession(Val Token, Val Path, Val Mode, Val TotalSize, Val Session) URL = "https://content.dropboxapi.com/2/files/upload_session/finish"; - + Commit = New Structure(); OPI_Tools.AddField("mode", Mode, "String", Commit); - OPI_Tools.AddField("path", Path, "String", Commit); - + OPI_Tools.AddField("path", Path, "String", Commit); + Cursor = New Structure("offset,session_id", TotalSize, Session); - + Parameters = New Structure("commit,cursor", Commit, Cursor); - Headers = GetRequestHeaders(Token, Parameters); - + Headers = GetRequestHeaders(Token, Parameters); + Response = OPI_Tools.PostBinary(URL, GetBinaryDataFromString(""), Headers); - + Return Response; - + EndFunction Function GetAccount(Val Token, Val Account) - + URL = "https://api.dropboxapi.com/2/users/get_account"; - + Parameters = New Structure; OPI_Tools.AddField("account_id", Account, "String", Parameters); - + Headers = GetRequestHeaders(Token); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction Function GetOwnAccount(Val Token) - - URL = "https://api.dropboxapi.com/2/users/get_current_account"; + + URL = "https://api.dropboxapi.com/2/users/get_current_account"; Headers = GetRequestHeaders(Token); - + Response = OPI_Tools.PostBinary(URL , GetBinaryDataFromString("null") , Headers - , - , "text/plain; charset=dropbox-cors-hack"); - + , + , "text/plain; charset=dropbox-cors-hack"); + Return Response; - + EndFunction #EndRegion diff --git a/src/en/OPI/src/CommonModules/OPI_GoogleCalendar/Module.bsl b/src/en/OPI/src/CommonModules/OPI_GoogleCalendar/Module.bsl index 567106d569..9d091238bb 100644 --- a/src/en/OPI/src/CommonModules/OPI_GoogleCalendar/Module.bsl +++ b/src/en/OPI/src/CommonModules/OPI_GoogleCalendar/Module.bsl @@ -43,131 +43,131 @@ // Create calendar // Creates an empty calendar -// +// // Parameters: // Token - String - Token - token // Name - String - Name of the created calendar - title -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function CreateCalendar(Val Token, Val Name) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Name); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/calendar/v3/calendars"; - + URL = "https://www.googleapis.com/calendar/v3/calendars"; + Parameters = New Structure; Parameters.Insert("summary" , Name); Parameters.Insert("timeZone", "Europe/Moscow"); - + Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Get calendar // Gets calendar information by ID -// +// // Parameters: // Token - String - Token - token // Calendar - String - Calendar ID - calendar -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function GetCalendarMetadata(Val Token, Val Calendar) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Calendar); - - Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/calendar/v3/calendars/" + Calendar; + + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); + URL = "https://www.googleapis.com/calendar/v3/calendars/" + Calendar; Response = OPI_Tools.Get(URL, , Headers); - + Return Response; EndFunction // Edit calendar // Edits properties of an existing calendar -// +// // Parameters: // Token - String - Token - token // Calendar - String - Calendar ID - calendar // Name - String - New name - title // Description - String - New calendar description - description -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function EditCalendarMetadata(Val Token , Val Calendar , Val Name = "" , Val Description = "") Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Calendar); OPI_TypeConversion.GetLine(Name); OPI_TypeConversion.GetLine(Description); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/calendar/v3/calendars/" + Calendar; - + URL = "https://www.googleapis.com/calendar/v3/calendars/" + Calendar; + Parameters = New Structure; - + If ValueIsFilled(Name) Then Parameters.Insert("summary", Name); EndIf; - + If ValueIsFilled(Description) Then Parameters.Insert("description", Description); EndIf; - + Response = OPI_Tools.Patch(URL, Parameters, Headers, True); - + Return Response; EndFunction // Clear primary calendar // Clears the event list of the primary calendar -// +// // Parameters: // Token - String - Token - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function ClearMainCalendar(Val Token) Export - + OPI_TypeConversion.GetLine(Token); - - Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/calendar/v3/calendars/primary/clear"; + + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); + URL = "https://www.googleapis.com/calendar/v3/calendars/primary/clear"; Response = OPI_Tools.Post(URL, , Headers, False); - + Return Response; EndFunction // Delete calendar // Deletes a calendar by ID -// +// // Parameters: // Token - String - Token - token // Calendar - String - Calendar ID - calendar -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function DeleteCalendar(Val Token, Val Calendar) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Calendar); - - Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/calendar/v3/calendars/" + Calendar; + + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); + URL = "https://www.googleapis.com/calendar/v3/calendars/" + Calendar; Response = OPI_Tools.Delete(URL, , Headers); - + Return Response; EndFunction @@ -178,105 +178,105 @@ EndFunction // Get list of calendars // Gets an array of account calendars -// +// // Parameters: // Token - String - Token - token -// +// // Returns: // Map Of KeyAndValue - Array of calendar data mappings Function GetCalendarList(Val Token) Export - + OPI_TypeConversion.GetLine(Token); - - Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); + + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); ArrayOfCalendars = New Array; - + GetCalendarsListRecursively(Headers, ArrayOfCalendars); - + Return ArrayOfCalendars; - + EndFunction // Add calendar to list // Adds an existing calendar to the user's list -// +// // Parameters: // Token - String - Token - token // Calendar - String - Calendar ID - calendar -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function AddCalendarToList(Val Token, Val Calendar) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Calendar); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/calendar/v3/users/me/calendarList"; - + URL = "https://www.googleapis.com/calendar/v3/users/me/calendarList"; + Parameters = New Structure; Parameters.Insert("id", Calendar); - + Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Get list calendar // Gets a calendar from the user's list by ID -// +// // Parameters: // Token - String - Token - token // Calendar - String - Calendar ID - calendar -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function GetListCalendar(Val Token, Val Calendar) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Calendar); - - Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/calendar/v3/users/me/calendarList/" + Calendar; + + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); + URL = "https://www.googleapis.com/calendar/v3/users/me/calendarList/" + Calendar; Response = OPI_Tools.Get(URL, , Headers); - + Return Response; EndFunction // Remove calendar from list // Removes a calendar from the user's list -// +// // Parameters: // Token - String - Token - token // Calendar - String - Calendar ID - calendar -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function DeleteCalendarFromList(Val Token, Val Calendar) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Calendar); - - Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/calendar/v3/users/me/calendarList/" + Calendar; + + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); + URL = "https://www.googleapis.com/calendar/v3/users/me/calendarList/" + Calendar; Response = OPI_Tools.Delete(URL, , Headers); - + Return Response; EndFunction // Edit list calendar // Edits the properties of a calendar from the user's list -// +// // Parameters: // Token - String - Token - token // Calendar - String - Calendar ID - calendar // PrimaryColor - String - HEX primary color (#ffffff) - primary // SecondaryColor - String - HEX secondary color (#ffffff) - secondary // Hidden - Boolean - Hidden calendar - hidden -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function EditListCalendar(Val Token @@ -284,23 +284,23 @@ Function EditListCalendar(Val Token , Val PrimaryColor , Val SecondaryColor , Val Hidden = False) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Calendar); OPI_TypeConversion.GetLine(PrimaryColor); OPI_TypeConversion.GetLine(SecondaryColor); OPI_TypeConversion.GetBoolean(Hidden); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/calendar/v3/users/me/calendarList/" + Calendar + "?colorRgbFormat=true"; - + URL = "https://www.googleapis.com/calendar/v3/users/me/calendarList/" + Calendar + "?colorRgbFormat =true"; + Parameters = New Map; - Parameters.Insert("hidden" , Hidden); + Parameters.Insert("hidden" , Hidden); Parameters.Insert("foregroundColor", PrimaryColor); Parameters.Insert("backgroundColor", SecondaryColor); - + Response = OPI_Tools.Put(URL, Parameters, Headers); - + Return Response; EndFunction @@ -310,167 +310,167 @@ EndFunction #Region EventManagement // Get event description !NOCLI -// +// // Returns: // Map Of KeyAndValue - Empty event template Function GetEventDescription() Export - + CurrentDate = OPI_Tools.GetCurrentDate(); - Hour = 3600; - Event = New Map; - - Event.Insert("Description" , ""); // Event description - Event.Insert("Title" , "New event"); // Title events - Event.Insert("Venue" , ""); // String description of the venue of the event - Event.Insert("StartDate" , CurrentDate); // Date of start events - Event.Insert("EndDate" , CurrentDate + Hour); // Date of end events + Hour = 3600; + Event = New Map; + + Event.Insert("Description" , ""); // Event description + Event.Insert("Title" , "New event"); // Title events + Event.Insert("Venue" , ""); // String description of the venue of the event + Event.Insert("StartDate" , CurrentDate); // Date of start events + Event.Insert("EndDate" , CurrentDate + Hour); // Date of end events Event.Insert("ArrayOfAttachmentURLs", New Map); // Key - name, Value - URL to file - Event.Insert("SendNotifications" , True); // Indication of sending notifications to participants + Event.Insert("SendNotifications" , True); // Indication of sending notifications to participants Return Event; - + EndFunction // Get list of events // Gets the list of all calendar events -// +// // Parameters: // Token - String - Token - token // Calendar - String - Calendar ID - calendar -// +// // Returns: // Map Of KeyAndValue - Array of event maps Function GetEventList(Val Token, Val Calendar) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Calendar); - - Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); + + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); ArrayOfEvents = New Array; - + GetEventsListRecursively(Headers, Calendar, ArrayOfEvents); - + Return ArrayOfEvents; - + EndFunction // Get event // Gets an event by ID -// +// // Parameters: // Token - String - Token - token // Calendar - String - Calendar ID - calendar // Event - String - Event ID - event -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function GetEvent(Val Token, Val Calendar, Val Event) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Calendar); OPI_TypeConversion.GetLine(Event); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/calendar/v3/calendars/" - + Calendar + URL = "https://www.googleapis.com/calendar/v3/calendars/" + + Calendar + "/events/" - + Event; - + + Event; + Response = OPI_Tools.Get(URL, , Headers); - + Return Response; EndFunction // Create event // Creates a new event -// +// // Parameters: -// Token - String - Token - token +// Token - String - Token - token // Calendar - String - Calendar ID - calendar // EventDescription - Map Of KeyAndValue - Event description - props -// +// // Returns: // String, Arbitrary, HTTPResponse, BinaryData, Undefined - Google server response -Function CreateEvent(Val Token, Val Calendar, Val EventDescription) Export - +Function CreateEvent(Val Token, Val Calendar, Val EventDescription) Export + Return EventManagement(Token, Calendar, EventDescription); - + EndFunction // Move event // Moves an event to another calendar -// +// // Parameters: // Token - String - Token - token // SourceCalendar - String - ID of the source calendar - from // TargetCalendar - String - ID of the target calendar - to // Event - String - ID of the source calendar event - event -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function MoveEvent(Val Token, Val SourceCalendar, Val TargetCalendar, Val Event) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(SourceCalendar); OPI_TypeConversion.GetLine(TargetCalendar); OPI_TypeConversion.GetLine(Event); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/calendar/v3/calendars/" - + SourceCalendar + URL = "https://www.googleapis.com/calendar/v3/calendars/" + + SourceCalendar + "/events/" + Event + "/move?destination=" - + TargetCalendar; - + + TargetCalendar; + Response = OPI_Tools.Post(URL, , Headers); - + Return Response; EndFunction // Edit event // Edits an existing event -// +// // Parameters: // Token - String - Token - token // Calendar - String - Calendar ID - calendar // EventDescription - String - New event description - props // Event - String - Event ID - event -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function EditEvent(Val Token, Val Calendar, Val EventDescription, Val Event) Export - + Return EventManagement(Token, Calendar, EventDescription, Event); - + EndFunction // Delete event // Deletes an event by ID -// +// // Parameters: // Token - String - Token - token // Calendar - String - Calendar ID - calendar // Event - String - Event ID - event -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function DeleteEvent(Val Token, Val Calendar, Val Event) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Calendar); OPI_TypeConversion.GetLine(Event); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/calendar/v3/calendars/" - + Calendar + URL = "https://www.googleapis.com/calendar/v3/calendars/" + + Calendar + "/events/" - + Event; - + + Event; + Response = OPI_Tools.Delete(URL, , Headers); - + Return Response; EndFunction @@ -482,51 +482,51 @@ EndFunction #Region Private Function ConvertDate(Val Date) - + OPI_TypeConversion.GetDate(Date); - + DateStructure = New Structure; - + If Not TypeOf(Date) = Type("Date") Then Return Undefined; EndIf; - - If Date = BegOfDay(Date) Then + + If Date = BegOfDay(Date) Then DateFormat = "DF=yyyy-MM-dd"; - Field = "date"; + Field = "date"; Else DateFormat = "DF=yyyy-MM-ddTHH:mm:ssZ"; - Field = "dateTime"; + Field = "dateTime"; EndIf; - + Date = Format(Date, DateFormat); - DateStructure.Insert(Field , Date); + DateStructure.Insert(Field , Date); DateStructure.Insert("timeZone", "Europe/Moscow"); - + Return DateStructure; - + EndFunction Function ConvertAttachments(Val Attachments) - + OPI_TypeConversion.GetCollection(Attachments); - + AttachmentsArray = New Array; - + If TypeOf(Attachments) = Type("Map") Or TypeOf(Attachments) = Type("Structure") Then - + For Each Attachment In Attachments Do - + CurrentAttachment = New Structure; - CurrentAttachment.Insert("title" , Attachment.Key); + CurrentAttachment.Insert("title" , Attachment.Key); CurrentAttachment.Insert("fileUrl", Attachment.Value); - + AttachmentsArray.Add(CurrentAttachment); - + EndDo; - + EndIf; - + If AttachmentsArray.Count() > 0 Then Return AttachmentsArray; Else @@ -536,105 +536,105 @@ Function ConvertAttachments(Val Attachments) EndFunction Function EventManagement(Val Token, Val Calendar, Val EventDescription, Val Event = "") - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Calendar); OPI_TypeConversion.GetLine(Event); OPI_TypeConversion.GetCollection(EventDescription); - - Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); + + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); Existing = ValueIsFilled(Event); - URL = "https://www.googleapis.com/calendar/v3/calendars/" - + Calendar + URL = "https://www.googleapis.com/calendar/v3/calendars/" + + Calendar + "/events" - + ?(Existing, "/" + Event, ""); - - Date0 = EventDescription["StartDate"]; - Date1 = EventDescription["EndDate"]; - Attachments = EventDescription["ArrayOfAttachmentURLs"]; - Attachments = ConvertAttachments(Attachments); + + ?(Existing, "/" + Event, ""); + + Date0 = EventDescription["StartDate"]; + Date1 = EventDescription["EndDate"]; + Attachments = EventDescription["ArrayOfAttachmentURLs"]; + Attachments = ConvertAttachments(Attachments); Notifications = ?(EventDescription["SendNotifications"] = Undefined , False , EventDescription["SendNotifications"]); - + Parameters = New Structure; - Parameters.Insert("summary" , EventDescription["Title"]); + Parameters.Insert("summary" , EventDescription["Title"]); Parameters.Insert("description", EventDescription["Description"]); - Parameters.Insert("location" , EventDescription["Venue"]); - Parameters.Insert("start" , ConvertDate(Date0)); - Parameters.Insert("end" , ConvertDate(Date1)); - Parameters.Insert("attachments", Attachments); - - URLParameters = New Structure; - URLParameters.Insert("sendUpdates" , ?(Notifications, "all", "none")); + Parameters.Insert("location" , EventDescription["Venue"]); + Parameters.Insert("start" , ConvertDate(Date0)); + Parameters.Insert("end" , ConvertDate(Date1)); + Parameters.Insert("attachments", Attachments); + + URLParameters = New Structure; + URLParameters.Insert("sendUpdates" , ?(Notifications , "all" , "none")); URLParameters.Insert("supportsAttachments" , ?(ValueIsFilled(Attachments), "true", "false")); - + URL = URL + OPI_Tools.RequestParametersToString(URLParameters); - + OPI_Tools.RemoveEmptyCollectionFields(Parameters); - + If Existing Then Response = OPI_Tools.Patch(URL, Parameters, Headers, True); Else Response = OPI_Tools.Post(URL, Parameters, Headers, True); EndIf; - + Return Response; EndFunction -Procedure GetCalendarsListRecursively(Val Headers, ArrayOfCalendars, Page = "") - - Items = "items"; - NPT = "nextPageToken"; +Procedure GetCalendarsListRecursively(Val Headers, ArrayOfCalendars, Page = "") + + Items = "items"; + NPT = "nextPageToken"; Parameters = New Structure; - + If ValueIsFilled(Page) Then Parameters.Insert("pageToken", Page); EndIf; - + Result = OPI_Tools.Get("https://www.googleapis.com/calendar/v3/users/me/calendarList" , Parameters , Headers); - + Calendars = Result[Items]; - Page = Result[NPT]; - + Page = Result[NPT]; + For Each Calendar In Calendars Do - ArrayOfCalendars.Add(Calendar); - EndDo; - + ArrayOfCalendars.Add(Calendar); + EndDo; + If Calendars.Count() > 0 And ValueIsFilled(Page) Then - GetCalendarsListRecursively(Headers, ArrayOfCalendars, Page); + GetCalendarsListRecursively(Headers, ArrayOfCalendars, Page); EndIf; - + EndProcedure -Procedure GetEventsListRecursively(Val Headers, Val Calendar, ArrayOfEvents, Page = "") - - Items = "items"; - NPT = "nextPageToken"; +Procedure GetEventsListRecursively(Val Headers, Val Calendar, ArrayOfEvents, Page = "") + + Items = "items"; + NPT = "nextPageToken"; Parameters = New Structure; - + If ValueIsFilled(Page) Then Parameters.Insert("pageToken", Page); EndIf; - + Result = OPI_Tools.Get("https://www.googleapis.com/calendar/v3/calendars/" + Calendar + "/events" , Parameters , Headers); - + Events = Result[Items]; - Page = Result[NPT]; - + Page = Result[NPT]; + For Each Event In Events Do - ArrayOfEvents.Add(Event); - EndDo; - + ArrayOfEvents.Add(Event); + EndDo; + If Events.Count() > 0 And ValueIsFilled(Page) Then - GetEventsListRecursively(Headers, ArrayOfEvents, Page); + GetEventsListRecursively(Headers, ArrayOfEvents, Page); EndIf; - + EndProcedure #EndRegion diff --git a/src/en/OPI/src/CommonModules/OPI_GoogleDrive/Module.bsl b/src/en/OPI/src/CommonModules/OPI_GoogleDrive/Module.bsl index c8c9ac1955..1a5ba559f9 100644 --- a/src/en/OPI/src/CommonModules/OPI_GoogleDrive/Module.bsl +++ b/src/en/OPI/src/CommonModules/OPI_GoogleDrive/Module.bsl @@ -43,277 +43,277 @@ // Get object information // Gets information about a folder or file by ID -// +// // Parameters: // Token - String - Token - token // Identifier - String - Identifier of the file or folder - object -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function GetObjectInformation(Val Token, Val Identifier) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Identifier); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/drive/v3/files/" + Identifier; - + URL = "https://www.googleapis.com/drive/v3/files/" + Identifier; + Parameters = New Structure; Parameters.Insert("fields", "*"); - + Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; EndFunction // Get list of directories // Gets the list of drive directories -// +// // Parameters: // Token - String - Token - token // NameContains - String - Filter by name - querry // Detailed - Boolean - Adds a list of files to the directory fields - depth -// +// // Returns: // Map Of KeyAndValue - Array of directory mappings Function GetDirectoriesList(Val Token, Val NameContains = "", Val Detailed = False) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(NameContains); OPI_TypeConversion.GetBoolean(Detailed); - - Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); + + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); ArrayOfObjects = New Array; - Filter = New Array; - + Filter = New Array; + Filter.Add("mimeType = 'application/vnd.google-apps.folder'"); - + If ValueIsFilled(NameContains) Then Filter.Add("name contains '" + NameContains + "'"); EndIf; - + GetObjectsListRecursively(Headers, ArrayOfObjects, Detailed, Filter); - + If Detailed Then - BreakDownObjectsInDetail(Token, ArrayOfObjects); + BreakDownObjectsInDetail(Token, ArrayOfObjects); EndIf; - + Return ArrayOfObjects; - + EndFunction // Get list of files // Gets the list of files -// +// // Parameters: // Token - String - Token - token // NameContains - String - Filter by name - querry // Directory - String - Filter by parent directory ID - catalog -// +// // Returns: // Map Of KeyAndValue - Array of file mappings Function GetFilesList(Val Token, Val NameContains = "", Val Directory = "") Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(NameContains); OPI_TypeConversion.GetLine(Directory); - - Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); + + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); ArrayOfObjects = New Array; - Filter = New Array; - + Filter = New Array; + Filter.Add("mimeType != 'application/vnd.google-apps.folder'"); - + If ValueIsFilled(NameContains) Then Filter.Add("name contains '" + NameContains + "'"); EndIf; - + If ValueIsFilled(Directory) Then Filter.Add("'" + Directory + "' in parents"); EndIf; - + GetObjectsListRecursively(Headers, ArrayOfObjects, , Filter); - + Return ArrayOfObjects; EndFunction // Upload file // Uploads a file to the drive -// +// // Parameters: // Token - String - Token - token // File - BinaryData,String - File to be uploaded - file // Description - Map Of KeyAndValue - See GetFileDescription - props - JSON description or path to .json -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function UploadFile(Val Token, Val File, Val Description) Export - - Return FileManagement(Token, File, Description); - + + Return FileManagement(Token, File, Description); + EndFunction // Create folder // Creates an empty directory on the drive -// +// // Parameters: // Token - String - Token - token // Name - String - Folder name - title // Parent - String - Parent - catalog -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function CreateFolder(Val Token, Val Name, Val Parent = "") Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Name); OPI_TypeConversion.GetLine(Parent); - + Description = New Map; - Description.Insert("MIME" , "application/vnd.google-apps.folder"); - Description.Insert("Name" , Name); + Description.Insert("MIME" , "application/vnd.google-apps.folder"); + Description.Insert("Name" , Name); Description.Insert("Description", ""); - Description.Insert("Parent", ?(ValueIsFilled(Parent), Parent, "root")); - + Description.Insert("Parent" , ?(ValueIsFilled(Parent), Parent, "root")); + Return FileManagement(Token, , Description); - + EndFunction // Download file // Gets file by ID -// +// // Parameters: // Token - String - Token - token // Identifier - String - File identifier - object -// SavePath - String - File save path - out -// +// SavePath - String - File save path - out +// // Returns: // BinaryData,String - Binary data or file path when SavePath parameter is specified Function DownloadFile(Val Token, Val Identifier, Val SavePath = "") Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Identifier); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/drive/v3/files/" + Identifier; - + URL = "https://www.googleapis.com/drive/v3/files/" + Identifier; + Parameters = New Map; Parameters.Insert("alt", "media"); - + Response = OPI_Tools.Get(URL, Parameters , Headers, SavePath); - + Return Response; EndFunction // Copy object // Copies file or directory -// +// // Parameters: // Token - String - Token - token // Identifier - String - Object identifier - object // NewName - String - New object name - title // NewParent - String - New parent directory - catalog -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function CopyObject(Val Token, Val Identifier, Val NewName = "", Val NewParent = "") Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(NewName); OPI_TypeConversion.GetLine(Identifier); OPI_TypeConversion.GetLine(NewParent); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/drive/v3/files/" + Identifier + "/copy"; - + URL = "https://www.googleapis.com/drive/v3/files/" + Identifier + "/copy"; + Parameters = New Structure; - + If ValueIsFilled(NewName) Then Parameters.Insert("name", NewName); EndIf; - + If ValueIsFilled(NewParent) Then - + ArrayOfParents = New Array; ArrayOfParents.Add(NewParent); Parameters.Insert("parents", ArrayOfParents); - + EndIf; - + Response = OPI_Tools.Post(URL, Parameters , Headers, True); - + Return Response; EndFunction // Update file // Updates file binary data -// +// // Parameters: // Token - String - Token - token // Identifier - String - Identifier of the object to update - object // File - BinaryData,String - File source for update - file // NewName - String - New file name (if necessary) - title -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function UpdateFile(Val Token, Val Identifier, Val File, Val NewName = "") Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Identifier); OPI_TypeConversion.GetLine(NewName); OPI_TypeConversion.GetBinaryData(File); - + If ValueIsFilled(NewName) Then Description = New Map; Description.Insert("Name", NewName); Else Description = ""; EndIf; - + Return FileManagement(Token, File, Description, Identifier); - + EndFunction // Delete object // Deletes file or directory by ID -// +// // Parameters: // Token - String - Token - token // Identifier - String - Identifier of the object to delete - object -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function DeleteObject(Val Token, Val Identifier) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Identifier); - - Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/drive/v3/files/" + Identifier; + + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); + URL = "https://www.googleapis.com/drive/v3/files/" + Identifier; Response = OPI_Tools.Delete(URL, , Headers); - + Return Response; EndFunction // Get file description !NOCLI -// +// // Returns: // Map Of KeyAndValue - File description Function GetFileDescription() Export - + Description = New Map; - Description.Insert("MIME" , "image/jpeg"); // MIME-type uploading file - Description.Insert("Name" , "New file.jpg"); // File name with extension + Description.Insert("MIME" , "image/jpeg"); // MIME-type uploading file + Description.Insert("Name" , "New file.jpg"); // File name with extension Description.Insert("Description" , "This is a new file"); // File description - Description.Insert("Parent" , "root"); // ID directory upload or "root" for upload in root - + Description.Insert("Parent" , "root"); // ID directory upload or "root" for upload in root + Return Description; - + EndFunction #EndRegion @@ -322,107 +322,107 @@ EndFunction // Create comment // Creates a comment for a file or directory -// +// // Parameters: // Token - String - Token - token -// Identifier - String - Identifier of the object that needs a comment - object +// Identifier - String - Identifier of the object that needs a comment - object // Comment - String - Comment text - text -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function CreateComment(Val Token, Val Identifier, Val Comment) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Identifier); OPI_TypeConversion.GetLine(Comment); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/drive/v3/files/" + Identifier + "/comments?fields=*"; - + URL = "https://www.googleapis.com/drive/v3/files/" + Identifier + "/comments?fields =*"; + Parameters = New Structure; Parameters.Insert("content", Comment); - + Response = OPI_Tools.POST(URL, Parameters, Headers); - + Return Response; EndFunction // Get comment // Gets comment by ID -// +// // Parameters: // Token - String - Token - token // ObjectID - String - Identifier of the file or directory where the comment is located - object // CommentID - String - Comment identifier - comment -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function GetComment(Val Token, Val ObjectID, Val CommentID) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(ObjectID); OPI_TypeConversion.GetLine(CommentID); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/drive/v3/files/" + ObjectID + "/comments/" + CommentID; - + URL = "https://www.googleapis.com/drive/v3/files/" + ObjectID + "/comments/" + CommentID; + Parameters = New Structure; Parameters.Insert("fields", "*"); - + Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; EndFunction // Get list of comments // Gets the list of all comments of the object -// +// // Parameters: // Token - String - Token - token // ObjectID - String - Object identifier - object -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function GetCommentList(Val Token, Val ObjectID) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(ObjectID); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/drive/v3/files/" + ObjectID + "/comments"; - + URL = "https://www.googleapis.com/drive/v3/files/" + ObjectID + "/comments"; + Parameters = New Structure; Parameters.Insert("fields", "*"); - + Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; EndFunction // Delete comment // Deletes comment by ID -// +// // Parameters: // Token - String - Token - token // ObjectID - String - Identifier of the file or directory where the comment is located - object // CommentID - String - Comment identifier - comment -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function DeleteComment(Val Token, Val ObjectID, Val CommentID) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(ObjectID); OPI_TypeConversion.GetLine(CommentID); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://www.googleapis.com/drive/v3/files/" + ObjectID + "/comments/" + CommentID; - + URL = "https://www.googleapis.com/drive/v3/files/" + ObjectID + "/comments/" + CommentID; + Response = OPI_Tools.Delete(URL, , Headers); - + Return Response; EndFunction @@ -433,294 +433,294 @@ EndFunction #Region Private -Procedure GetObjectsListRecursively(Val Headers, ArrayOfObjects, Detailed = False, Filter = "", Page = "") - - URL = "https://www.googleapis.com/drive/v3/files"; - Files = "files"; - NPT = "nextPageToken"; +Procedure GetObjectsListRecursively(Val Headers, ArrayOfObjects, Detailed = False, Filter = "", Page = "") + + URL = "https://www.googleapis.com/drive/v3/files"; + Files = "files"; + NPT = "nextPageToken"; Parameters = New Structure; Parameters.Insert("fields", "*"); - + If ValueIsFilled(Page) Then Parameters.Insert("pageToken", Page); EndIf; - - If ValueIsFilled(Filter) And TypeOf(Filter) = Type("Array") Then + + If ValueIsFilled(Filter) And TypeOf(Filter) = Type("Array") Then FilterString = StrConcat(Filter, " and "); - Parameters.Insert("q", FilterString); + Parameters.Insert("q", FilterString); EndIf; - + Result = OPI_Tools.Get(URL, Parameters, Headers); - + Objects = Result[Files]; - Page = Result[NPT]; - + Page = Result[NPT]; + For Each CurrentObject In Objects Do ArrayOfObjects.Add(CurrentObject); - EndDo; - + EndDo; + If Objects.Count() > 0 And ValueIsFilled(Page) Then - GetObjectsListRecursively(Headers, ArrayOfObjects, Detailed, Filter, Page); + GetObjectsListRecursively(Headers, ArrayOfObjects, Detailed, Filter, Page); EndIf; - + EndProcedure -Procedure BreakDownObjectsInDetail(Val Token, ArrayOfObjects) - +Procedure BreakDownObjectsInDetail(Val Token, ArrayOfObjects) + For Each CurrentObject In ArrayOfObjects Do - + ArrayOfFiles = New Array; - CurrentID = CurrentObject["id"]; - + CurrentID = CurrentObject["id"]; + Result = GetFilesList(Token, , CurrentID); - + For Each File In Result Do - ArrayOfFiles.Add(File); + ArrayOfFiles.Add(File); EndDo; - + CurrentObject.Insert("files", ArrayOfFiles); - + EndDo; - + EndProcedure Procedure FormFileUploadParameters(Description) - + FormedDescription = New Map; OPI_Tools.RemoveEmptyCollectionFields(Description); FieldMapping = New Map; - FieldMapping.Insert("MIME" , "mimeType"); - FieldMapping.Insert("Name" , "name"); + FieldMapping.Insert("MIME" , "mimeType"); + FieldMapping.Insert("Name" , "name"); FieldMapping.Insert("Description" , "description"); - FieldMapping.Insert("Parent" , "parents"); - FieldMapping.Insert("Extension", "fileExtension"); - + FieldMapping.Insert("Parent" , "parents"); + FieldMapping.Insert("Extension" , "fileExtension"); + For Each Element In Description Do - + If Element.Key = "Parent" Then - + CurrentValue = New Array; CurrentValue.Add(Element.Value); - + Else - + CurrentValue = Element.Value; - + EndIf; - + FieldName = FieldMapping.Get(Element.Key); FormedDescription.Insert(FieldName, CurrentValue); - + EndDo; - + Description = FormedDescription; - + EndProcedure -Function FileManagement(Val Token, Val File = "", Val Description = "", Val Identifier = "") - +Function FileManagement(Val Token, Val File = "", Val Description = "", Val Identifier = "") + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Identifier); - + If ValueIsFilled(Description) Then OPI_TypeConversion.GetCollection(Description); EndIf; - + MimeType = "mimeType"; - + If ValueIsFilled(Identifier) Then MIME = GetObjectInformation(Token, Identifier)[MimeType]; Else MIME = Description["MIME"]; - EndIf; - + EndIf; + If Not ValueIsFilled(Description) Then Description = New Map; EndIf; - - Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); + + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); FormFileUploadParameters(Description); JSONDescription = OPI_Tools.JSONString(Description); - + FileMapping = New Map; - + If ValueIsFilled(File) Then - - ChunkSize = 268435457; - Size = OPI_Tools.ConvertDataWithSizeRetrieval(File, ChunkSize); - + + ChunkSize = 268435457; + Size = OPI_Tools.ConvertDataWithSizeRetrieval(File, ChunkSize); + FileMapping.Insert(File, MIME); - + If Size < ChunkSize And TypeOf(File) = Type("BinaryData") Then Response = UploadSmallFile(JSONDescription, FileMapping, Headers, Identifier); Else Response = UploadLargeFile(Description, FileMapping, Headers, Identifier); EndIf; - + Else - Response = UploadSmallFile(JSONDescription, FileMapping, Headers, Identifier); + Response = UploadSmallFile(JSONDescription, FileMapping, Headers, Identifier); EndIf; - + Return Response; - + EndFunction Function UploadSmallFile(Val Description, Val FileMapping, Val Headers, Val Identifier = "") - + URL = "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart"; - + If ValueIsFilled(Identifier) Then - URL = StrReplace(URL, "/files", "/files/" + Identifier); + URL = StrReplace(URL, "/files", "/files/" + Identifier); Response = OPI_Tools.PatchMultipartRelated(URL, Description, FileMapping, Headers); Else Response = OPI_Tools.PostMultipartRelated(URL, Description, FileMapping, Headers); EndIf; Return Response; - + EndFunction Function UploadLargeFile(Val Description, Val FileMapping, Val Headers, Val Identifier = "") - + For Each File In FileMapping Do Binary = File.Key; Break; EndDo; - + URL = "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable"; - + If ValueIsFilled(Identifier) Then - URL = StrReplace(URL, "/files", "/files/" + Identifier); + URL = StrReplace(URL, "/files", "/files/" + Identifier); Response = OPI_Tools.Patch(URL, Description, Headers, True, True); Else Response = OPI_Tools.Post(URL, Description, Headers, True, True); EndIf; - + UploadURL = Response.Headers["Location"]; - + If Not ValueIsFilled(UploadURL) Then OPI_Tools.ProcessResponse(Response); Return Response; EndIf; - + UploadResponse = UploadFileInParts(Binary, UploadURL); - Response = ?(ValueIsFilled(UploadResponse), UploadResponse, Response); - + Response = ?(ValueIsFilled(UploadResponse), UploadResponse, Response); + OPI_Tools.ProcessResponse(Response); Return Response; - + EndFunction Function UploadFileInParts(Val Binary, Val UploadURL) - - Response = ""; - ChunkSize = 268435456; - BytesRead = 0; + + Response = ""; + ChunkSize = 268435456; + BytesRead = 0; CurrentPosition = 0; - TotalSize = Binary.Size(); - StrTotalSize = OPI_Tools.NumberToString(TotalSize); - DataReader = New DataReader(Binary); - SourceStream = DataReader.SourceStream(); - + TotalSize = Binary.Size(); + StrTotalSize = OPI_Tools.NumberToString(TotalSize); + DataReader = New DataReader(Binary); + SourceStream = DataReader.SourceStream(); + WHile BytesRead < TotalSize Do - - BytesRead = SourceStream.CurrentPosition(); - Result = DataReader.Read(ChunkSize); - CurrentData = Result.GetBinaryData(); - CurrentSize = CurrentData.Size(); - NextPosition = CurrentPosition + CurrentSize - 1; - + + BytesRead = SourceStream.CurrentPosition(); + Result = DataReader.Read(ChunkSize); + CurrentData = Result.GetBinaryData(); + CurrentSize = CurrentData.Size(); + NextPosition = CurrentPosition + CurrentSize - 1; + If Not ValueIsFilled(CurrentData) Then Break; EndIf; - + StreamHeader = "bytes " + OPI_Tools.NumberToString(CurrentPosition) - + "-" - + OPI_Tools.NumberToString(NextPosition) - + "/" + + "-" + + OPI_Tools.NumberToString(NextPosition) + + "/" + StrTotalSize; - + AdditionalHeaders = New Map; AdditionalHeaders.Insert("Content-Length", OPI_Tools.NumberToString(CurrentSize)); - AdditionalHeaders.Insert("Content-Range" , StreamHeader); - AdditionalHeaders.Insert("Content-Type" , "application/octet-stream"); - + AdditionalHeaders.Insert("Content-Range" , StreamHeader); + AdditionalHeaders.Insert("Content-Type" , "application/octet-stream"); + Response = OPI_Tools.Put(UploadURL, CurrentData, AdditionalHeaders, False, True); - + CheckResult = CheckPartUpload(Response, StrTotalSize, AdditionalHeaders, UploadURL, CurrentPosition); - + If ValueIsFilled(CheckResult) Then Return CheckResult; EndIf; - + // !OInt KB = 1024; // !OInt MB = KB * KB; // !OInt Message(OPI_Tools.ProgressInfo(CurrentPosition, TotalSize, "MB", MB)); - + // !OInt RunGarbageCollection(); // !OInt FreeObject(CurrentData); - + EndDo; - + Return Response; - + EndFunction Function CheckPartUpload(Response, StrTotalSize, AdditionalHeaders, UploadURL, CurrentPosition) - - StartOfErrorCodes = 400; - EndOfFailureCodes = 600; + + StartOfErrorCodes = 400; + EndOfFailureCodes = 600; StartOfSuccessCodes = 200; - EndOfSuccessCodes = 300; - Redirection = 308; - + EndOfSuccessCodes = 300; + Redirection = 308; + If Response.StatusCode >= StartOfErrorCodes And Response.StatusCode < EndOfFailureCodes Then - + StreamHeader = "bytes */" + StrTotalSize; AdditionalHeaders.Insert("Content-Range" , StreamHeader); - + CheckResponse = OPI_Tools.Put(UploadURL, "", AdditionalHeaders, False, True); - + If CheckResponse.StatusCode >= StartOfSuccessCodes And CheckResponse.StatusCode < EndOfSuccessCodes Then - + OPI_Tools.ProcessResponse(CheckResponse); Return CheckResponse; - + ElsIf CheckResponse.StatusCode = Redirection Then - + UploadedData = Response.Headers["Range"]; - + Else - + OPI_Tools.ProcessResponse(Response); Return Response; - + EndIf; - + Else UploadedData = Response.Headers["Range"]; EndIf; - + If Not ValueIsFilled(UploadedData) Then OPI_Tools.ProcessResponse(Response); Return Response; EndIf; - - UploadedData = StrReplace(UploadedData, "bytes=", ""); + + UploadedData = StrReplace(UploadedData, "bytes =", ""); ArrayOfInformation = StrSplit(UploadedData, "-", False); - PartsRequired = 2; - + PartsRequired = 2; + If Not ArrayOfInformation.Count() = PartsRequired Then OPI_Tools.ProcessResponse(Response); Return Response; EndIf; - + CurrentPosition = Number(ArrayOfInformation[1]) + 1; - + Return ""; - + EndFunction #EndRegion diff --git a/src/en/OPI/src/CommonModules/OPI_GoogleSheets/Module.bsl b/src/en/OPI/src/CommonModules/OPI_GoogleSheets/Module.bsl index 843fc819ea..9e01ba842b 100644 --- a/src/en/OPI/src/CommonModules/OPI_GoogleSheets/Module.bsl +++ b/src/en/OPI/src/CommonModules/OPI_GoogleSheets/Module.bsl @@ -43,90 +43,90 @@ // Create spreadsheet // Creates a new spreadsheet -// +// // Parameters: // Token - String - Token - token // Name - String - Name - title // ArrayOfSheetNames - Array of String - Array of names to add new sheets to the spreadsheet - sheets -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function CreateSpreadsheet(Val Token, Val Name, Val ArrayOfSheetNames) Export - + OPI_TypeConversion.GetLine(Name); OPI_TypeConversion.GetCollection(ArrayOfSheetNames); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://sheets.googleapis.com/v4/spreadsheets"; - + URL = "https://sheets.googleapis.com/v4/spreadsheets"; + Properties = New Structure("title" , Name); - Sheets = New Array; - + Sheets = New Array; + FillSheetArray(ArrayOfSheetNames, Sheets); - + Parameters = New Structure; OPI_Tools.AddField("properties", Properties, "Collection", Parameters); - OPI_Tools.AddField("sheets" , Sheets , "Collection", Parameters); - + OPI_Tools.AddField("sheets" , Sheets , "Collection", Parameters); + Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction // Get spreadsheet // Gets information about the spreadsheet by ID -// +// // Parameters: // Token - String - Token - token // Identifier - String - Spreadsheet identifier - spreadsheet -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function GetSpreadsheet(Val Token, Val Identifier) Export - OPI_TypeConversion.GetLine(Identifier); - + OPI_TypeConversion.GetLine(Identifier); + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Identifier; - + URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Identifier; + Response = OPI_Tools.Get(URL, , Headers); - + Return Response; EndFunction // Change spreadsheet name // Changes the name of the existing spreadsheet -// +// // Parameters: // Token - String - Token - token // Spreadsheet - String - SpreadsheetID - spreadsheet // Name - String - New name - title -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function EditSpreadsheetTitle(Val Token, Val Spreadsheet, Val Name) Export - + OPI_TypeConversion.GetLine(Spreadsheet); OPI_TypeConversion.GetLine(Name); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Spreadsheet + ":batchUpdate"; - - Change = New Structure("title", Name); + URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Spreadsheet + ":batchUpdate"; + + Change = New Structure("title", Name); ChangeRequest = New Structure("properties,fields", Change, "title"); - Request = New Structure("updateSpreadsheetProperties", ChangeRequest); - + Request = New Structure("updateSpreadsheetProperties", ChangeRequest); + ArrayOfRequests = New Array; ArrayOfRequests.Add(Request); - + Parameters = New Structure("requests", ArrayOfRequests); - + Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction #EndRegion @@ -135,95 +135,95 @@ EndFunction // Add sheet // Adds a new sheet to the spreadsheet -// -// +// +// // Parameters: // Token - String - Token - token // Spreadsheet - String - Spreadsheet identifier - spreadsheet // Name - String - NewSheetName - title -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function AddSheet(Val Token, Val Spreadsheet, Val Name) Export - + OPI_TypeConversion.GetLine(Spreadsheet); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Spreadsheet + ":batchUpdate"; - Sheet = CreateSheet(Name); - + URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Spreadsheet + ":batchUpdate"; + Sheet = CreateSheet(Name); + Requests = New Array; - Change = New Structure("addSheet", Sheet); + Change = New Structure("addSheet", Sheet); Requests.Add(Change); - + Parameters = New Structure("requests", Requests); - + Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction // Delete sheet // Deletes a sheet from the spreadsheet -// +// // Parameters: // Token - String - Token - token // Spreadsheet - String - Spreadsheet identifier - spreadsheet // Sheet - String - IdentifierOfSheetToDelete - sheet -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function DeleteSheet(Val Token, Val Spreadsheet, Val Sheet) Export - + OPI_TypeConversion.GetLine(Spreadsheet); OPI_TypeConversion.GetLine(Sheet); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Spreadsheet + ":batchUpdate"; - + URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Spreadsheet + ":batchUpdate"; + Requests = New Array; - Sheet = New Structure("sheetId" , Sheet); - Change = New Structure("deleteSheet", Sheet); + Sheet = New Structure("sheetId" , Sheet); + Change = New Structure("deleteSheet", Sheet); Requests.Add(Change); - + Parameters = New Structure("requests", Requests); - + Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction // Copy sheet // Copies a sheet from one spreadsheet to another -// +// // Parameters: // Token - String - Token - token // From - String - Source spreadsheet ID - from // Target - String - Destination spreadsheet ID - to // Sheet - String - CopiedSheetID - sheet -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function CopySheet(Val Token, Val From, Val Target, Val Sheet) Export - + OPI_TypeConversion.GetLine(From); OPI_TypeConversion.GetLine(Target); OPI_TypeConversion.GetLine(Sheet); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://sheets.googleapis.com/v4/spreadsheets/" + URL = "https://sheets.googleapis.com/v4/spreadsheets/" + From + "/sheets/" + Sheet + ":copyTo"; - - Parameters = New Structure("destinationSpreadsheetId", Target); - Response = OPI_Tools.Post(URL, Parameters, Headers); - + + Parameters = New Structure("destinationSpreadsheetId", Target); + Response = OPI_Tools.Post(URL, Parameters, Headers); + Return Response; - + EndFunction #EndRegion @@ -232,14 +232,14 @@ EndFunction // Set cell values // Sets sheet cell values -// +// // Parameters: // Token - String - Token - token -// Spreadsheet - String - SpreadsheetID - spreadsheet +// Spreadsheet - String - SpreadsheetID - spreadsheet // ValueMapping - Map Of KeyAndValue - Fill data where the key is the cell name like A1 - data // Sheet - String - Sheet name (first sheet by default) - sheetname // MajorDimension - String - Main dimension when filling the array range - dim -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function SetCellValues(Val Token @@ -247,90 +247,90 @@ Function SetCellValues(Val Token , Val ValueMapping , Val Sheet = "" , Val MajorDimension = "COLUMNS") Export - + OPI_TypeConversion.GetLine(Spreadsheet); OPI_TypeConversion.GetCollection(ValueMapping); - - If Not TypeOf(ValueMapping) = Type("Structure") + + If Not TypeOf(ValueMapping) = Type("Structure") And Not TypeOf(ValueMapping) = Type("Map") Then Return "Failed to convert the structure of values to a collection"; EndIf; - - Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Spreadsheet + "/values:batchUpdate"; + + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); + URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Spreadsheet + "/values:batchUpdate"; DataArray = FormCellDataArray(ValueMapping, MajorDimension, Sheet); Parameters = New Structure("data,valueInputOption", DataArray, "USER_ENTERED"); - Response = OPI_Tools.Post(URL, Parameters, Headers); - + Response = OPI_Tools.Post(URL, Parameters, Headers); + Return Response; - + EndFunction // Clear cells // Clears the value in cells -// +// // Parameters: // Token - String - Token - token // Spreadsheet - String - SpreadsheetID - spreadsheet // CellsArray - Array of String - Array of cells like A1 to be cleared - cells // Sheet - String - Sheet name (first sheet by default) - sheetname -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function ClearCells(Val Token, Val Spreadsheet, Val CellsArray, Val Sheet = "") Export - + OPI_TypeConversion.GetLine(Spreadsheet); OPI_TypeConversion.GetCollection(CellsArray); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Spreadsheet + "/values:batchClear"; - + URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Spreadsheet + "/values:batchClear"; + FormCellNameArray(CellsArray, Sheet); - + Parameters = New Structure("ranges", CellsArray); - Response = OPI_Tools.Post(URL, Parameters, Headers); - + Response = OPI_Tools.Post(URL, Parameters, Headers); + Return Response; - + EndFunction // Get cell values // Gets cell values of the table -// +// // Parameters: // Token - String - Token - token // Spreadsheet - String - SpreadsheetID - spreadsheet // CellsArray - Array of String - Array of A1 type cells to get (whole sheet if not filled) - cells // Sheet - String - Sheet name (first sheet by default) - sheetname -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function GetCellValues(Val Token, Val Spreadsheet, Val CellsArray = "", Val Sheet = "") Export - + OPI_TypeConversion.GetLine(Spreadsheet); - + Headers = OPI_GoogleWorkspace.GetAuthorizationHeader(Token); - URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Spreadsheet + "/values:batchGet"; - + URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Spreadsheet + "/values:batchGet"; + If ValueIsFilled(CellsArray) Then - OPI_TypeConversion.GetCollection(CellsArray); + OPI_TypeConversion.GetCollection(CellsArray); FormCellNameArray(CellsArray, Sheet); - - First = True; + + First = True; For Each Cell In CellsArray Do Delimiter = ?(First, "?", "&"); - URL = URL + Delimiter + "ranges=" + Cell; - First = False; + URL = URL + Delimiter + "ranges =" + Cell; + First = False; EndDo; Else - URL = URL + "?ranges='" + Sheet + "'"; + URL = URL + "?ranges ='" + Sheet + "'"; EndIf; - + Response = OPI_Tools.Get(URL, , Headers); - + Return Response; - + EndFunction #EndRegion @@ -340,75 +340,75 @@ EndFunction #Region Private Procedure FillSheetArray(Val ArrayOfNames, SheetArray) - + For Each SheetName In ArrayOfNames Do - + Sheet = CreateSheet(SheetName); SheetArray.Add(Sheet); - + EndDo; EndProcedure Procedure AddSheetName(Cell, Val Sheet) - + If ValueIsFilled(Sheet) Then Cell = "'" + Sheet + "'!" + Cell; EndIf; - + EndProcedure Function CreateSheet(Val Name) - + OPI_TypeConversion.GetLine(Name); - + SheetProperties = New Structure("title" , Name); - Sheet = New Structure("properties", SheetProperties); + Sheet = New Structure("properties", SheetProperties); Return Sheet; - + EndFunction Function FormCellDataArray(Val ValueStructure, Val MajorDimension, Val Sheet) - + OPI_TypeConversion.GetLine(Sheet); - + DataArray = New Array; - + For Each CellData In ValueStructure Do - + CurrentValue = CellData.Value; - CurrentKey = CellData.Key; - + CurrentKey = CellData.Key; + AddSheetName(CurrentKey, Sheet); - + OPI_TypeConversion.GetArray(CurrentValue); - - CurrentData = New Map; + + CurrentData = New Map; CurrentArray = New Array; - + CurrentArray.Add(CurrentValue); - - OPI_Tools.AddField("range" , CurrentKey , "String", CurrentData); - OPI_Tools.AddField("values" , CurrentArray , "Array", CurrentData); + + OPI_Tools.AddField("range" , CurrentKey , "String", CurrentData); + OPI_Tools.AddField("values" , CurrentArray , "Array" , CurrentData); OPI_Tools.AddField("majorDimension", MajorDimension, "String", CurrentData); - + DataArray.Add(CurrentData); - + EndDo; - + Return DataArray; - + EndFunction Procedure FormCellNameArray(Val ArrayOfNames, Val Sheet) - OPI_TypeConversion.GetLine(Sheet); - - For N = 0 To ArrayOfNames.UBound() Do + OPI_TypeConversion.GetLine(Sheet); + + For N = 0 To ArrayOfNames.UBound() Do AddSheetName(ArrayOfNames[N], Sheet); EndDo; - + EndProcedure #EndRegion diff --git a/src/en/OPI/src/CommonModules/OPI_GoogleWorkspace/Module.bsl b/src/en/OPI/src/CommonModules/OPI_GoogleWorkspace/Module.bsl index 4a586a56ff..524cbae01a 100644 --- a/src/en/OPI/src/CommonModules/OPI_GoogleWorkspace/Module.bsl +++ b/src/en/OPI/src/CommonModules/OPI_GoogleWorkspace/Module.bsl @@ -41,97 +41,97 @@ // Generate code retrieval link // Returns URL for browser authorization -// +// // Parameters: // ClientID - String - Client ID - id // Calendar - Boolean - Calendar methods permission - calendar // Drive - Boolean - Drive methods permission - drive // Sheets - Boolean - Sheets methods permission - sheets -// +// // Returns: // String - Code retrieval link Function FormCodeRetrievalLink(Val ClientID , Val Calendar = True , Val Drive = True , Val Sheets = True) Export - + OPI_TypeConversion.GetLine(ClientID); OPI_TypeConversion.GetBoolean(Calendar); OPI_TypeConversion.GetBoolean(Sheets); OPI_TypeConversion.GetBoolean(Drive); - + URL = "https://accounts.google.com/o/oauth2/auth"; - + URLParameters = New Structure; URLParameters.Insert("response_type", "code"); - URLParameters.Insert("client_id" , ClientID); + URLParameters.Insert("client_id" , ClientID); URLParameters.Insert("redirect_uri" , "http://localhost"); - URLParameters.Insert("access_type" , "offline"); - URLParameters.Insert("scope" , GetPermissionsList(Calendar, Drive, Sheets)); - + URLParameters.Insert("access_type" , "offline"); + URLParameters.Insert("scope" , GetPermissionsList(Calendar, Drive, Sheets)); + URL = URL + OPI_Tools.RequestParametersToString(URLParameters); - + Return URL; - + EndFunction // Get token by code // Gets token by code from browser authorization -// +// // Parameters: // ClientID - String - Client ID - id // ClientSecret - String - Client secret - secret // Code - String - Code from browser - code -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function GetTokenByCode(Val ClientID, Val ClientSecret, Val Code) Export - + OPI_TypeConversion.GetLine(ClientID); OPI_TypeConversion.GetLine(ClientSecret); OPI_TypeConversion.GetLine(Code); - + URL = "https://accounts.google.com/o/oauth2/token"; - + URLParameters = New Structure; - URLParameters.Insert("grant_type" , "authorization_code"); - URLParameters.Insert("client_id" , ClientID); + URLParameters.Insert("grant_type" , "authorization_code"); + URLParameters.Insert("client_id" , ClientID); URLParameters.Insert("client_secret", ClientSecret); - URLParameters.Insert("redirect_uri" , "http://localhost"); - URLParameters.Insert("code" , Code); - + URLParameters.Insert("redirect_uri" , "http://localhost"); + URLParameters.Insert("code" , Code); + Response = OPI_Tools.Post(URL, URLParameters, , False); - + Return Response; EndFunction // Refresh token // Updates token by Refresh token -// +// // Parameters: // ClientID - String - Client ID - id // ClientSecret - String - Client secret - secret // RefreshToken - String - Refresh token - refresh -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Google Function RefreshToken(Val ClientID, Val ClientSecret, Val RefreshToken) Export - + OPI_TypeConversion.GetLine(ClientID); OPI_TypeConversion.GetLine(ClientSecret); OPI_TypeConversion.GetLine(RefreshToken); - + URL = "https://accounts.google.com/o/oauth2/token"; - + URLParameters = New Structure; - URLParameters.Insert("grant_type" , "refresh_token"); - URLParameters.Insert("client_id" , ClientID); - URLParameters.Insert("client_secret", ClientSecret); + URLParameters.Insert("grant_type" , "refresh_token"); + URLParameters.Insert("client_id" , ClientID); + URLParameters.Insert("client_secret", ClientSecret); URLParameters.Insert("refresh_token", RefreshToken); - + Response = OPI_Tools.Post(URL, URLParameters, , False); - + Return Response; EndFunction @@ -141,14 +141,14 @@ EndFunction #Region Internal Function GetAuthorizationHeader(Val Token) Export - + OPI_TypeConversion.GetLine(Token); - + Headers = New Map; Headers.Insert("Authorization", "Bearer " + Token); - + Return Headers; - + EndFunction #EndRegion @@ -156,23 +156,23 @@ EndFunction #Region ServiceProceduresAndFunctions Function GetPermissionsList(Calendar, Drive, Sheets) - + PermissionsArray = New Array; - + If Calendar Then PermissionsArray.Add("https://www.googleapis.com/auth/calendar"); EndIf; - + If Drive Then PermissionsArray.Add("https://www.googleapis.com/auth/drive"); EndIf; - + If Sheets Then PermissionsArray.Add("https://www.googleapis.com/auth/spreadsheets"); EndIf; - + Return StrConcat(PermissionsArray, " "); - + EndFunction #EndRegion diff --git a/src/en/OPI/src/CommonModules/OPI_Notion/Module.bsl b/src/en/OPI/src/CommonModules/OPI_Notion/Module.bsl index fa4fdf6fd1..3994f25f52 100644 --- a/src/en/OPI/src/CommonModules/OPI_Notion/Module.bsl +++ b/src/en/OPI/src/CommonModules/OPI_Notion/Module.bsl @@ -45,91 +45,91 @@ // Create page // Creates a child page above another parent page -// +// // Parameters: // Token - String - Token - token // Parent - String - Parent ID - page // Title - String - Page title - title -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Notion Function CreatePage(Val Token, Val Parent, Val Title) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Parent); OPI_TypeConversion.GetLine(Title); - - Headers = CreateRequestHeaders(Token); + + Headers = CreateRequestHeaders(Token); Properties = New Structure; Parameters = New Structure; - + AddPageHeader(Title, Properties); AddPageParent(Parent, False, Parameters); - + Parameters.Insert("properties", Properties); - + Response = OPI_Tools.Post("https://api.notion.com/v1/pages", Parameters, Headers); - + Return Response; - + EndFunction // Create page in database // Creates a page in the parent database -// +// // Parameters: -// Token - String - Token - token +// Token - String - Token - token // Parent - String - Parent database ID - base // Data - Map Of KeyAndValue - Properties map - data -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Notion Function CreatePageInDatabase(Val Token, Val Parent, Val Data) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Parent); OPI_TypeConversion.GetCollection(Data); - - Headers = CreateRequestHeaders(Token); + + Headers = CreateRequestHeaders(Token); Parameters = New Structure; - + AddPageParent(Parent, True, Parameters); - Properties = FillDataBySchema(Parent, Data, Token); + Properties = FillDataBySchema(Parent, Data, Token); Parameters.Insert("properties", Properties); - + Response = OPI_Tools.Post("https://api.notion.com/v1/pages", Parameters, Headers); - + Return Response; - + EndFunction // Get page // Gets information about the page by ID -// +// // Parameters: // Token - String - Token - token -// Page - String - Page ID - page -// +// Page - String - Page ID - page +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Notion Function GetPage(Val Token, Val Page) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Page); - + Headers = CreateRequestHeaders(Token); - ConvertID(Page); - + ConvertID(Page); + Response = OPI_Tools.Get("https://api.notion.com/v1/pages/" + Page, , Headers); - + Return Response; - + EndFunction // Edit page properties // Changes the properties of an existing page -// +// // Parameters: // Token - String - Token - token // Page - String - ID of the page being modified - page @@ -137,7 +137,7 @@ EndFunction // Icon - String - URL of the page icon image - icon // Cover - String - URL of the page cover image - cover // Archived - Boolean - Archive page or not (boolean) - archive -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Notion Function EditPageProperties(Val Token @@ -146,36 +146,36 @@ Function EditPageProperties(Val Token , Val Icon = "" , Val Cover = "" , Val Archived = False) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Page); OPI_TypeConversion.GetLine(Icon); OPI_TypeConversion.GetLine(Cover); OPI_TypeConversion.GetBoolean(Archived); OPI_TypeConversion.GetCollection(Data); - - Headers = CreateRequestHeaders(Token); + + Headers = CreateRequestHeaders(Token); Parameters = New Structure; - Files = "files"; - - If ValueIsFilled(Data) + Files = "files"; + + If ValueIsFilled(Data) And (TypeOf(Data) = Type("Map") Or TypeOf(Data) = Type("Structure")) Then - Properties = FillDataBySchema(Page, Data, Token, False); - Else - Properties = New Map; + Properties = FillDataBySchema(Page, Data, Token, False); + Else + Properties = New Map; EndIf; - + If ValueIsFilled(Icon) Then IconMap = New Map; IconMap.Insert("Icon", Icon); - + IconObject = ConvertValueByType(Files, IconMap); IconObject = IconObject[Files][0]; IconObject.Delete("name"); - + Parameters.Insert("icon", IconObject); EndIf; - + If ValueIsFilled(Cover) Then CoverMap = New Map; CoverMap.Insert("Cover", Cover); @@ -188,14 +188,14 @@ Function EditPageProperties(Val Token EndIf; Parameters.Insert("properties", Properties); - Parameters.Insert("archived" , Archived); - + Parameters.Insert("archived" , Archived); + ConvertID(Page); Response = OPI_Tools.Patch("https://api.notion.com/v1/pages/" + Page, Parameters, Headers); - + Return Response; - + EndFunction #EndRegion @@ -204,13 +204,13 @@ EndFunction // Create database // Creates a database -// +// // Parameters: -// Token - String - Token - token +// Token - String - Token - token // Parent - String - Parent page ID - page // Title - String - Database title - title // Properties - Structure Of String - Database properties - props -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Notion Function CreateDatabase(Val Token, Val Parent, Val Title, Val Properties = "") Export @@ -219,273 +219,273 @@ Function CreateDatabase(Val Token, Val Parent, Val Title, Val Properties = "") E OPI_TypeConversion.GetLine(Parent); OPI_TypeConversion.GetLine(Title); OPI_TypeConversion.GetCollection(Properties); - + // Example structure/property map - + // Name : title // Description : rich_text - // InProgress : checkbox + // InProgress : checkbox // Count : number // Date : date // Status : Map // Active : green // Inactive : red // Archive : yellow - + // All pages created as children must have parent base properties If Not TypeOf(Properties) = Type("Structure") And Not TypeOf(Properties) = Type("Map") Then - Properties = New Structure("Name", "title"); + Properties = New Structure("Name", "title"); EndIf; - Headers = CreateRequestHeaders(Token); + Headers = CreateRequestHeaders(Token); Parameters = New Structure; - + AddDatabaseParent(Parent, False, Parameters); AddDatabaseHeader(Title, Parameters); AddDatabaseProperties(Properties, Parameters); Response = OPI_Tools.Post("https://api.notion.com/v1/databases", Parameters, Headers); - + Return Response; - + EndFunction // Get database // Get database information -// +// // Parameters: // Token - String - Token - token // Base - String - Database ID - base -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Notion Function GetDatabase(Val Token, Val Base) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Base); - + Headers = CreateRequestHeaders(Token); - ConvertID(Base); - + ConvertID(Base); + Response = OPI_Tools.Get("https://api.notion.com/v1/databases/" + Base, , Headers); - - Return Response; - + + Return Response; + EndFunction // Edit database properties // Edits properties of an existing database -// +// // Parameters: // Token - String - Token - token // Base - String - Target database ID - base // Properties - Map of KeyAndValue - New or modified database properties - props // Title - String - New database title - title // Description - String - New database description - description -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Notion Function EditDatabaseProperties(Val Token, Val Base, Val Properties = "", Val Title = "", Val Description = "") Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Base); OPI_TypeConversion.GetLine(Title); OPI_TypeConversion.GetLine(Description); OPI_TypeConversion.GetCollection(Properties); - + Parameters = New Structure; - Headers = CreateRequestHeaders(Token); - ConvertID(Base); - + Headers = CreateRequestHeaders(Token); + ConvertID(Base); + If ValueIsFilled(Title) Then AddDatabaseHeader(Title, Parameters); EndIf; - + If ValueIsFilled(Description) Then AddDatabaseDescription(Description, Parameters); EndIf; - + If TypeOf(Properties) = Type("Structure") Or TypeOf(Properties) = Type("Map") Then AddDatabaseProperties(Properties, Parameters); EndIf; - + Response = OPI_Tools.Patch("https://api.notion.com/v1/databases/" + Base, Parameters, Headers); - + Return Response; - + EndFunction -#EndRegion +#EndRegion #Region BlocksManagment // Create block // Creates a new block based on an existing block -// +// // Parameters: // Token - String - Token - token // Parent - String - Parent block or page ID - page // Block - String, Map Of KeyAndValue - Block ID or block sample itself - block // InsertAfter - String - Block ID after which to insert the new one - prev -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Notion Function CreateBlock(Val Token, Val Parent, Val Block, Val InsertAfter = "") Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Parent); OPI_TypeConversion.GetLine(InsertAfter); OPI_TypeConversion.GetCollection(Block); - + If TypeOf(Block) = Type("Array") Then - Block = Block[0]; + Block = Block[0]; EndIf; - - Headers = CreateRequestHeaders(Token); + + Headers = CreateRequestHeaders(Token); ConvertID(Parent); - + If TypeOf(Block) = Type("String") Then ConvertID(Block); - Block = ReturnBlock(Token, Block); + Block = ReturnBlock(Token, Block); EndIf; - + BlockArray = New Array; BlockArray.Add(Block); - + Parameters = New Map; Parameters.Insert("children", BlockArray); - + If ValueIsFilled(InsertAfter) Then Parameters.Insert("after", InsertAfter); EndIf; - - URL = "https://api.notion.com/v1/blocks/" + Parent + "/children"; + + URL = "https://api.notion.com/v1/blocks/" + Parent + "/children"; Response = OPI_Tools.Patch(URL, Parameters, Headers); - + Return Response; - + EndFunction // Return block // Returns the block structure by ID -// +// // Parameters: // Token - String - Token - token // BlockID - String - Block ID - block // OnlyBase - Boolean - True > service fields are deleted, only the block itself remains - core -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Notion Function ReturnBlock(Val Token, Val BlockID, Val OnlyBase = True) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(BlockID); OPI_TypeConversion.GetBoolean(OnlyBase); - + ConvertID(BlockID); - - Headers = CreateRequestHeaders(Token); + + Headers = CreateRequestHeaders(Token); Response = OPI_Tools.Get("https://api.notion.com/v1/blocks/" + BlockID, , Headers); - + If OnlyBase Then - RemoveExtraBlockFields(Response); + RemoveExtraBlockFields(Response); EndIf; - + Return Response; - + EndFunction // Return child blocks // Returns list of child blocks of parent block -// +// // Parameters: // Token - String - Token - token // BlockID - String - Parent block ID - block -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Notion Function ReturnChildBlocks(Val Token, Val BlockID) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(BlockID); - + ConvertID(BlockID); - - Headers = CreateRequestHeaders(Token); + + Headers = CreateRequestHeaders(Token); Response = OPI_Tools.Get("https://api.notion.com/v1/blocks/" + BlockID + "/children", , Headers); - + Return Response; - + EndFunction // Delete block // Deletes block by ID -// +// // Parameters: // Token - String - Token - token // BlockID - String - Block ID - block -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Notion Function DeleteBlock(Val Token, Val BlockID) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(BlockID); - + ConvertID(BlockID); - - Headers = CreateRequestHeaders(Token); + + Headers = CreateRequestHeaders(Token); Response = OPI_Tools.Delete("https://api.notion.com/v1/blocks/" + BlockID, , Headers); - + Return Response; - + EndFunction - + #EndRegion #Region Users // User list // Returns a list of workspace users -// +// // Parameters: // Token - String - Token - token -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Notion Function UserList(Val Token) Export OPI_TypeConversion.GetLine(Token); - - Headers = CreateRequestHeaders(Token); + + Headers = CreateRequestHeaders(Token); Response = OPI_Tools.Get("https://api.notion.com/v1/users", , Headers); - + Return Response; - + EndFunction // Get user data // Gets user data by ID -// +// // Parameters: // Token - String - Token - token // UserID - String - Target user ID - user -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Notion Function GetUserData(Val Token, Val UserID) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(UserID); - + ConvertID(UserID); - - Headers = CreateRequestHeaders(Token); + + Headers = CreateRequestHeaders(Token); Response = OPI_Tools.Get("https://api.notion.com/v1/users/" + UserID, , Headers); - + Return Response; - + EndFunction #EndRegion @@ -495,183 +495,183 @@ EndFunction #Region Private Function CreateRequestHeaders(Val Token) - + OPI_TypeConversion.GetLine(Token); - + Headers = New Map; Headers.Insert("Authorization" , "Bearer " + Token); Headers.Insert("Notion-Version", "2022-06-28"); - + Return Headers; - + EndFunction Procedure ConvertID(Identifier) - + OPI_TypeConversion.GetLine(Identifier); - + Identifier = StrReplace(Identifier, "-", ""); - + EndProcedure Procedure AddPageParent(Val Parent, Val ParentBase, MainStructure) - + OPI_TypeConversion.GetLine(ParentBase); - + ConvertID(Parent); - + IdentifierField = ?(ParentBase, "database_id", "page_id"); ParentStructure = New Structure(IdentifierField, Parent); MainStructure.Insert("parent", ParentStructure); - + EndProcedure Procedure AddDatabaseParent(Val Parent, Val ParentBase, MainStructure) - + OPI_TypeConversion.GetLine(ParentBase); - + ConvertID(Parent); - + IdentifierField = ?(ParentBase, "database_id", "page_id"); - + ParentStructure = New Structure(); - ParentStructure.Insert("type" , IdentifierField); + ParentStructure.Insert("type" , IdentifierField); ParentStructure.Insert(IdentifierField, Parent); MainStructure.Insert("parent", ParentStructure); - + EndProcedure -Procedure AddPageHeader(Val Title, MainStructure) - +Procedure AddPageHeader(Val Title, MainStructure) + OPI_TypeConversion.GetLine(Title); - + SubordinateStructure = New Structure; - DataStructure = New Structure; - TextStructure = New Structure; - DataArray = New Array; + DataStructure = New Structure; + TextStructure = New Structure; + DataArray = New Array; Title = "title"; - + TextStructure.Insert("content", Title); - TextStructure.Insert("link" , Undefined); - + TextStructure.Insert("link" , Undefined); + DataStructure.Insert("text", TextStructure); DataStructure.Insert("type", "text"); - + DataArray.Add(DataStructure); - - SubordinateStructure.Insert("id" , Title); + + SubordinateStructure.Insert("id" , Title); SubordinateStructure.Insert("type" , Title); - SubordinateStructure.Insert(Title , DataArray); - + SubordinateStructure.Insert(Title , DataArray); + MainStructure.Insert(Title, SubordinateStructure); - + EndProcedure Procedure AddDatabaseHeader(Val Title, MainStructure) - + OPI_TypeConversion.GetLine(Title); - - Title = ConvertHeader(Title); + + Title = ConvertHeader(Title); MainStructure.Insert("title", Title["title"]); - + EndProcedure Procedure AddDatabaseDescription(Val Description, MainStructure) - + OPI_TypeConversion.GetLine(Description); - - Title = ConvertHeader(Description); + + Title = ConvertHeader(Description); MainStructure.Insert("description", Title["title"]); - + EndProcedure Procedure AddDatabaseProperties(Val Properties, MainStructure) - + If Properties.Count() = 0 Then MainStructure.Insert("properties", New Structure); - Return; + Return; EndIf; - + ParameterMap = New Map; - + For Each Property In Properties Do - + If TypeOf(Property.Value) = Type("String") Then - + ParameterMap.Insert(Property.Key, New Structure(Property.Value, New Structure)); - - ElsIf TypeOf(Property.Value) = Type("Structure") + + ElsIf TypeOf(Property.Value) = Type("Structure") Or TypeOf(Property.Value) = Type("Map") Then - + ValueSelection = FormSelectionValues(Property.Value); ParameterMap.Insert(Property.Key, New Structure("select", ValueSelection)); - + Else - + ParameterMap.Insert(Property.Key, Property.Value); - + EndIf; - + EndDo; - + MainStructure.Insert("properties", ParameterMap); - + EndProcedure Function FormSelectionValues(Val VariantStructure) - + OptionArray = New Array; - + For Each Option In VariantStructure Do - + OptionMap = New Map; OptionMap.Insert("name" , Option.Key); OptionMap.Insert("color", Option.Value); - + OptionArray.Add(OptionMap); - + EndDo; - + Return New Structure("options", OptionArray); - + EndFunction Function FillDataBySchema(Val Scheme, Val Data, Val Token, Val ThisIsBase = True) - + If ThisIsBase Then SchemaData = GetDatabase(Token, Scheme); Else - SchemaData = GetPage(Token, Scheme); + SchemaData = GetPage(Token, Scheme); EndIf; - + BaseFields = SchemaData["properties"]; Properties = New Map; - + If ValueIsFilled(BaseFields) Then - + For Each Field In BaseFields Do - + FieldData = Field.Value; FieldType = FieldData["type"]; - + FillableData = Data.Get(Field.Key); - + If FillableData = Undefined Then Continue; EndIf; - + ConvertedData = ConvertValueByType(FieldType, FillableData); - + If ConvertedData = Undefined Then Continue; EndIf; - - Properties.Insert(FieldData["id"], ConvertedData); - + + Properties.Insert(FieldData["id"], ConvertedData); + EndDo; - + EndIf; Return Properties; @@ -679,7 +679,7 @@ Function FillDataBySchema(Val Scheme, Val Data, Val Token, Val ThisIsBase = True EndFunction Procedure RemoveExtraBlockFields(Val Block) - + ExtraArray = New Array; ExtraArray.Add("request_id"); ExtraArray.Add("archived"); @@ -690,22 +690,22 @@ Procedure RemoveExtraBlockFields(Val Block) ExtraArray.Add("parrent"); ExtraArray.Add("last_edited_by"); ExtraArray.Add("id"); - + For Each Field In ExtraArray Do - + If Not Block.Get(Field) = Undefined Then Block.Delete(Field); EndIf; - + EndDo; - + EndProcedure #Region TypeConversion Function ConvertValueByType(Val Type, Val Value) - - If Type = "title" Then + + If Type = "title" Then Return ConvertHeader(Value); ElsIf Type = "rich_text" Then Return ConvertText(Value); @@ -733,42 +733,42 @@ Function ConvertValueByType(Val Type, Val Value) Return ConvertEmail(Value); ElsIf Type = "phone_number" Then Return ConvertPhone(Value); - Else + Else Return Undefined; EndIf; - + EndFunction -Function ConvertHeader(Val Title) - +Function ConvertHeader(Val Title) + DataStructure = New Structure; TextStructure = New Structure; - DataArray = New Array; - + DataArray = New Array; + TextStructure.Insert("content", Title); - TextStructure.Insert("link" , Undefined); - + TextStructure.Insert("link" , Undefined); + DataStructure.Insert("type", "text"); DataStructure.Insert("text", TextStructure); - + DataArray.Add(DataStructure); Return New Structure("title", DataArray); - + EndFunction Function ConvertText(Val Text) - - TextArray = New Array; + + TextArray = New Array; TextStructure = New Structure; - + TextStructure.Insert("type", "text"); TextStructure.Insert("text", New Structure("content", Text)); - + TextArray.Add(TextStructure); - + Return New Structure("rich_text", TextArray); - + EndFunction Function ConvertNumber(Val Number) @@ -776,101 +776,101 @@ Function ConvertNumber(Val Number) EndFunction Function ConvertSelectionOption(Val Option) - + ChoiceStructure = New Structure; ChoiceStructure.Insert("select", New Structure("name", Option)); - + Return ChoiceStructure; - + EndFunction Function ConvertStatus(Val Status) - + StatusStructure = New Structure; StatusStructure.Insert("status", New Structure("name", Status)); - + Return StatusStructure; - + EndFunction Function ConvertMultipleChoice(Val OptionArray) - + ChoiceOptionArray = New Array; - + For Each Option In OptionArray Do ChoiceOptionArray.Add(New Structure("name", Option)); EndDo; - + Return New Structure("multi_select", ChoiceOptionArray); - + EndFunction Function ConvertDate(Val Date) - + DateStructure = New Structure; - - If Date = BegOfDay(Date) Then + + If Date = BegOfDay(Date) Then DateFormat = "DF=yyyy-MM-dd"; Else DateFormat = "ISO8601Datetime"; EndIf; - + Date = Format(Date, DateFormat); DateStructure.Insert("start", Date); - + Return New Structure("date", DateStructure); - + EndFunction -Function ConvertLink(Val Identifier) - +Function ConvertLink(Val Identifier) + LinkArray = New Array; LinkArray.Add(New Structure("id", Identifier)); - + Return New Structure("relation", LinkArray); - + EndFunction Function ConvertUsers(Val IDArray) - + If Not TypeOf(IDArray) = Type("Array") Then - ArrayID_ = New Array; + ArrayID_ = New Array; ArrayID_.Add(IDArray); - IDArray = ArrayID_; + IDArray = ArrayID_; EndIf; - + ArrayOfUsers = New Array; - + For Each Identifier In IDArray Do - + UserStructure = New Structure; UserStructure.Insert("object", "user"); - UserStructure.Insert("id" , Identifier); + UserStructure.Insert("id" , Identifier); ArrayOfUsers.Add(UserStructure); - + EndDo; - + Return New Structure("people", ArrayOfUsers); - + EndFunction Function ConvertFiles(Val FileMapping) - + ArrayOfFiles = New Array; - + For Each File In FileMapping Do - + FileStructure = New Structure; - FileStructure.Insert("type" , "external"); - FileStructure.Insert("name" , File.Key); + FileStructure.Insert("type" , "external"); + FileStructure.Insert("name" , File.Key); FileStructure.Insert("external", New Structure("url", File.Value)); - + ArrayOfFiles.Add(FileStructure); - + EndDo; Return New Structure("files", ArrayOfFiles); - + EndFunction Function ConvertBoolean(Val Boolean) diff --git a/src/en/OPI/src/CommonModules/OPI_Slack/Module.bsl b/src/en/OPI/src/CommonModules/OPI_Slack/Module.bsl index e9646ac8f3..c260924688 100644 --- a/src/en/OPI/src/CommonModules/OPI_Slack/Module.bsl +++ b/src/en/OPI/src/CommonModules/OPI_Slack/Module.bsl @@ -43,57 +43,57 @@ // Get bot information // Gets basic information about the bot -// +// // Parameters: // Token - String - Bot token - token -// +// // Returns: -// Map Of KeyAndValue - Serialized JSON response from Slack +// Map Of KeyAndValue - Serialized JSON response from Slack Function GetBotInformation(Val Token) Export - - URL = "https://slack.com/api/auth.test"; + + URL = "https://slack.com/api/auth.test"; Headers = GetAuthorizationHeader(Token); - + Response = OPI_Tools.Get(URL, , Headers); - + Return Response; EndFunction // Get workspace list // Gets a list of workspaces where the bot is connected -// +// // Parameters: // Token - String - Bot token - token // Cursor - String - Pointer from the previous request, if the result rows > 100 - cursor -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function GetWorkspaceList(Val Token, Val Cursor = "") Export - - URL = "https://slack.com/api/auth.teams.list"; + + URL = "https://slack.com/api/auth.teams.list"; Response = GeneralDataRetrieval(Token, URL, Cursor); - + Return Response; EndFunction // Get user list // Gets a list of users in the workspace -// +// // Parameters: // Token - String - Bot token - token // Cursor - String - Pointer from the previous request, if the result rows > 100 - cursor -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function GetUserList(Val Token, Val Cursor = "") Export - - URL = "https://slack.com/api/users.list"; + + URL = "https://slack.com/api/users.list"; Response = GeneralDataRetrieval(Token, URL, Cursor); - + Return Response; - + EndFunction #EndRegion @@ -102,68 +102,68 @@ EndFunction // Send message // Sends a message at a selected hour -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel // Text - String - Message text - text -// SendingDate - Date - Sending date for delayed message - date +// SendingDate - Date - Sending date for delayed message - date // Blocks - Array of Structure - Array of block descriptions - blocks - JSON array of block descriptions -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function SendMessage(Val Token, Val Channel, Val Text = "", Val SendingDate = "", Val Blocks = "") Export - + String_ = "String"; - HasDate = ValueIsFilled(SendingDate); + HasDate = ValueIsFilled(SendingDate); Headers = GetAuthorizationHeader(Token); - + If ValueIsFilled(Blocks) And TypeOf(Blocks) = Type(String_) Then OPI_TypeConversion.GetCollection(Blocks); - + If TypeOf(Blocks) = Type("Array") Then - + For N = 0 To Blocks.UBound() Do - OPI_TypeConversion.GetCollection(Blocks[N]); + OPI_TypeConversion.GetCollection(Blocks[N]); EndDo; - + EndIf; EndIf; - + Parameters = New Structure; OPI_Tools.AddField("channel", Channel, String_ , Parameters); - OPI_Tools.AddField("text" , Text, String_ , Parameters); - OPI_Tools.AddField("blocks" , Blocks, "Array" , Parameters); + OPI_Tools.AddField("text" , Text , String_ , Parameters); + OPI_Tools.AddField("blocks" , Blocks , "Array" , Parameters); If HasDate Then - + URL = "https://slack.com/api/chat.scheduleMessage"; - OPI_Tools.AddField("post_at", SendingDate, "Date", Parameters); - + OPI_Tools.AddField("post_at", SendingDate, "Date", Parameters); + Else - + URL = "https://slack.com/api/chat.postMessage"; - + EndIf; - + Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Send ephemeral message -// Sends a message that arrives in the channel but is visible +// Sends a message that arrives in the channel but is visible // only to a specific user -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel // Text - String - Message text - text -// User - String - User ID - user +// User - String - User ID - user // Blocks - Array of Structure - Array of block descriptions - blocks - JSON array of block descriptions -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function SendEphemeralMessage(Val Token @@ -171,168 +171,168 @@ Function SendEphemeralMessage(Val Token , Val Text = "" , Val User = "" , Val Blocks = "") Export - + String_ = "String"; - + If ValueIsFilled(Blocks) And Not TypeOf(Blocks) = Type(String_) Then OPI_TypeConversion.GetArray(Blocks); EndIf; - + Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; - OPI_Tools.AddField("channel", Channel , String_ , Parameters); - OPI_Tools.AddField("text" , Text , String_ , Parameters); - OPI_Tools.AddField("user" , User, String_ , Parameters); - OPI_Tools.AddField("blocks" , Blocks , "Collection", Parameters); - + OPI_Tools.AddField("channel", Channel , String_ , Parameters); + OPI_Tools.AddField("text" , Text , String_ , Parameters); + OPI_Tools.AddField("user" , User , String_ , Parameters); + OPI_Tools.AddField("blocks" , Blocks , "Collection", Parameters); + URL = "https://slack.com/api/chat.postEphemeral"; - + Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Edit message // Edits the content of an existing message -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel // Timestamp - String - Message timestamp - stamp // Text - String - New message text - text // BlockArray - Array of Structure - Array of block descriptions - blocks - JSON array of block descriptions -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function EditMessage(Val Token, Val Channel, Val Timestamp, Val Text = "", Val BlockArray = "") Export - + String_ = "String"; - URL = "https://slack.com/api/chat.update"; + URL = "https://slack.com/api/chat.update"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; - OPI_Tools.AddField("channel", Channel , String_ , Parameters); - OPI_Tools.AddField("text" , Text , String_ , Parameters); - OPI_Tools.AddField("ts" , Timestamp , String_ , Parameters); + OPI_Tools.AddField("channel", Channel , String_ , Parameters); + OPI_Tools.AddField("text" , Text , String_ , Parameters); + OPI_Tools.AddField("ts" , Timestamp , String_ , Parameters); OPI_Tools.AddField("blocks" , BlockArray, "Collection", Parameters); - + Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Delete message // Deletes a channel message by timestamp -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel // Timestamp - String - Timestamp or message ID - stamp // IsDelayed - Boolean - Indicator of deleting a delayed message - issheduled -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function DeleteMessage(Val Token, Val Channel, Val Timestamp, Val IsDelayed = False) Export - + OPI_TypeConversion.GetBoolean(IsDelayed); - + Headers = GetAuthorizationHeader(Token); - + If IsDelayed Then - URL = "https://slack.com/api/chat.deleteScheduledMessage"; - TimestampField = "scheduled_message_id"; + URL = "https://slack.com/api/chat.deleteScheduledMessage"; + TimestampField = "scheduled_message_id"; Else - URL = "https://slack.com/api/chat.delete"; + URL = "https://slack.com/api/chat.delete"; TimestampField = "ts"; EndIf; - + Parameters = New Structure; - OPI_Tools.AddField("channel" , Channel , "String", Parameters); + OPI_Tools.AddField("channel" , Channel , "String", Parameters); OPI_Tools.AddField(TimestampField, Timestamp, "String", Parameters); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction // Get list of delayed messages // Gets a list of delayed channel messages -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel // Cursor - String - Pointer from the previous request, if the result rows > 100 - cursor -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function GetDelayedMessageList(Val Token, Val Channel, Val Cursor = "") Export - - URL = "https://slack.com/api/chat.scheduledMessages.list"; + + URL = "https://slack.com/api/chat.scheduledMessages.list"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; OPI_Tools.AddField("channel", Channel , "String", Parameters); - OPI_Tools.AddField("cursor" , Cursor, "String", Parameters); - + OPI_Tools.AddField("cursor" , Cursor , "String", Parameters); + Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction // Get message link // Gets a permanent URL to the channel message -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel // Timestamp - String - Timestamp or message ID - stamp -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function GetMessageLink(Val Token, Val Channel, Val Timestamp) Export - - URL = "https://slack.com/api/chat.getPermalink"; + + URL = "https://slack.com/api/chat.getPermalink"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; - OPI_Tools.AddField("channel" , Channel , "String", Parameters); + OPI_Tools.AddField("channel" , Channel , "String", Parameters); OPI_Tools.AddField("message_ts", Timestamp, "String", Parameters); Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; EndFunction // Get list of message replies // Gets an array of messages that are replies to the specified -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel // Timestamp - String - Timestamp or message ID - stamp // Cursor - String - Pointer from the previous request, if the result rows > 100 - cursor -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function GetMessageReplyList(Val Token, Val Channel, Val Timestamp, Val Cursor = "") Export - + String_ = "String"; - URL = "https://slack.com/api/conversations.replies"; + URL = "https://slack.com/api/conversations.replies"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; - OPI_Tools.AddField("channel", Channel , String_, Parameters); - OPI_Tools.AddField("cursor" , Cursor , String_, Parameters); - OPI_Tools.AddField("ts" , Timestamp, String_, Parameters); - + OPI_Tools.AddField("channel", Channel , String_, Parameters); + OPI_Tools.AddField("cursor" , Cursor , String_, Parameters); + OPI_Tools.AddField("ts" , Timestamp, String_, Parameters); + Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; EndFunction @@ -343,108 +343,108 @@ EndFunction // Get channel list // Gets a list of available channels -// +// // Parameters: // Token - String - Bot token - token -// ExcludeArchived - Boolean - Indicator of excluding archived channels - notarchived +// ExcludeArchived - Boolean - Indicator of excluding archived channels - notarchived // Cursor - String - Pointer from the previous request, if the result rows > 100 - cursor -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function GetChannelList(Val Token, Val ExcludeArchived = False, Val Cursor = "") Export - - URL = "https://slack.com/api/conversations.list"; + + URL = "https://slack.com/api/conversations.list"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; OPI_Tools.AddField("exclude_archived", ExcludeArchived, "Boolean", Parameters); - OPI_Tools.AddField("cursor" , Cursor , "String", Parameters); + OPI_Tools.AddField("cursor" , Cursor , "String" , Parameters); Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; - + EndFunction // Get channel user list // Gets a list of users in the specified channel -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel // Cursor - String - Pointer from the previous request, if the result rows > 100 - cursor -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function GetChannelUserList(Val Token, Val Channel, Val Cursor = "") Export - - URL = "https://slack.com/api/conversations.members"; + + URL = "https://slack.com/api/conversations.members"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; OPI_Tools.AddField("channel", Channel , "String", Parameters); - OPI_Tools.AddField("cursor" , Cursor, "String", Parameters); + OPI_Tools.AddField("cursor" , Cursor , "String", Parameters); Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; EndFunction // Create channel // Creates a new channel -// +// // Parameters: // Token - String - Bot token - token // Name - String - Channel name - title // Private - Boolean - Create channel as private - private -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function CreateChannel(Val Token, Val Name, Val Private = False) Export - - URL = "https://slack.com/api/conversations.create"; + + URL = "https://slack.com/api/conversations.create"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; - OPI_Tools.AddField("name" , Name , "String", Parameters); + OPI_Tools.AddField("name" , Name , "String" , Parameters); OPI_Tools.AddField("is_private", Private, "Boolean", Parameters); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Archive channel // Archives an active channel -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function ArchiveChannel(Val Token, Val Channel) Export - - URL = "https://slack.com/api/conversations.archive"; + + URL = "https://slack.com/api/conversations.archive"; Response = DialogManagement(Token, Channel, URL); Return Response; - + EndFunction // Get channel // Gets information about the channel -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function GetChannel(Val Token, Val Channel) Export - - URL = "https://slack.com/api/conversations.info"; + + URL = "https://slack.com/api/conversations.info"; Response = DialogManagement(Token, Channel, URL, "GET"); Return Response; @@ -452,16 +452,16 @@ EndFunction // Get channel history // Gets information about channel events -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function GetChannelHistory(Val Token, Val Channel) Export - - URL = "https://slack.com/api/conversations.history"; + + URL = "https://slack.com/api/conversations.history"; Response = DialogManagement(Token, Channel, URL, "GET"); Return Response; @@ -469,69 +469,69 @@ EndFunction // Invite users to channel // Adds specified users to the channel -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel // ArrayOfUsers - Array Of String - User ID Array - users -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function InviteUsersToChannel(Val Token, Val Channel, Val ArrayOfUsers) Export - - URL = "https://slack.com/api/conversations.invite"; + + URL = "https://slack.com/api/conversations.invite"; Headers = GetAuthorizationHeader(Token); - + OPI_TypeConversion.GetCollection(ArrayOfUsers); ArrayOfUsers = StrConcat(ArrayOfUsers, ","); - + Parameters = New Structure; - OPI_Tools.AddField("channel", Channel , "String", Parameters); - OPI_Tools.AddField("users" , ArrayOfUsers, "String", Parameters); + OPI_Tools.AddField("channel", Channel , "String", Parameters); + OPI_Tools.AddField("users" , ArrayOfUsers, "String", Parameters); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction // Kick user from channel // Removes specified user from channel -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel // User - String - User ID - user -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function KickUserFromChannel(Val Token, Val Channel, Val User) Export - - URL = "https://slack.com/api/conversations.kick"; + + URL = "https://slack.com/api/conversations.kick"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; OPI_Tools.AddField("channel", Channel , "String", Parameters); - OPI_Tools.AddField("user" , User, "String", Parameters); + OPI_Tools.AddField("user" , User , "String", Parameters); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction // Join channel // Adds the current bot to the channel -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function JoinChannel(Val Token, Val Channel) Export - - URL = "https://slack.com/api/conversations.join"; + + URL = "https://slack.com/api/conversations.join"; Response = DialogManagement(Token, Channel, URL); Return Response; @@ -539,16 +539,16 @@ EndFunction // Leave channel // Removes the current bot from the channel -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function LeaveChannel(Val Token, Val Channel) Export - - URL = "https://slack.com/api/conversations.leave"; + + URL = "https://slack.com/api/conversations.leave"; Response = DialogManagement(Token, Channel, URL); Return Response; @@ -556,75 +556,75 @@ EndFunction // Set channel topic // Sets the channel topic -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel // Topic - String - Channel topic - theme -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function SetChannelTopic(Val Token, Val Channel, Val Topic) Export - - URL = "https://slack.com/api/conversations.setTopic"; + + URL = "https://slack.com/api/conversations.setTopic"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; OPI_Tools.AddField("channel", Channel , "String", Parameters); - OPI_Tools.AddField("topic" , Topic , "String", Parameters); + OPI_Tools.AddField("topic" , Topic , "String", Parameters); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction // Set channel purpose // Sets the channel purpose (description) -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel // Purpose - String - Channel purpose - purpose -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function SetChannelGoal(Val Token, Val Channel, Val Purpose) Export - - URL = "https://slack.com/api/conversations.setPurpose"; + + URL = "https://slack.com/api/conversations.setPurpose"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; OPI_Tools.AddField("channel", Channel , "String", Parameters); OPI_Tools.AddField("purpose", Purpose , "String", Parameters); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction // Rename channel // Changes the name of the channel -// +// // Parameters: // Token - String - Bot token - token // Channel - String - Channel ID - channel // Name - String - New channel name - title -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function RenameChannel(Val Token, Val Channel, Val Name) Export - - URL = "https://slack.com/api/conversations.rename"; + + URL = "https://slack.com/api/conversations.rename"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; OPI_Tools.AddField("channel", Channel , "String", Parameters); - OPI_Tools.AddField("name" , Name, "String", Parameters); + OPI_Tools.AddField("name" , Name , "String", Parameters); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction @@ -635,45 +635,45 @@ EndFunction // Open dialog // Opens a new dialog with one or more users -// +// // Parameters: // Token - String - Bot token - token // ArrayOfUsers - Array of String - User ID Array - users -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function OpenDialog(Val Token, Val ArrayOfUsers) Export - - URL = "https://slack.com/api/conversations.open"; + + URL = "https://slack.com/api/conversations.open"; Headers = GetAuthorizationHeader(Token); - + OPI_TypeConversion.GetCollection(ArrayOfUsers); ArrayOfUsers = StrConcat(ArrayOfUsers, ","); - + Parameters = New Structure; OPI_Tools.AddField("users", ArrayOfUsers, "String", Parameters); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; EndFunction // Close dialog // Closes an existing dialog -// +// // Parameters: // Token - String - Bot token - token // Dialog - String - Dialog ID - conv -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function CloseDialog(Val Token, Val Dialog) Export - - URL = "https://slack.com/api/conversations.close"; + + URL = "https://slack.com/api/conversations.close"; Response = DialogManagement(Token, Dialog, URL); Return Response; - + EndFunction #EndRegion @@ -682,154 +682,154 @@ EndFunction // Get list of files // Gets a list of files of the bot or channel -// +// // Parameters: // Token - String - Bot token - token -// Channel - String - Channel for selection - channel +// Channel - String - Channel for selection - channel // PageNumber - Number, String - Page number - page -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function GetFilesList(Val Token, Val Channel = "", Val PageNumber = 1) Export - - URL = "https://slack.com/api/files.list"; + + URL = "https://slack.com/api/files.list"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; - OPI_Tools.AddField("channel", Channel , "String", Parameters); - OPI_Tools.AddField("page" , PageNumber, "String", Parameters); + OPI_Tools.AddField("channel", Channel , "String", Parameters); + OPI_Tools.AddField("page" , PageNumber, "String", Parameters); Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; - + EndFunction // Upload file // Uploads a file to Slack servers -// +// // Parameters: // Token - String - Bot token - token // File - String, BinaryData - File for upload - file // FileName - String - File name with extension - filename // Title - String - File name in Slack - title // Channel - String - Channel ID - channel -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function UploadFile(Val Token, Val File, Val FileName, Val Title, Val Channel = "") Export - + OPI_TypeConversion.GetBinaryData(File); OPI_TypeConversion.GetLine(FileName); OPI_TypeConversion.GetLine(Title); - - String_ = "String"; + + String_ = "String"; Upload_url = "upload_url"; - File_id = "file_id"; - URL = "https://slack.com/api/files.getUploadURLExternal"; - Headers = GetAuthorizationHeader(Token); - Size = File.Size(); - + File_id = "file_id"; + URL = "https://slack.com/api/files.getUploadURLExternal"; + Headers = GetAuthorizationHeader(Token); + Size = File.Size(); + Parameters = New Structure; OPI_Tools.AddField("filename", FileName, String_, Parameters); - OPI_Tools.AddField("length" , Size , String_, Parameters); + OPI_Tools.AddField("length" , Size , String_, Parameters); - Response = OPI_Tools.Get(URL, Parameters, Headers); - URL = Response[Upload_url]; + Response = OPI_Tools.Get(URL, Parameters, Headers); + URL = Response[Upload_url]; Identifier = Response[File_id]; - + If Not ValueIsFilled(URL) Or Not ValueIsFilled(Identifier) Then Return Response; EndIf; - + Files = New Map; Files.Insert(FileName, File); - - Response = OPI_Tools.PostMultipart(URL, , Files, , Headers); - URL = "https://slack.com/api/files.completeUploadExternal"; - SlackFile = New Structure("id, title", Identifier, Title); - + + Response = OPI_Tools.PostMultipart(URL, , Files, , Headers); + URL = "https://slack.com/api/files.completeUploadExternal"; + SlackFile = New Structure("id, title", Identifier, Title); + Parameters = New Structure; - OPI_Tools.AddField("filename" , FileName, String_, Parameters); - OPI_Tools.AddField("channel_id", Channel , String_, Parameters); - OPI_Tools.AddField("files" , SlackFile, "Array", Parameters); + OPI_Tools.AddField("filename" , FileName , String_, Parameters); + OPI_Tools.AddField("channel_id", Channel , String_, Parameters); + OPI_Tools.AddField("files" , SlackFile, "Array", Parameters); Response = OPI_Tools.Post(URL, Parameters, Headers); - + Return Response; - + EndFunction // Get file data // Gets information about the file -// +// // Parameters: // Token - String - Bot token - token // FileID - String - File identifier - fileid -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function GetFileData(Val Token, Val FileID) Export - - URL = "https://slack.com/api/files.info"; + + URL = "https://slack.com/api/files.info"; Response = FileManagement(Token, FileID, URL, "GET"); - + Return Response; - + EndFunction // Delete file // Deletes a file on Slack -// +// // Parameters: // Token - String - Bot token - token // FileID - String - File identifier - fileid -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function DeleteFile(Val Token, Val FileID) Export - - URL = "https://slack.com/api/files.delete"; + + URL = "https://slack.com/api/files.delete"; Response = FileManagement(Token, FileID, URL); - + Return Response; - + EndFunction // Make file public // Creates a public URL for the file. Requires user token -// +// // Parameters: // Token - String - User token - token // FileID - String - File identifier - fileid -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function MakeFilePublic(Val Token, Val FileID) Export - - URL = "https://slack.com/api/files.sharedPublicURL"; + + URL = "https://slack.com/api/files.sharedPublicURL"; Response = FileManagement(Token, FileID, URL); - + Return Response; - + EndFunction // Make file private // Removes the public URL from the file. Requires user token -// +// // Parameters: // Token - String - User token - token // FileID - String - File identifier - fileid -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function MakeFilePrivate(Val Token, Val FileID) Export - - URL = "https://slack.com/api/files.revokePublicURL"; + + URL = "https://slack.com/api/files.revokePublicURL"; Response = FileManagement(Token, FileID, URL); - + Return Response; - + EndFunction #EndRegion @@ -838,119 +838,119 @@ EndFunction // Get list of external files // Gets a list of external files of a user or channel -// +// // Parameters: // Token - String - Bot token - token -// Channel - String - Channel for selection - channel +// Channel - String - Channel for selection - channel // Cursor - String - Pointer from the previous request, if the result rows > 100 - cursor -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function GetExternalFileList(Val Token, Val Channel = "", Val Cursor = "") Export - - URL = "https://slack.com/api/files.remote.list"; + + URL = "https://slack.com/api/files.remote.list"; Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; OPI_Tools.AddField("channel", Channel , "String", Parameters); - OPI_Tools.AddField("cursor" , Cursor, "String", Parameters); + OPI_Tools.AddField("cursor" , Cursor , "String", Parameters); Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; - + EndFunction // Get external file // Gets information about the external file -// +// // Parameters: // Token - String - Bot token - token // FileID - String - File identifier - fileid -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function GetExternalFile(Val Token, Val FileID) Export - - URL = "https://slack.com/api/files.remote.info"; + + URL = "https://slack.com/api/files.remote.info"; Response = ExternalFileManagement(Token, FileID, URL); - + Return Response; - + EndFunction // Add external file // Adds a new external file -// +// // Parameters: // Token - String - Bot token - token // URL - String - URL to external file - url // Title - String - File title for Slack - title -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function AddExternalFile(Val Token, Val URL, Val Title) Export - + String_ = "String"; - URL = "https://slack.com/api/files.remote.add"; + URL = "https://slack.com/api/files.remote.add"; Headers = GetAuthorizationHeader(Token); - UID = String(New UUID()); - + UID = String(New UUID()); + Parameters = New Structure; - OPI_Tools.AddField("external_url", URL , String_, Parameters); - OPI_Tools.AddField("external_id" , UID , String_, Parameters); - OPI_Tools.AddField("title" , Title , String_, Parameters); + OPI_Tools.AddField("external_url", URL , String_, Parameters); + OPI_Tools.AddField("external_id" , UID , String_, Parameters); + OPI_Tools.AddField("title" , Title , String_, Parameters); Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; - + EndFunction // Send external file // Sends an external file to a list of channels -// +// // Parameters: // Token - String - Bot token - token // FileID - String - File identifier - fileid // ChannelArray - Array Of String - Array of channels for sending - channels -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function SendExternalFile(Val Token, Val FileID, Val ChannelArray) Export - - URL = "https://slack.com/api/files.remote.share"; + + URL = "https://slack.com/api/files.remote.share"; Headers = GetAuthorizationHeader(Token); - + OPI_TypeConversion.GetCollection(ChannelArray); ChannelArray = StrConcat(ChannelArray, ","); - + Parameters = New Structure; - OPI_Tools.AddField("file" , FileID , "String", Parameters); + OPI_Tools.AddField("file" , FileID , "String", Parameters); OPI_Tools.AddField("channels", ChannelArray , "String", Parameters); Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; - + EndFunction // Delete external file // Deletes an external file from Slack -// +// // Parameters: // Token - String - Bot token - token // FileID - String - File identifier - fileid -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Slack Function DeleteExternalFile(Val Token, Val FileID) Export - - URL = "https://slack.com/api/files.remote.remove"; + + URL = "https://slack.com/api/files.remote.remove"; Response = ExternalFileManagement(Token, FileID, URL); - + Return Response; - + EndFunction #EndRegion @@ -959,24 +959,24 @@ EndFunction // Generate image block // Generates a block with an image to add to the message block array -// +// // Parameters: // URL - String - Image URL - picture // AlternateText - String - Alternate text of the image - alt -// +// // Returns: // Map Of KeyAndValue - Image block Function GenerateImageBlock(Val URL, Val AlternateText = "") Export - + String_ = "String"; - + Block = New Map; - OPI_Tools.AddField("type" , "image" , String_, Block); - OPI_Tools.AddField("image_url", URL , String_, Block); + OPI_Tools.AddField("type" , "image" , String_, Block); + OPI_Tools.AddField("image_url", URL , String_, Block); OPI_Tools.AddField("alt_text" , AlternateText , String_, Block); - + Return Block; - + EndFunction #EndRegion @@ -988,43 +988,43 @@ EndFunction Function GetAuthorizationHeader(Val Token) OPI_TypeConversion.GetLine(Token); - + Headers = New Map; Headers.Insert("Authorization", "Bearer " + Token); Return Headers; - + EndFunction Function DialogManagement(Val Token, Val Channel, Val URL, Val RequestType = "POST") - - Headers = GetAuthorizationHeader(Token); + + Headers = GetAuthorizationHeader(Token); RequestType = Upper(RequestType); - + Parameters = New Structure; OPI_Tools.AddField("channel", Channel, "String", Parameters); If RequestType = "POST" Then - Response = OPI_Tools.Post(URL, Parameters, Headers); + Response = OPI_Tools.Post(URL, Parameters, Headers); Else - Response = OPI_Tools.Get(URL, Parameters, Headers); + Response = OPI_Tools.Get(URL, Parameters, Headers); EndIf; - + Return Response; - + EndFunction Function FileManagement(Val Token, Val FileID, Val URL, Val RequestType = "POST") - - Headers = GetAuthorizationHeader(Token); + + Headers = GetAuthorizationHeader(Token); RequestType = Upper(RequestType); - + Parameters = New Structure; OPI_Tools.AddField("file", FileID , "String", Parameters); If RequestType = "POST" Then - Response = OPI_Tools.Post(URL, Parameters, Headers); + Response = OPI_Tools.Post(URL, Parameters, Headers); Else - Response = OPI_Tools.Get(URL, Parameters, Headers); + Response = OPI_Tools.Get(URL, Parameters, Headers); EndIf; Return Response; @@ -1032,29 +1032,29 @@ Function FileManagement(Val Token, Val FileID, Val URL, Val RequestType = "POST" EndFunction Function GeneralDataRetrieval(Val Token, Val URL, Val Cursor) - + Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; OPI_Tools.AddField("cursor", Cursor, "String", Parameters); - + Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; - + EndFunction Function ExternalFileManagement(Val Token, Val FileID, Val URL) - + Headers = GetAuthorizationHeader(Token); - + Parameters = New Structure; OPI_Tools.AddField("file", FileID , "String", Parameters); Response = OPI_Tools.Get(URL, Parameters, Headers); - + Return Response; - + EndFunction #EndRegion diff --git a/src/en/OPI/src/CommonModules/OPI_Telegram/Module.bsl b/src/en/OPI/src/CommonModules/OPI_Telegram/Module.bsl index 195ef2bc30..b4be4ae41c 100644 --- a/src/en/OPI/src/CommonModules/OPI_Telegram/Module.bsl +++ b/src/en/OPI/src/CommonModules/OPI_Telegram/Module.bsl @@ -47,19 +47,19 @@ // Get bot information // Executes the /getMe request, returning basic bot information: name, id, ability to add the bot to groups, etc.. -// +// // Parameters: // Token - String - Bot token - token -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function GetBotInformation(Val Token) Export OPI_TypeConversion.GetLine(Token); - - URL = "api.telegram.org/bot" + Token + "/getMe"; + + URL = "api.telegram.org/bot" + Token + "/getMe"; Response = OPI_Tools.Get(URL); - + Return Response; EndFunction @@ -71,119 +71,119 @@ EndFunction // Token - String - Bot token - token // Timeout - String, Number - Waiting time for new events - timeout // Offset - String, Number - Offset in the list of received messages - offset -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function GetUpdates(Val Token, Val Timeout = 0, Val Offset = "") Export OPI_TypeConversion.GetLine(Token); - + URL = "api.telegram.org/bot" + Token + "/getUpdates"; - + Parameters = New Structure; OPI_Tools.AddField("timeout", Timeout , "String", Parameters); - OPI_Tools.AddField("offset" , Offset, "String", Parameters); - + OPI_Tools.AddField("offset" , Offset , "String", Parameters); + Response = OPI_Tools.Get(URL, Parameters); Return Response; EndFunction // Set Webhook -// Set webhook URL for bot event handling in webhook mode -// +// Set webhook URL for bot event handling in webhook mode +// // Parameters: // Token - String - Bot token - token // URL - String - Request handling address from Telegram (with https:) - url -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function SetWebhook(Val Token, Val URL) Export OPI_TypeConversion.GetLine(Token); - + Parameters = New Structure; OPI_Tools.AddField("url", URL, "String", Parameters); - URL = "api.telegram.org/bot" + Token + "/setWebHook"; + URL = "api.telegram.org/bot" + Token + "/setWebHook"; Response = OPI_Tools.Get(URL, Parameters); - + Return Response; EndFunction // Delete webhook // Deletes the bot event handler URL for webhook operation -// +// // Parameters: // Token - String - Bot token - token -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function DeleteWebhook(Val Token) Export OPI_TypeConversion.GetLine(Token); - - URL = "api.telegram.org/bot" + Token + "/deleteWebHook"; + + URL = "api.telegram.org/bot" + Token + "/deleteWebHook"; Response = OPI_Tools.Get(URL); - + Return Response; EndFunction // Download file // Download file from Telegram servers -// +// // Parameters: // Token - String - Token - token // FileID - String - File ID for downloading - fileid -// +// // Returns: // BinaryData - file's binary data Function DownloadFile(Val Token, Val FileID) Export Result = "result"; - - OPI_TypeConversion.GetLine(Token); - OPI_TypeConversion.GetLine(FileID); - + + OPI_TypeConversion.GetLine(Token); + OPI_TypeConversion.GetLine(FileID); + Parameters = New Structure("file_id", FileID); - URL = "api.telegram.org/bot" + Token + "/getFile"; + URL = "api.telegram.org/bot" + Token + "/getFile"; Response = OPI_Tools.Get(URL, Parameters); - + Path = Response[Result]["file_path"]; - + If Not ValueIsFilled(Path) Then Return Response; EndIf; - - URL = "api.telegram.org/file/bot" + Token + "/" + Path; + + URL = "api.telegram.org/file/bot" + Token + "/" + Path; Response = OPI_Tools.Get(URL, Parameters); - - Return Response; - + + Return Response; + EndFunction // Process Telegram Mini App data // Processes TMA data and determines its validity -// +// // Parameters: // DataString - String - Query from Telegram.WebApp.initData // Token - String - Bot token -// +// // Returns: // Map of String - Map of data with the result of verification in the passed field Function ProcessTMAData(Val DataString, Val Token) Export OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(DataString); - - DataString = DecodeString(DataString, StringEncodingMethod.URLencoding); + + DataString = DecodeString(DataString, StringEncodingMethod.URLencoding); DataStructure = OPI_Tools.RequestParametersToMap(DataString); - KeyString = "WebAppData"; - Hash = ""; - BinaryKey = GetBinaryDataFromString(KeyString); + KeyString = "WebAppData"; + Hash = ""; + BinaryKey = GetBinaryDataFromString(KeyString); Result = OPI_Cryptography.HMACSHA256(BinaryKey, GetBinaryDataFromString(Token)); @@ -193,8 +193,8 @@ Function ProcessTMAData(Val DataString, Val Token) Export For Each Data In DataStructure Do - NewLine = TValue.Add(); - NewLine.Key = Data.Key; + NewLine = TValue.Add(); + NewLine.Key = Data.Key; NewLine.Value = Data.Value; EndDo; @@ -202,12 +202,12 @@ Function ProcessTMAData(Val DataString, Val Token) Export TValue.Sort("Key"); ReturnMapping = New Map; - DCS = ""; + DCS = ""; For Each DataString In TValue Do If DataString.Key <> "hash" Then - DCS = DCS + DataString.Key + "=" + DataString.Value + Chars.LF; + DCS = DCS + DataString.Key + " =" + DataString.Value + Chars.LF; ReturnMapping.Insert(DataString.Key, DataString.Value); Else Hash = DataString.Value; @@ -215,12 +215,12 @@ Function ProcessTMAData(Val DataString, Val Token) Export EndDo; - DCS = Left(DCS, StrLen(DCS) - 1); + DCS = Left(DCS, StrLen(DCS) - 1); Signature = OPI_Cryptography.HMACSHA256(Result, GetBinaryDataFromString(DCS)); Final = GetHexStringFromBinaryData(Signature); - If Final = Upper(Hash) Then + If Final = Upper(Hash) Then Response = True; Else Response = False; @@ -238,7 +238,7 @@ EndFunction // Send text message // Sends a text message to a chat or channel -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID or ChatID*TopicID - chat @@ -246,7 +246,7 @@ EndFunction // Keyboard - String - See GenerateKeyboardFromArray - keyboard - Keyboard JSON or path to .json // Markup - String - Text processing type (HTML, Markdown, MarkdownV2) - parsemode // RepliedID - String, Number - Reply to message ID - reply -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function SendTextMessage(Val Token @@ -256,20 +256,20 @@ Function SendTextMessage(Val Token , Val Markup = "Markdown" , Val RepliedID = 0) Export - OPI_TypeConversion.GetLine(Token); + OPI_TypeConversion.GetLine(Token); OPI_Tools.ReplaceSpecialCharacters(Text, Markup); - + String_ = "String"; - + Parameters = New Structure; - OPI_Tools.AddField("parse_mode" , Markup , String_ , Parameters); - OPI_Tools.AddField("text" , Text , String_ , Parameters); - OPI_Tools.AddField("reply_markup" , Keyboard , "FileString", Parameters); - OPI_Tools.AddField("reply_to_message_id", RepliedID, String_ , Parameters); - + OPI_Tools.AddField("parse_mode" , Markup , String_ , Parameters); + OPI_Tools.AddField("text" , Text , String_ , Parameters); + OPI_Tools.AddField("reply_markup" , Keyboard , "FileString", Parameters); + OPI_Tools.AddField("reply_to_message_id", RepliedID, String_ , Parameters); + AddChatIdentifier(ChatID, Parameters); - - URL = "api.telegram.org/bot" + Token + "/sendMessage"; + + URL = "api.telegram.org/bot" + Token + "/sendMessage"; Response = OPI_Tools.Get(URL, Parameters); Return Response; @@ -278,7 +278,7 @@ EndFunction // Send image // Sends an image to a chat or channel -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID or ChatID*TopicID - chat @@ -286,7 +286,7 @@ EndFunction // Image - BinaryData,String - Image file - picture // Keyboard - String - See GenerateKeyboardFromArray - keyboard - Keyboard JSON or path to .json // Markup - String - Text processing type (HTML, Markdown, MarkdownV2) - parsemode -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function SendImage(Val Token @@ -302,7 +302,7 @@ EndFunction // Send video // Sends a video to a chat or channel -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID or ChatID*TopicID - chat @@ -310,7 +310,7 @@ EndFunction // Video - BinaryData,String - Video file - video // Keyboard - String - See GenerateKeyboardFromArray - keyboard - Keyboard JSON or path to .json // Markup - String - Text processing type (HTML, Markdown, MarkdownV2) - parsemode -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function SendVideo(Val Token @@ -326,7 +326,7 @@ EndFunction // Send audio // Sends an audio file to a chat or channel -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID or ChatID*TopicID - chat @@ -334,7 +334,7 @@ EndFunction // Audio - BinaryData,String - Audio file - audio // Keyboard - String - See GenerateKeyboardFromArray - keyboard - Keyboard JSON or path to .json // Markup - String - Text processing type (HTML, Markdown, MarkdownV2) - parsemode -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function SendAudio(Val Token @@ -350,7 +350,7 @@ EndFunction // Send document // Sends a document to a chat or channel -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID or ChatID*TopicID - chat @@ -359,7 +359,7 @@ EndFunction // Keyboard - String - See GenerateKeyboardFromArray - keyboard - Keyboard JSON or path to .json // Markup - String - Text processing type (HTML, Markdown, MarkdownV2) - parsemode // FileName - String - Custom displayed file name with extension, if necessary - filename -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function SendDocument(Val Token @@ -376,7 +376,7 @@ EndFunction // Send GIF // Sends a GIF to a chat or channel -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID or ChatID*TopicID - chat @@ -384,7 +384,7 @@ EndFunction // GIF - BinaryData,String - GIF file - gif // Keyboard - String - See GenerateKeyboardFromArray - keyboard - Keyboard JSON or path to .json // Markup - String - Text processing type (HTML, Markdown, MarkdownV2) - parsemode -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function SendGif(Val Token @@ -400,10 +400,10 @@ EndFunction // Send media group // Sends a set of files to a chat or channel. Media types: audio, document, photo, video -// +// // Note // Map: Key - File, Value - media type -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID or ChatID*TopicID - chat @@ -411,7 +411,7 @@ EndFunction // FileMapping - Map of String - File collection - media - File JSON or path to .json // Keyboard - String - See GenerateKeyboardFromArray - keyboard - Keyboard JSON or path to .json // Markup - String - Text processing type (HTML, Markdown, MarkdownV2) - parsemode -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function SendMediaGroup(Val Token @@ -420,30 +420,30 @@ Function SendMediaGroup(Val Token , Val FileMapping , Val Keyboard = "" , Val Markup = "Markdown") Export - + // FileMapping // Key - File, Value - Type // Types: audio, document, photo, video // Different types cannot be mixed! String_ = "String"; - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(ChatID); OPI_TypeConversion.GetCollection(FileMapping); - + OPI_Tools.ReplaceSpecialCharacters(Text, Markup); - URL = "api.telegram.org/bot" + Token + "/sendMediaGroup"; - Media = New Array; + URL = "api.telegram.org/bot" + Token + "/sendMediaGroup"; + Media = New Array; Parameters = New Structure; - + AddChatIdentifier(ChatID, Parameters); ConvertFilesToMedia(FileMapping, Text, Media); - - OPI_Tools.AddField("parse_mode" , Markup , String_ , Parameters); - OPI_Tools.AddField("caption" , Text , String_ , Parameters); - OPI_Tools.AddField("media" , Media , String_ , Parameters); + + OPI_Tools.AddField("parse_mode" , Markup , String_ , Parameters); + OPI_Tools.AddField("caption" , Text , String_ , Parameters); + OPI_Tools.AddField("media" , Media , String_ , Parameters); OPI_Tools.AddField("reply_markup", Keyboard, "FileString", Parameters); Response = OPI_Tools.PostMultipart(URL, Parameters, FileMapping, "mixed"); @@ -454,14 +454,14 @@ EndFunction // Send location // Sends location by geographic latitude and longitude to a chat or channel -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID or ChatID*TopicID - chat // Latitude - String, Number - Geographic latitude - lat // Longitude - String, Number - Geographic longitude - long // Keyboard - String - See GenerateKeyboardFromArray - keyboard - Keyboard JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function SendLocation(Val Token, Val ChatID, Val Latitude, Val Longitude, Val Keyboard = "") Export @@ -469,15 +469,15 @@ Function SendLocation(Val Token, Val ChatID, Val Latitude, Val Longitude, Val Ke String_ = "String"; OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(ChatID); - + URL = "api.telegram.org/bot" + Token + "/sendLocation"; - + Parameters = New Structure; - OPI_Tools.AddField("parse_mode" , "Markdown" , String_ , Parameters); - OPI_Tools.AddField("latitude" , Latitude , String_ , Parameters); - OPI_Tools.AddField("longitude" , Longitude , String_ , Parameters); - OPI_Tools.AddField("reply_markup", Keyboard , "FileString", Parameters); - + OPI_Tools.AddField("parse_mode" , "Markdown" , String_ , Parameters); + OPI_Tools.AddField("latitude" , Latitude , String_ , Parameters); + OPI_Tools.AddField("longitude" , Longitude , String_ , Parameters); + OPI_Tools.AddField("reply_markup", Keyboard , "FileString", Parameters); + AddChatIdentifier(ChatID, Parameters); Response = OPI_Tools.Get(URL, Parameters); @@ -488,7 +488,7 @@ EndFunction // Send contact // Sends a contact with name and phone number -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID or ChatID*TopicID - chat @@ -496,7 +496,7 @@ EndFunction // LastName - String - Contact last name - surname // Phone - String - Contact phone number - phone // Keyboard - String - See GenerateKeyboardFromArray - keyboard - Keyboard JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function SendContact(Val Token, Val ChatID, Val Name, Val LastName, Val Phone, Val Keyboard = "") Export @@ -504,16 +504,16 @@ Function SendContact(Val Token, Val ChatID, Val Name, Val LastName, Val Phone, V String_ = "String"; OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(ChatID); - + URL = "api.telegram.org/bot" + Token + "/sendContact"; Parameters = New Structure; - OPI_Tools.AddField("parse_mode" , "Markdown", String_ , Parameters); - OPI_Tools.AddField("first_name" , Name , String_ , Parameters); - OPI_Tools.AddField("last_name" , LastName , String_ , Parameters); - OPI_Tools.AddField("phone_number", Phone , String_ , Parameters); - OPI_Tools.AddField("reply_markup", Keyboard, "FileString", Parameters); - + OPI_Tools.AddField("parse_mode" , "Markdown", String_ , Parameters); + OPI_Tools.AddField("first_name" , Name , String_ , Parameters); + OPI_Tools.AddField("last_name" , LastName , String_ , Parameters); + OPI_Tools.AddField("phone_number", Phone , String_ , Parameters); + OPI_Tools.AddField("reply_markup", Keyboard , "FileString", Parameters); + AddChatIdentifier(ChatID, Parameters); Response = OPI_Tools.Get(URL, Parameters); @@ -524,14 +524,14 @@ EndFunction // Send poll // Sends a poll with answer options -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID or ChatID*TopicID - chat // Question - String - Poll question - question // AnswersArray - Array of String - Array of answer options - options // Anonymous - Boolean - Poll anonymity - anonymous -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function SendPoll(Val Token, Val ChatID, Val Question, Val AnswersArray, Val Anonymous = True) Export @@ -541,15 +541,15 @@ Function SendPoll(Val Token, Val ChatID, Val Question, Val AnswersArray, Val Ano OPI_TypeConversion.GetCollection(AnswersArray); OPI_TypeConversion.GetBoolean(Anonymous); - + URL = "api.telegram.org/bot" + Token + "/sendPoll"; Parameters = New Structure; - OPI_Tools.AddField("parse_mode", "Markdown" , "String" , Parameters); - OPI_Tools.AddField("question" , Question , "String" , Parameters); - OPI_Tools.AddField("options" , AnswersArray, "FileString", Parameters); - - Parameters.Insert("is_anonymous", ?(Anonymous, 1, 0)); + OPI_Tools.AddField("parse_mode", "Markdown" , "String" , Parameters); + OPI_Tools.AddField("question" , Question , "String" , Parameters); + OPI_Tools.AddField("options" , AnswersArray, "FileString", Parameters); + + Parameters.Insert("is_anonymous", ?(Anonymous, 1, 0)); AddChatIdentifier(ChatID, Parameters); Response = OPI_Tools.Get(URL, Parameters); @@ -560,13 +560,13 @@ EndFunction // Forward message // Forwards a message between chats or within a chat -// +// // Parameters: // Token - String - Bot token - token // OriginalID - String, Number - Original message ID - message // FromID - String, Number - Chat ID of the original message - from // ToID - String, Number - Target chat ID or ChatID*TopicID - to -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function ForwardMessage(Val Token, Val OriginalID, Val FromID, Val ToID) Export @@ -575,15 +575,15 @@ Function ForwardMessage(Val Token, Val OriginalID, Val FromID, Val ToID) Export OPI_TypeConversion.GetLine(OriginalID); OPI_TypeConversion.GetLine(FromID); OPI_TypeConversion.GetLine(ToID); - + URL = "api.telegram.org/bot" + Token + "/forwardMessage"; - + Parameters = New Structure; - OPI_Tools.AddField("from_chat_id", FromID , "String", Parameters); - OPI_Tools.AddField("message_id" , OriginalID, "String", Parameters); + OPI_Tools.AddField("from_chat_id", FromID , "String", Parameters); + OPI_Tools.AddField("message_id" , OriginalID, "String", Parameters); AddChatIdentifier(ToID, Parameters); - + Response = OPI_Tools.Get(URL, Parameters); Return Response; @@ -592,12 +592,12 @@ EndFunction // Generate keyboard from array of buttons // Generates a simple JSON keyboard from an array of buttons for a message or bottom panel -// +// // Parameters: -// ButtonArray - Array of String - Array of buttons - buttons +// ButtonArray - Array of String - Array of buttons - buttons // UnderMessage - Boolean - Keyboard under the message or on the bottom panel - under // OneByOne - Boolean - True > buttons are displayed in a column, False > in a row - column -// +// // Returns: // String - Keyboard JSON Function FormKeyboardFromButtonArray(Val ButtonArray @@ -607,7 +607,7 @@ Function FormKeyboardFromButtonArray(Val ButtonArray OPI_TypeConversion.GetBoolean(UnderMessage); OPI_TypeConversion.GetBoolean(OneByOne); OPI_TypeConversion.GetCollection(ButtonArray); - + If OneByOne Then Strings = CreateTallKeyboard(ButtonArray); Else @@ -615,7 +615,7 @@ Function FormKeyboardFromButtonArray(Val ButtonArray EndIf; If UnderMessage Then - ParameterStructure = New Structure("inline_keyboard,rows", Strings, 1); + ParameterStructure = New Structure("inline_keyboard,rows" , Strings, 1); Else ParameterStructure = New Structure("keyboard,resize_keyboard", Strings, True); EndIf; @@ -632,25 +632,25 @@ EndFunction // Ban // Bans a user in the selected chat -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID or ChatID*TopicID - chat // UserID - String, Number - Target user ID - user -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function Ban(Val Token, Val ChatID, Val UserID) Export String_ = "String"; OPI_TypeConversion.GetLine(Token); - + URL = "api.telegram.org/bot" + Token + "/banChatMember"; Parameters = New Structure; OPI_Tools.AddField("parse_mode", "Markdown" , String_, Parameters); - OPI_Tools.AddField("chat_id" , ChatID , String_, Parameters); - OPI_Tools.AddField("user_id" , UserID, String_, Parameters); + OPI_Tools.AddField("chat_id" , ChatID , String_, Parameters); + OPI_Tools.AddField("user_id" , UserID , String_, Parameters); Response = OPI_Tools.Get(URL, Parameters); @@ -660,26 +660,26 @@ EndFunction // Unban // Unbans a previously banned user -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID or ChatID*TopicID - chat // UserID - String, Number - Target user ID - user -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function Unban(Val Token, Val ChatID, Val UserID) Export String_ = "String"; OPI_TypeConversion.GetLine(Token); - + URL = "api.telegram.org/bot" + Token + "/unbanChatMember"; - Parameters = New Structure; - OPI_Tools.AddField("parse_mode" , "Markdown" , String_ , Parameters); - OPI_Tools.AddField("chat_id" , ChatID , String_ , Parameters); - OPI_Tools.AddField("user_id" , UserID, String_ , Parameters); - OPI_Tools.AddField("only_if_banned", False , "Boolean", Parameters); + Parameters = New Structure; + OPI_Tools.AddField("parse_mode" , "Markdown" , String_ , Parameters); + OPI_Tools.AddField("chat_id" , ChatID , String_ , Parameters); + OPI_Tools.AddField("user_id" , UserID , String_ , Parameters); + OPI_Tools.AddField("only_if_banned", False , "Boolean", Parameters); Response = OPI_Tools.Get(URL, Parameters); @@ -689,14 +689,14 @@ EndFunction // Create invitation link // Creates a link for joining a closed chat -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID or ChatID*TopicID - chat // Title - String - Invitation title - title // ExpirationDate - Date - Link expiration date (permanent if not specified) - expire // UserLimit - Number - User limit (infinite if not specified) - limit -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function CreateInvitationLink(Val Token @@ -707,16 +707,16 @@ Function CreateInvitationLink(Val Token String_ = "String"; OPI_TypeConversion.GetLine(Token); - + URL = "api.telegram.org/bot" + Token + "/createChatInviteLink"; - + Parameters = New Structure; - OPI_Tools.AddField("parse_mode" , "Markdown" , String_ , Parameters); - OPI_Tools.AddField("chat_id" , ChatID , String_ , Parameters); - OPI_Tools.AddField("name" , Title , String_ , Parameters); - OPI_Tools.AddField("member_limit" , UserLimit, String_ , Parameters); - OPI_Tools.AddField("expire_date" , ExpirationDate , "Date" , Parameters); - + OPI_Tools.AddField("parse_mode" , "Markdown" , String_ , Parameters); + OPI_Tools.AddField("chat_id" , ChatID , String_ , Parameters); + OPI_Tools.AddField("name" , Title , String_ , Parameters); + OPI_Tools.AddField("member_limit" , UserLimit , String_ , Parameters); + OPI_Tools.AddField("expire_date" , ExpirationDate , "Date" , Parameters); + Response = OPI_Tools.Get(URL, Parameters); Return Response; @@ -725,26 +725,26 @@ EndFunction // Pin message // Pins a message in the chat header -// +// // Parameters: // Token - String - Token - token // ChatID - String, Number - Target chat ID - chat // MessageID - String, Number - Target message ID - message -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function PinMessage(Val Token, Val ChatID, Val MessageID) Export - + String_ = "String"; OPI_TypeConversion.GetLine(Token); - + URL = "api.telegram.org/bot" + Token + "/pinChatMessage"; - + Parameters = New Structure; - OPI_Tools.AddField("parse_mode" , "Markdown" , String_ , Parameters); - OPI_Tools.AddField("chat_id" , ChatID , String_ , Parameters); - OPI_Tools.AddField("message_id" , MessageID, String_ , Parameters); - OPI_Tools.AddField("disable_notification", False , "Boolean", Parameters); + OPI_Tools.AddField("parse_mode" , "Markdown" , String_ , Parameters); + OPI_Tools.AddField("chat_id" , ChatID , String_ , Parameters); + OPI_Tools.AddField("message_id" , MessageID , String_ , Parameters); + OPI_Tools.AddField("disable_notification", False , "Boolean", Parameters); Response = OPI_Tools.Get(URL, Parameters); @@ -754,25 +754,25 @@ EndFunction // Unpin message // Unpins a message in the chat header -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID - chat // MessageID - String, Number - Target message ID - message -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function UnpinMessage(Val Token, Val ChatID, Val MessageID) Export - + String_ = "String"; OPI_TypeConversion.GetLine(Token); - + URL = "api.telegram.org/bot" + Token + "/unpinChatMessage"; - + Parameters = New Structure; OPI_Tools.AddField("parse_mode", "Markdown" , String_, Parameters); - OPI_Tools.AddField("chat_id" , ChatID , String_, Parameters); - OPI_Tools.AddField("message_id", MessageID, String_, Parameters); + OPI_Tools.AddField("chat_id" , ChatID , String_, Parameters); + OPI_Tools.AddField("message_id", MessageID , String_, Parameters); Response = OPI_Tools.Get(URL, Parameters); @@ -782,22 +782,22 @@ EndFunction // Get participant count // Gets the total number of chat participants -// +// // Parameters: // Token - String - Bot token - token // ChatID - String, Number - Target chat ID - chat -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function GetParticipantCount(Val Token, Val ChatID) Export OPI_TypeConversion.GetLine(Token); - + URL = "api.telegram.org/bot" + Token + "/getChatMemberCount"; - + Parameters = New Structure; OPI_Tools.AddField("parse_mode", "Markdown" , "String", Parameters); - OPI_Tools.AddField("chat_id" , ChatID , "String", Parameters); + OPI_Tools.AddField("chat_id" , ChatID , "String", Parameters); Response = OPI_Tools.Get(URL, Parameters); @@ -807,24 +807,24 @@ EndFunction // Delete message // Delete message from chat or channel -// +// // Parameters: // Token - String - Token - token // ChatID - String, Number - Target chat ID - chat // MessageID - String, Number - ID of message to delete - message -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function DeleteMessage(Val Token, Val ChatID, Val MessageID) Export - + OPI_TypeConversion.GetLine(Token); - + URL = "api.telegram.org/bot" + Token + "/deleteMessage"; - + Parameters = New Structure; OPI_Tools.AddField("message_id", MessageID, "String", Parameters); - OPI_Tools.AddField("chat_id" , ChatID , "String", Parameters); - + OPI_Tools.AddField("chat_id" , ChatID , "String", Parameters); + Response = OPI_Tools.Get(URL, Parameters); Return Response; @@ -836,206 +836,206 @@ EndFunction // Get avatar icon list // Gets the mapping of Emoji IDs for setting as forum theme icons -// +// // Parameters: // Token - String - Token - token -// +// // Returns: // Map Of KeyAndValue - Key > ID, Value > Emoji Function GetAvatarIconList(Val Token) Export - + OPI_TypeConversion.GetLine(Token); - - Result = "result"; - URL = "api.telegram.org/bot" + Token + "/getForumTopicIconStickers"; - Response = OPI_Tools.Get(URL); - Icons = Response[Result]; - + + Result = "result"; + URL = "api.telegram.org/bot" + Token + "/getForumTopicIconStickers"; + Response = OPI_Tools.Get(URL); + Icons = Response[Result]; + If Not ValueIsFilled(Icons) Then Return Response; - EndIf; - + EndIf; + Collection = New Map; - + For Each Icon In Icons Do Collection.Insert(Icon["custom_emoji_id"], Icon["emoji"]); EndDo; - + Return Collection; EndFunction // Create forum thread // Creates a new thread in the group with theme functionality enabled -// +// // Parameters: // Token - String - Token - token // ChatID - String, Number - Thread creation chat ID - forum // Title - String - Thread title - title // IconID - String - See GetAvatarIconList - icon -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function CreateForumThread(Val Token, Val ChatID, Val Title, Val IconID = "") Export - + Return ForumTopicManagement(Token, ChatID, Title, IconID); - + EndFunction // Edit forum thread // Creates a new thread in the group with theme functionality enabled -// +// // Parameters: // Token - String - Token - token // ChatID - String, Number - Thread creation chat ID - forum // ThreadID - String, Number - Thread ID - topic // Title - String - New title - title // IconID - String - See GetAvatarIconList - icon -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function EditForumTopic(Val Token , Val ChatID , Val ThreadID , Val Title = Undefined - , Val IconID = Undefined) Export - + , Val IconID = Undefined) Export + Return ForumTopicManagement(Token, ChatID, Title, IconID, ThreadID); EndFunction // Close forum thread // Closes the thread for new messages -// +// // Parameters: // Token - String - Token - token // ChatID - String, Number - Thread chat ID - forum // ThreadID - String, Number - Thread ID - topic -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function CloseForumThread(Val Token, Val ChatID, Val ThreadID = "") Export - - Return ManageForumThreadState(Token, ChatID, 2, ThreadID); - + + Return ManageForumThreadState(Token, ChatID, 2, ThreadID); + EndFunction // Open forum thread // Reopens a previously closed forum thread -// +// // Parameters: // Token - String - Token - token // ChatID - String, Number - Thread chat ID - forum // ThreadID - String, Number - Thread ID - topic -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function OpenForumThread(Val Token, Val ChatID, Val ThreadID = "") Export - - Return ManageForumThreadState(Token, ChatID, 1, ThreadID); - + + Return ManageForumThreadState(Token, ChatID, 1, ThreadID); + EndFunction // Delete forum thread // Deletes a forum thread -// +// // Parameters: // Token - String - Token - token // ChatID - String, Number - Thread chat ID - forum // ThreadID - String, Number - Thread ID - topic -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function DeleteForumTopic(Val Token, Val ChatID, Val ThreadID) Export - - Return ManageForumThreadState(Token, ChatID, 3, ThreadID); - + + Return ManageForumThreadState(Token, ChatID, 3, ThreadID); + EndFunction // Hide main forum thread // Hides the main forum thread -// +// // Parameters: // Token - String - Token - token // ChatID - String, Number - Thread chat ID - forum -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function HideMainForumTopic(Val Token, Val ChatID) Export - + Return ManageMainTopicVisibility(Token, ChatID, True); - + EndFunction // Show main forum thread // Shows a previously hidden main forum thread -// +// // Parameters: // Token - String - Token - token // ChatID - String, Number - Thread chat ID - forum -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function ShowMainForumTopic(Val Token, Val ChatID) Export - + Return ManageMainTopicVisibility(Token, ChatID, False); - + EndFunction // Edit main forum thread name // Edits the name of the main forum thread -// +// // Parameters: // Token - String - Token - token // ChatID - String, Number - Thread chat ID - forum // Title - String - New main thread name - title -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function EditMainForumTopicName(Val Token, Val ChatID, Val Title) Export - + OPI_TypeConversion.GetLine(Token); - + URL = "api.telegram.org/bot" + Token + "/editGeneralForumTopic"; - + Parameters = New Structure; OPI_Tools.AddField("chat_id", ChatID , "String", Parameters); - OPI_Tools.AddField("name" , Title, "String", Parameters); - + OPI_Tools.AddField("name" , Title , "String", Parameters); + Response = OPI_Tools.Get(URL, Parameters); - + Return Response; EndFunction // Clear thread's pinned messages list // Clears the list of pinned messages in the forum thread -// +// // Parameters: // Token - String - Token - token // ChatID - String, Number - Thread chat ID - forum // ThreadID - String, Number - Thread ID. Main if not filled - topic -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from Telegram Function ClearThreadPinnedMessagesList(Val Token, Val ChatID, Val ThreadID = "") Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(ChatID); OPI_TypeConversion.GetLine(ThreadID); - + Parameters = New Structure; - OPI_Tools.AddField("chat_id" , ChatID, "String", Parameters); + OPI_Tools.AddField("chat_id" , ChatID , "String", Parameters); OPI_Tools.AddField("message_thread_id", ThreadID, "String", Parameters); - + If ValueIsFilled(ThreadID) Then Method = "/unpinAllForumTopicMessages"; Else Method = "/unpinAllGeneralForumTopicMessages"; EndIf; - - URL = "api.telegram.org/bot" + Token + Method; + + URL = "api.telegram.org/bot" + Token + Method; Response = OPI_Tools.Get(URL, Parameters); - + Return Response; EndFunction @@ -1061,27 +1061,27 @@ Function SendFile(Val Token OPI_TypeConversion.GetLine(Text); OPI_Tools.ReplaceSpecialCharacters(Text, Markup); - + If Not ValueIsFilled(FileName) Then FileName = ConvertFileData(File, View, ""); Else OPI_TypeConversion.GetBinaryData(File); EndIf; - + FileName = View + "|" + FileName; - + Parameters = New Structure; - OPI_Tools.AddField("parse_mode" , Markup , "String" , Parameters); - OPI_Tools.AddField("caption" , Text , "String" , Parameters); + OPI_Tools.AddField("parse_mode" , Markup , "String" , Parameters); + OPI_Tools.AddField("caption" , Text , "String" , Parameters); OPI_Tools.AddField("reply_markup", Keyboard, "FileString", Parameters); - + AddChatIdentifier(ChatID, Parameters); FileMapping = New Map; FileMapping.Insert(FileName, File); - Method = DetermineSendMethod(View); - URL = "api.telegram.org/bot" + Token + Method; + Method = DetermineSendMethod(View); + URL = "api.telegram.org/bot" + Token + Method; Response = OPI_Tools.PostMultipart(URL, Parameters, FileMapping, "mixed"); Return Response; @@ -1090,56 +1090,56 @@ EndFunction Function ForumTopicManagement(Val Token , Val ChatID - , Val Title = Undefined - , Val IconID = Undefined + , Val Title = Undefined + , Val IconID = Undefined , Val ThreadID = "") - + String_ = "String"; OPI_TypeConversion.GetLine(Token); - + Parameters = New Structure; - OPI_Tools.AddField("name" , Title, String_, Parameters); - OPI_Tools.AddField("chat_id" , ChatID , String_, Parameters); - OPI_Tools.AddField("icon_custom_emoji_id", IconID , String_, Parameters); - OPI_Tools.AddField("message_thread_id" , ThreadID , String_, Parameters); - + OPI_Tools.AddField("name" , Title , String_, Parameters); + OPI_Tools.AddField("chat_id" , ChatID , String_, Parameters); + OPI_Tools.AddField("icon_custom_emoji_id", IconID , String_, Parameters); + OPI_Tools.AddField("message_thread_id" , ThreadID , String_, Parameters); + If ValueIsFilled(ThreadID) Then - Method = "/editForumTopic"; - Else - Method = "/createForumTopic"; + Method = "/editForumTopic"; + Else + Method = "/createForumTopic"; EndIf; - + Response = OPI_Tools.Get("api.telegram.org/bot" + Token + Method, Parameters); - + Return Response; EndFunction -Function ManageForumThreadState(Val Token, Val ChatID, Val Status, Val ThreadID = "") - +Function ManageForumThreadState(Val Token, Val ChatID, Val Status, Val ThreadID = "") + OPI_TypeConversion.GetLine(Token); - + If ValueIsFilled(ThreadID) Then Forum = "Forum"; Else Forum = "GeneralForum"; EndIf; - + Method = DetermineForumManagementMethod(Status, Forum); - + Parameters = New Structure; - OPI_Tools.AddField("chat_id" , ChatID, "String", Parameters); + OPI_Tools.AddField("chat_id" , ChatID , "String", Parameters); OPI_Tools.AddField("message_thread_id", ThreadID, "String", Parameters); - - URL = "api.telegram.org/bot" + Token + Method; + + URL = "api.telegram.org/bot" + Token + Method; Response = OPI_Tools.Get(URL, Parameters); Return Response; - + EndFunction Function ManageMainTopicVisibility(Val Token, Val ChatID, Val Hide) - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetBoolean(Hide); @@ -1148,71 +1148,71 @@ Function ManageMainTopicVisibility(Val Token, Val ChatID, Val Hide) Else Method = "/unhideGeneralForumTopic"; EndIf; - + Parameters = New Structure; OPI_Tools.AddField("chat_id", ChatID, "String", Parameters); - - URL = "api.telegram.org/bot" + Token + Method; + + URL = "api.telegram.org/bot" + Token + Method; Response = OPI_Tools.Get(URL, Parameters); - + Return Response; -EndFunction +EndFunction -Function DetermineForumManagementMethod(Val Status, Val Forum) - - Open = 1; - Close = 2; +Function DetermineForumManagementMethod(Val Status, Val Forum) + + Open = 1; + Close = 2; Delete = 3; - - If Status = Open Then - Method = "/reopen" + Forum + "Topic"; + + If Status = Open Then + Method = "/reopen" + Forum + "Topic"; ElsIf Status = Close Then - Method = "/close" + Forum + "Topic"; + Method = "/close" + Forum + "Topic"; ElsIf Status = Delete Then - Method = "/deleteForumTopic"; - Else + Method = "/deleteForumTopic"; + Else Raise "Incorrect forum management status"; EndIf; - + Return Method; EndFunction Function CreateTallKeyboard(Val ButtonArray) - + Strings = New Array; - + For Each Button In ButtonArray Do Buttons = New Array; - Button = OPI_Tools.NumberToString(Button); + Button = OPI_Tools.NumberToString(Button); Buttons.Add(New Structure("text,callback_data", Button, Button)); Strings.Add(Buttons); EndDo; Return Strings; - + EndFunction Function CreateLongKeyboard(Val ButtonArray) - + Strings = New Array; Buttons = New Array; - + For Each Button In ButtonArray Do Button = OPI_Tools.NumberToString(Button); Buttons.Add(New Structure("text,callback_data", Button, Button)); EndDo; - + Strings.Add(Buttons); - + Return Strings; EndFunction Function DetermineSendMethod(Val View) - - If View = "photo" Then + + If View = "photo" Then Method = "/sendPhoto"; ElsIf View = "video" Then Method = "/sendVideo"; @@ -1225,48 +1225,48 @@ Function DetermineSendMethod(Val View) EndIf; Return Method; - + EndFunction Function ConvertFileData(File, View, Counter) - + FileName = ""; - + If TypeOf(File) = Type("String") And View = "document" Then - + CurrentFile = New File(File); - FileName = CurrentFile.Name; - + FileName = CurrentFile.Name; + EndIf; - + If Not ValueIsFilled(FileName) Then FileName = View + String(Counter); - - If View = "animation" Then - FileName = FileName + ".gif"; + + If View = "animation" Then + FileName = FileName + ".gif"; EndIf; - + EndIf; - + OPI_TypeConversion.GetBinaryData(File); - + Return FileName; - + EndFunction Procedure ConvertFilesToMedia(FileMapping, Text, Media) - + OPI_TypeConversion.GetCollection(FileMapping); OPI_TypeConversion.GetLine(Text); - + If TypeOf(FileMapping) <> Type("Map") Then // !OInt RaiseException("Failed to get information from json media!"); Return; EndIf; - + TempMap = New Map; Counter = 0; - + For Each CurrentFile In FileMapping Do CurrentData = CurrentFile.Key; @@ -1290,25 +1290,25 @@ Procedure ConvertFilesToMedia(FileMapping, Text, Media) EndDo; - Media = OPI_Tools.JSONString(Media); - FileMapping = TempMap; - + Media = OPI_Tools.JSONString(Media); + FileMapping = TempMap; + EndProcedure Procedure AddChatIdentifier(Val ChatID, Parameters) - - ChatID = OPI_Tools.NumberToString(ChatID); + + ChatID = OPI_Tools.NumberToString(ChatID); ChatArray = StrSplit(ChatID, "*", False); - + If ChatArray.Count() > 1 Then - - ChatID = ChatArray[0]; + + ChatID = ChatArray[0]; ThreadID = ChatArray[1]; - + Parameters.Insert("message_thread_id", ThreadID); - + EndIf; - + Parameters.Insert("chat_id", ChatID); EndProcedure diff --git a/src/en/OPI/src/CommonModules/OPI_TestDataRetrieval/Module.bsl b/src/en/OPI/src/CommonModules/OPI_TestDataRetrieval/Module.bsl index fe67336b0b..0c4e972e26 100644 --- a/src/en/OPI/src/CommonModules/OPI_TestDataRetrieval/Module.bsl +++ b/src/en/OPI/src/CommonModules/OPI_TestDataRetrieval/Module.bsl @@ -46,404 +46,404 @@ #Region Internal Function GetTestingSectionMapping() Export - + StandardDependencies = "[Decode, Build]"; - GoogleDependencies = "Testing-GoogleWorkspace"; - + GoogleDependencies = "Testing-GoogleWorkspace"; + Sections = New Structure; - Sections.Insert("Telegram" , StandardDependencies); - Sections.Insert("VK" , StandardDependencies); - Sections.Insert("Viber" , StandardDependencies); - Sections.Insert("Twitter" , StandardDependencies); - Sections.Insert("YandexDisk" , StandardDependencies); + Sections.Insert("Telegram" , StandardDependencies); + Sections.Insert("VK" , StandardDependencies); + Sections.Insert("Viber" , StandardDependencies); + Sections.Insert("Twitter" , StandardDependencies); + Sections.Insert("YandexDisk" , StandardDependencies); Sections.Insert("GoogleWorkspace", StandardDependencies); - Sections.Insert("GoogleCalendar" , GoogleDependencies); - Sections.Insert("GoogleDrive" , GoogleDependencies); - Sections.Insert("GoogleSheets" , GoogleDependencies); - Sections.Insert("Notion" , StandardDependencies); - Sections.Insert("Slack" , StandardDependencies); - Sections.Insert("Airtable" , StandardDependencies); - Sections.Insert("Dropbox" , StandardDependencies); - Sections.Insert("Bitrix24" , StandardDependencies); - + Sections.Insert("GoogleCalendar" , GoogleDependencies); + Sections.Insert("GoogleDrive" , GoogleDependencies); + Sections.Insert("GoogleSheets" , GoogleDependencies); + Sections.Insert("Notion" , StandardDependencies); + Sections.Insert("Slack" , StandardDependencies); + Sections.Insert("Airtable" , StandardDependencies); + Sections.Insert("Dropbox" , StandardDependencies); + Sections.Insert("Bitrix24" , StandardDependencies); + Return Sections; - + EndFunction Function GetTestTable() Export - - Telegram = "Telegram"; + + Telegram = "Telegram"; VKontakte = "VK"; - YDisk = "YandexDisk"; - Calendar = "GoogleCalendar"; - Twitter = "Twitter"; - Viber = "Viber"; - Drive = "GoogleDrive"; - VSpace = "GoogleWorkspace"; - Notion = "Notion"; - Slack = "Slack"; - Tables = "GoogleSheets"; - AirT = "Airtable"; - Dropbox = "Dropbox"; - Bitrix = "Bitrix24"; - + YDisk = "YandexDisk"; + Calendar = "GoogleCalendar"; + Twitter = "Twitter"; + Viber = "Viber"; + Drive = "GoogleDrive"; + VSpace = "GoogleWorkspace"; + Notion = "Notion"; + Slack = "Slack"; + Tables = "GoogleSheets"; + AirT = "Airtable"; + Dropbox = "Dropbox"; + Bitrix = "Bitrix24"; + TestTable = New ValueTable; TestTable.Columns.Add("Method"); TestTable.Columns.Add("Synonym"); TestTable.Columns.Add("Section"); - - NewTest(TestTable, "TelegramAPI_GetBotInfo" , "Get bot information" , Telegram); - NewTest(TestTable, "TelegramAPI_GetUpdates" , "Get updates" , Telegram); - NewTest(TestTable, "TelegramAPI_SetWebhook" , "Set Webhook" , Telegram); - NewTest(TestTable, "TelegramAPI_SendTextMessage" , "Send text message" , Telegram); - NewTest(TestTable, "TelegramAPI_SendImage" , "Send image" , Telegram); - NewTest(TestTable, "TelegramAPI_SendVideo" , "Send video" , Telegram); - NewTest(TestTable, "TelegramAPI_SendAudio" , "Send audio" , Telegram); - NewTest(TestTable, "TelegramAPI_SendDocument" , "Send document" , Telegram); - NewTest(TestTable, "TelegramAPI_SendGIF" , "Send GIF" , Telegram); - NewTest(TestTable, "TelegramAPI_SendMediaGroup" , "Send mediagroup" , Telegram); - NewTest(TestTable, "TelegramAPI_SendLocation" , "Send location" , Telegram); - NewTest(TestTable, "TelegramAPI_SendContact" , "Send contact" , Telegram); - NewTest(TestTable, "TelegramAPI_SendPoll" , "Send poll" , Telegram); - NewTest(TestTable, "TelegramAPI_ForwardMessage" , "Forward message" , Telegram); - NewTest(TestTable, "TelegramAPI_BanUnban" , "Ban/Unban" , Telegram); - NewTest(TestTable, "TelegramAPI_CreateInvitationLink" , "Create invitation link" , Telegram); - NewTest(TestTable, "TelegramAPI_PinUnpinMessage" , "Pin/Unpin message" , Telegram); - NewTest(TestTable, "TelegramAPI_GetMemberCount" , "Get participant count" , Telegram); - NewTest(TestTable, "TelegramAPI_GetForumAvatarsList", "Get forum avatars list", Telegram); + + NewTest(TestTable, "TelegramAPI_GetBotInfo" , "Get bot information" , Telegram); + NewTest(TestTable, "TelegramAPI_GetUpdates" , "Get updates" , Telegram); + NewTest(TestTable, "TelegramAPI_SetWebhook" , "Set Webhook" , Telegram); + NewTest(TestTable, "TelegramAPI_SendTextMessage" , "Send text message" , Telegram); + NewTest(TestTable, "TelegramAPI_SendImage" , "Send image" , Telegram); + NewTest(TestTable, "TelegramAPI_SendVideo" , "Send video" , Telegram); + NewTest(TestTable, "TelegramAPI_SendAudio" , "Send audio" , Telegram); + NewTest(TestTable, "TelegramAPI_SendDocument" , "Send document" , Telegram); + NewTest(TestTable, "TelegramAPI_SendGIF" , "Send GIF" , Telegram); + NewTest(TestTable, "TelegramAPI_SendMediaGroup" , "Send mediagroup" , Telegram); + NewTest(TestTable, "TelegramAPI_SendLocation" , "Send location" , Telegram); + NewTest(TestTable, "TelegramAPI_SendContact" , "Send contact" , Telegram); + NewTest(TestTable, "TelegramAPI_SendPoll" , "Send poll" , Telegram); + NewTest(TestTable, "TelegramAPI_ForwardMessage" , "Forward message" , Telegram); + NewTest(TestTable, "TelegramAPI_BanUnban" , "Ban/Unban" , Telegram); + NewTest(TestTable, "TelegramAPI_CreateInvitationLink" , "Create invitation link" , Telegram); + NewTest(TestTable, "TelegramAPI_PinUnpinMessage" , "Pin/Unpin message" , Telegram); + NewTest(TestTable, "TelegramAPI_GetMemberCount" , "Get participant count" , Telegram); + NewTest(TestTable, "TelegramAPI_GetForumAvatarsList" , "Get forum avatars list" , Telegram); NewTest(TestTable, "TelegramAPI_CreateDeleteForumTopic" , "Create/Delete forum topic" , Telegram); - NewTest(TestTable, "TelegramAPI_ChangeMainTopicName" , "Change main topic name" , Telegram); - NewTest(TestTable, "TelegramAPI_HideShowMainTopic" , "Hide/Show main topic" , Telegram); - - NewTest(TestTable, "VKAPI_CreateTokenLink" , "Create token retrieval link", VKontakte); - NewTest(TestTable, "VKAPI_CreateDeletePost" , "Create/Delete post" , VKontakte); - NewTest(TestTable, "VKAPI_CreateCompositePost" , "Create/Delete composite post" , VKontakte); - NewTest(TestTable, "VKAPI_CreatePoll" , "Create poll" , VKontakte); - NewTest(TestTable, "VKAPI_SaveDeleteImage" , "Add/Delete image" , VKontakte); - NewTest(TestTable, "VKAPI_CreateStory" , "Create story" , VKontakte); - NewTest(TestTable, "VKAPI_DiscussionMethods" , "Actions with discussions" , VKontakte); - NewTest(TestTable, "VKAPI_LikeRepostComment" , "Like/Repost/Comment" , VKontakte); - NewTest(TestTable, "VKAPI_GetStatistics" , "Get statistics" , VKontakte); - NewTest(TestTable, "VKAPI_GetPostStatistics" , "Get post statistics" , VKontakte); - NewTest(TestTable, "VKAPI_CreateAdCampaign" , "Create advertising campaign" , VKontakte); - NewTest(TestTable, "VKAPI_SendMessage" , "Send message" , VKontakte); - NewTest(TestTable, "VKAPI_GetProductCategories" , "Get product categories" , VKontakte); - NewTest(TestTable, "VKAPI_CreateProductSelection" , "Create product and selection" , VKontakte); + NewTest(TestTable, "TelegramAPI_ChangeMainTopicName" , "Change main topic name" , Telegram); + NewTest(TestTable, "TelegramAPI_HideShowMainTopic" , "Hide/Show main topic" , Telegram); + + NewTest(TestTable, "VKAPI_CreateTokenLink" , "Create token retrieval link" , VKontakte); + NewTest(TestTable, "VKAPI_CreateDeletePost" , "Create/Delete post" , VKontakte); + NewTest(TestTable, "VKAPI_CreateCompositePost" , "Create/Delete composite post" , VKontakte); + NewTest(TestTable, "VKAPI_CreatePoll" , "Create poll" , VKontakte); + NewTest(TestTable, "VKAPI_SaveDeleteImage" , "Add/Delete image" , VKontakte); + NewTest(TestTable, "VKAPI_CreateStory" , "Create story" , VKontakte); + NewTest(TestTable, "VKAPI_DiscussionMethods" , "Actions with discussions" , VKontakte); + NewTest(TestTable, "VKAPI_LikeRepostComment" , "Like/Repost/Comment" , VKontakte); + NewTest(TestTable, "VKAPI_GetStatistics" , "Get statistics" , VKontakte); + NewTest(TestTable, "VKAPI_GetPostStatistics" , "Get post statistics" , VKontakte); + NewTest(TestTable, "VKAPI_CreateAdCampaign" , "Create advertising campaign" , VKontakte); + NewTest(TestTable, "VKAPI_SendMessage" , "Send message" , VKontakte); + NewTest(TestTable, "VKAPI_GetProductCategories" , "Get product categories" , VKontakte); + NewTest(TestTable, "VKAPI_CreateProductSelection" , "Create product and selection" , VKontakte); NewTest(TestTable, "VKAPI_CreateProductWithProperties" , "Create product with properties" , VKontakte); - NewTest(TestTable, "VKAPI_GetProductList" , "Get product list" , VKontakte); - NewTest(TestTable, "VKAPI_GetSelectionList" , "Get selection list" , VKontakte); - NewTest(TestTable, "VKAPI_GetPropertyList" , "Get property list" , VKontakte); - NewTest(TestTable, "VKAPI_GetOrderList" , "Get order list" , VKontakte); - NewTest(TestTable, "VKAPI_UploadVideo" , "Upload video" , VKontakte); - - NewTest(TestTable, "YDisk_GetDiskInfo" , "Get disk information" , YDisk); - NewTest(TestTable, "YDisk_CreateFolder" , "Create folder" , YDisk); - NewTest(TestTable, "YDisk_UploadByUrlAndGetObject", "Upload by URL and get" , YDisk); - NewTest(TestTable, "YDisk_UploadDeleteFile" , "Upload/Delete file" , YDisk); - NewTest(TestTable, "YDisk_CreateObjectCopy" , "Create object copy" , YDisk); - NewTest(TestTable, "YDisk_GetDownloadLink" , "Get download link" , YDisk); - NewTest(TestTable, "YDisk_GetFileList" , "Get list of files" , YDisk); - NewTest(TestTable, "YDisk_MoveObject" , "Move object" , YDisk); - NewTest(TestTable, "YDisk_PublicObjectActions" , "Actions with public objects", YDisk); - NewTest(TestTable, "YDisk_GetPublishedList" , "Get published list" , YDisk); - + NewTest(TestTable, "VKAPI_GetProductList" , "Get product list" , VKontakte); + NewTest(TestTable, "VKAPI_GetSelectionList" , "Get selection list" , VKontakte); + NewTest(TestTable, "VKAPI_GetPropertyList" , "Get property list" , VKontakte); + NewTest(TestTable, "VKAPI_GetOrderList" , "Get order list" , VKontakte); + NewTest(TestTable, "VKAPI_UploadVideo" , "Upload video" , VKontakte); + + NewTest(TestTable, "YDisk_GetDiskInfo" , "Get disk information" , YDisk); + NewTest(TestTable, "YDisk_CreateFolder" , "Create folder" , YDisk); + NewTest(TestTable, "YDisk_UploadByUrlAndGetObject", "Upload by URL and get" , YDisk); + NewTest(TestTable, "YDisk_UploadDeleteFile" , "Upload/Delete file" , YDisk); + NewTest(TestTable, "YDisk_CreateObjectCopy" , "Create object copy" , YDisk); + NewTest(TestTable, "YDisk_GetDownloadLink" , "Get download link" , YDisk); + NewTest(TestTable, "YDisk_GetFileList" , "Get list of files" , YDisk); + NewTest(TestTable, "YDisk_MoveObject" , "Move object" , YDisk); + NewTest(TestTable, "YDisk_PublicObjectActions" , "Actions with public objects", YDisk); + NewTest(TestTable, "YDisk_GetPublishedList" , "Get published list" , YDisk); + NewTest(TestTable, "GV_GetAuthorizationLink" , "Get authorization link" , VSpace); - NewTest(TestTable, "GV_GetToken" , "Get token" , VSpace); - NewTest(TestTable, "GV_UpdateToken" , "Refresh token" , VSpace); - - NewTest(TestTable, "GC_GetCalendarList" , "Get list of calendars" , Calendar); + NewTest(TestTable, "GV_GetToken" , "Get token" , VSpace); + NewTest(TestTable, "GV_UpdateToken" , "Refresh token" , VSpace); + + NewTest(TestTable, "GC_GetCalendarList" , "Get list of calendars" , Calendar); NewTest(TestTable, "GC_CreateDeleteCalendar" , "Create/Delete calendar" , Calendar); - NewTest(TestTable, "GC_CreateDeleteEvent" , "Create/Delete event" , Calendar); - NewTest(TestTable, "GC_GetEventList" , "Get list of events" , Calendar); - - NewTest(TestTable, "GD_GetCatalogList" , "Get list of directories" , Drive); - NewTest(TestTable, "GD_UploadDeleteFile" , "Upload/Delete file" , Drive); - NewTest(TestTable, "GD_CreateDeleteComment" , "Create/Delete Comment" , Drive); - NewTest(TestTable, "GD_CreateCatalog" , "Create/Delete catalog" , Drive); - - NewTest(TestTable, "GT_CreateTable" , "Create table" , Tables); - NewTest(TestTable, "GT_GetTable" , "Get table" , Tables); + NewTest(TestTable, "GC_CreateDeleteEvent" , "Create/Delete event" , Calendar); + NewTest(TestTable, "GC_GetEventList" , "Get list of events" , Calendar); + + NewTest(TestTable, "GD_GetCatalogList" , "Get list of directories" , Drive); + NewTest(TestTable, "GD_UploadDeleteFile" , "Upload/Delete file" , Drive); + NewTest(TestTable, "GD_CreateDeleteComment" , "Create/Delete Comment" , Drive); + NewTest(TestTable, "GD_CreateCatalog" , "Create/Delete catalog" , Drive); + + NewTest(TestTable, "GT_CreateTable" , "Create table" , Tables); + NewTest(TestTable, "GT_GetTable" , "Get table" , Tables); NewTest(TestTable, "GT_FillClearCells" , "Fill/Clear cells" , Tables); - + NewTest(TestTable, "Twitter_GetAuthorizationLink" , "Get authorization link" , Twitter); - NewTest(TestTable, "Twitter_UpdateToken" , "Refresh token" , Twitter); - NewTest(TestTable, "Twitter_CreateTextTweet" , "Text tweet" , Twitter); - NewTest(TestTable, "Twitter_CreateTweetWithImage" , "Tweet with image" , Twitter); - NewTest(TestTable, "Twitter_CreateTweetWithVideo" , "Tweet with video" , Twitter); - NewTest(TestTable, "Twitter_CreateTweetWithGif" , "Tweet with gif" , Twitter); - NewTest(TestTable, "Twitter_CreateTweetWithPoll" , "Tweet with poll" , Twitter); - - NewTest(TestTable, "Viber_GetChannelInfo" , "Get channel info" , Viber); - NewTest(TestTable, "Viber_GetUserData" , "Get user data" , Viber); - NewTest(TestTable, "Viber_GetOnlineUsers" , "Get online users" , Viber); + NewTest(TestTable, "Twitter_UpdateToken" , "Refresh token" , Twitter); + NewTest(TestTable, "Twitter_CreateTextTweet" , "Text tweet" , Twitter); + NewTest(TestTable, "Twitter_CreateTweetWithImage" , "Tweet with image" , Twitter); + NewTest(TestTable, "Twitter_CreateTweetWithVideo" , "Tweet with video" , Twitter); + NewTest(TestTable, "Twitter_CreateTweetWithGif" , "Tweet with gif" , Twitter); + NewTest(TestTable, "Twitter_CreateTweetWithPoll" , "Tweet with poll" , Twitter); + + NewTest(TestTable, "Viber_GetChannelInfo" , "Get channel info" , Viber); + NewTest(TestTable, "Viber_GetUserData" , "Get user data" , Viber); + NewTest(TestTable, "Viber_GetOnlineUsers" , "Get online users" , Viber); NewTest(TestTable, "Viber_SendTextMessage" , "Send text message" , Viber); - NewTest(TestTable, "Viber_SendImage" , "Send image" , Viber); - NewTest(TestTable, "Viber_SendFile" , "SendFile" , Viber); - NewTest(TestTable, "Viber_SendContact" , "Send contact" , Viber); - NewTest(TestTable, "Viber_SendLocation" , "Send location" , Viber); - NewTest(TestTable, "Viber_SendLink" , "Send link" , Viber); - - NewTest(TestTable, "Notion_CreatePage" , "Create page" , Notion); - NewTest(TestTable, "Notion_CreateEditDatabase" , "Create/Edit database" , Notion); - NewTest(TestTable, "Notion_GetPageInfo" , "Get page info" , Notion); - NewTest(TestTable, "Notion_GetDatabaseInfo" , "Get database info" , Notion); + NewTest(TestTable, "Viber_SendImage" , "Send image" , Viber); + NewTest(TestTable, "Viber_SendFile" , "SendFile" , Viber); + NewTest(TestTable, "Viber_SendContact" , "Send contact" , Viber); + NewTest(TestTable, "Viber_SendLocation" , "Send location" , Viber); + NewTest(TestTable, "Viber_SendLink" , "Send link" , Viber); + + NewTest(TestTable, "Notion_CreatePage" , "Create page" , Notion); + NewTest(TestTable, "Notion_CreateEditDatabase" , "Create/Edit database" , Notion); + NewTest(TestTable, "Notion_GetPageInfo" , "Get page info" , Notion); + NewTest(TestTable, "Notion_GetDatabaseInfo" , "Get database info" , Notion); NewTest(TestTable, "Notion_CreatePageInDatabase" , "Create page in database" , Notion); - NewTest(TestTable, "Notion_EditPageProperties" , "Edit page properties" , Notion); - NewTest(TestTable, "Notion_CreateDeleteBlock" , "Create/Delete block" , Notion); - NewTest(TestTable, "Notion_GetUsers" , "Get users" , Notion); - NewTest(TestTable, "Notion_GetUserData" , "Get user data" , Notion); - - NewTest(TestTable, "Slack_GetBotInfo" , "Get bot information" , Slack); - NewTest(TestTable, "Slack_GetUserList" , "Get user list" , Slack); - NewTest(TestTable, "Slack_GetRegionList" , "Get region list" , Slack); - NewTest(TestTable, "Slack_SendDeleteMessage" , "Send/Delete message" , Slack); - NewTest(TestTable, "Slack_SendDeleteEphemeral" , "Send/Delete ephemeral" , Slack); - NewTest(TestTable, "Slack_GetScheduledMessages" , "Get scheduled messages" , Slack); - NewTest(TestTable, "Slack_CreateArchiveChannel" , "Create/Archive channel" , Slack); - NewTest(TestTable, "Slack_GetChannelList" , "Get channel list" , Slack); - NewTest(TestTable, "Slack_OpenCloseDialog" , "Open/Close dialog" , Slack); - NewTest(TestTable, "Slack_GetFileList" , "Get list of files" , Slack); - NewTest(TestTable, "Slack_UploadDeleteFile" , "Upload/Delete file" , Slack); - NewTest(TestTable, "Slack_GetExternalFileList" , "Get external file list" , Slack); + NewTest(TestTable, "Notion_EditPageProperties" , "Edit page properties" , Notion); + NewTest(TestTable, "Notion_CreateDeleteBlock" , "Create/Delete block" , Notion); + NewTest(TestTable, "Notion_GetUsers" , "Get users" , Notion); + NewTest(TestTable, "Notion_GetUserData" , "Get user data" , Notion); + + NewTest(TestTable, "Slack_GetBotInfo" , "Get bot information" , Slack); + NewTest(TestTable, "Slack_GetUserList" , "Get user list" , Slack); + NewTest(TestTable, "Slack_GetRegionList" , "Get region list" , Slack); + NewTest(TestTable, "Slack_SendDeleteMessage" , "Send/Delete message" , Slack); + NewTest(TestTable, "Slack_SendDeleteEphemeral" , "Send/Delete ephemeral" , Slack); + NewTest(TestTable, "Slack_GetScheduledMessages" , "Get scheduled messages" , Slack); + NewTest(TestTable, "Slack_CreateArchiveChannel" , "Create/Archive channel" , Slack); + NewTest(TestTable, "Slack_GetChannelList" , "Get channel list" , Slack); + NewTest(TestTable, "Slack_OpenCloseDialog" , "Open/Close dialog" , Slack); + NewTest(TestTable, "Slack_GetFileList" , "Get list of files" , Slack); + NewTest(TestTable, "Slack_UploadDeleteFile" , "Upload/Delete file" , Slack); + NewTest(TestTable, "Slack_GetExternalFileList" , "Get external file list" , Slack); NewTest(TestTable, "Slack_UploadDeleteExternalFile" , "Upload/Delete external file" , Slack); - - NewTest(TestTable, "AT_CreateDatabase" , "Create/Edit database" , AirT); - NewTest(TestTable, "AT_CreateTable" , "Create/Edit table" , AirT); - NewTest(TestTable, "AT_CreateField" , "Create/Edit field" , AirT); + + NewTest(TestTable, "AT_CreateDatabase" , "Create/Edit database" , AirT); + NewTest(TestTable, "AT_CreateTable" , "Create/Edit table" , AirT); + NewTest(TestTable, "AT_CreateField" , "Create/Edit field" , AirT); NewTest(TestTable, "AT_CreateDeleteRecords" , "Create/Delete records" , AirT); - - NewTest(TestTable, "DropboxAPI_GetUpdateToken" , "Get/Update token" , Dropbox); - NewTest(TestTable, "DropboxAPI_UploadFile" , "Upload file" , Dropbox); - NewTest(TestTable, "DropboxAPI_UploadFileByURL" , "Upload file by URL" , Dropbox); - NewTest(TestTable, "DropboxAPI_CreateFolder" , "Create folder" , Dropbox); - NewTest(TestTable, "DropboxAPI_CreateDeleteTag" , "Create/Delete tag" , Dropbox); - NewTest(TestTable, "DropboxAPI_GetAccount" , "Get account data" , Dropbox); - NewTest(TestTable, "DropboxAPI_AccessManagement" , "Access management" , Dropbox); + + NewTest(TestTable, "DropboxAPI_GetUpdateToken" , "Get/Update token" , Dropbox); + NewTest(TestTable, "DropboxAPI_UploadFile" , "Upload file" , Dropbox); + NewTest(TestTable, "DropboxAPI_UploadFileByURL" , "Upload file by URL" , Dropbox); + NewTest(TestTable, "DropboxAPI_CreateFolder" , "Create folder" , Dropbox); + NewTest(TestTable, "DropboxAPI_CreateDeleteTag" , "Create/Delete tag" , Dropbox); + NewTest(TestTable, "DropboxAPI_GetAccount" , "Get account data" , Dropbox); + NewTest(TestTable, "DropboxAPI_AccessManagement" , "Access management" , Dropbox); NewTest(TestTable, "DropboxAPI_GetFolderFileList" , "Get list of folder files" , Dropbox); - - NewTest(TestTable, "B24_TokenManagment" , "Token management" , Bitrix); - NewTest(TestTable, "B24_ServerTime" , "Server time" , Bitrix); - NewTest(TestTable, "B24_PostsManagment" , "Posts managment" , Bitrix); - NewTest(TestTable, "B24_TaskManagment" , "Tasks managment" , Bitrix); - NewTest(TestTable, "B24_CommentsManagment" , "Comments managment" , Bitrix); - NewTest(TestTable, "B24_WorkingWithDrive" , "Working with drive" , Bitrix); - NewTest(TestTable, "B24_Kanban" , "Kanban" , Bitrix); - NewTest(TestTable, "B24_Timekeeping" , "Timekeeping" , Bitrix); - NewTest(TestTable, "B24_ChatManagment" , "Chats works" , Bitrix); + + NewTest(TestTable, "B24_TokenManagment" , "Token management" , Bitrix); + NewTest(TestTable, "B24_ServerTime" , "Server time" , Bitrix); + NewTest(TestTable, "B24_PostsManagment" , "Posts managment" , Bitrix); + NewTest(TestTable, "B24_TaskManagment" , "Tasks managment" , Bitrix); + NewTest(TestTable, "B24_CommentsManagment" , "Comments managment" , Bitrix); + NewTest(TestTable, "B24_WorkingWithDrive" , "Working with drive" , Bitrix); + NewTest(TestTable, "B24_Kanban" , "Kanban" , Bitrix); + NewTest(TestTable, "B24_Timekeeping" , "Timekeeping" , Bitrix); + NewTest(TestTable, "B24_ChatManagment" , "Chats works" , Bitrix); NewTest(TestTable, "B24_NotificationsManagment" , "Notifications managment" , Bitrix); - + Return TestTable; - -EndFunction + +EndFunction Function ExpectsThat(Value) Export - + Try - - Module = GetCommonModule("ЮТест"); + + Module = GetCommonModule("ЮТест"); Ожидаем = TypeOf(Module) = Type("CommonModule"); - Return Module.ОжидаетЧто(Value); - + Return Module.ОжидаетЧто(Value); + Except Return Ожидаем.Что(Value); EndTry; - + EndFunction Function FormYAXTests() Export - - Module = GetCommonModule("ЮТТесты"); - Sections = GetTestingSectionMapping(); + + Module = GetCommonModule("ЮТТесты"); + Sections = GetTestingSectionMapping(); TestTable = GetTestTable(); - + For Each Section In Sections Do - + CurrentSection = Section.Key; - Filter = New Structure("Section", CurrentSection); - SectionTests = TestTable.FindRows(Filter); - + Filter = New Structure("Section", CurrentSection); + SectionTests = TestTable.FindRows(Filter); + Set = Module.ДобавитьТестовыйНабор(CurrentSection); - + For Each Test In SectionTests Do Set.ДобавитьСерверныйТест(Test.Method, Test.Synonym); EndDo; - + EndDo; - + Return ""; - + EndFunction Function FormAssertsTests() Export - - TestTable = GetTestTable(); + + TestTable = GetTestTable(); ArrayOfTests = New Array; - - For Each Test In TestTable Do + + For Each Test In TestTable Do ArrayOfTests.Add(Test.Method); EndDo; - + Return ArrayOfTests; - + EndFunction -Function GetParameter(Parameter) Export +Function GetParameter(Parameter) Export - Path = DataFilePath(); + Path = DataFilePath(); Return GetValueFromFile(Parameter, Path); EndFunction Function GetBinary(Parameter) Export - - Path = DataFilePath(); + + Path = DataFilePath(); LocalParameter = Parameter + "Local"; - MainValue = GetValueFromFile(Parameter , Path); - LocalValue = GetValueFromFile(LocalParameter, Path); - + MainValue = GetValueFromFile(Parameter , Path); + LocalValue = GetValueFromFile(LocalParameter, Path); + LocalFile = New File(LocalValue); - + If LocalFile.Exists() Then Value = New BinaryData(LocalValue); Else Value = MainValue; EndIf; - + If TypeOf(Value) = Type("String") Then - Value = GetFilePath(Value, LocalParameter); + Value = GetFilePath(Value, LocalParameter); EndIf; - + Return Value; - + EndFunction Function GetFilePath(Val Path, LocalParameter, Val SaveLocally = True) Export - - If StrFind(Path, "http") > 0 + + If StrFind(Path, "http") > 0 Or StrFind(Path, "www") > 0 Then - - TFN = GetTempFileName(); + + TFN = GetTempFileName(); FileCopy(Path, TFN); - Path = TFN; + Path = TFN; Binary = New BinaryData(Path); - + If SaveLocally Then WriteParameter(LocalParameter, TFN); Else DeleteFiles(TFN); EndIf; - + Else - + Binary = New BinaryData(Path); - + EndIf; - + Return Binary; - + EndFunction Procedure ParameterToCollection(Parameter, Collection) Export Value = GetParameter(Parameter); Collection.Insert(Parameter, Value); - + EndProcedure Procedure BinaryToCollection(Parameter, Collection) Export Value = GetBinary(Parameter); Collection.Insert(Parameter, Value); - + EndProcedure Procedure WriteParameter(Parameter, Value) Export - - Path = DataFilePath(); + + Path = DataFilePath(); WriteParameterToFile(Parameter, Value, Path); - + EndProcedure Procedure WriteLog(Val Result, Val Method, Val Library = "") Export - + Header = String(OPI_Tools.GetCurrentDate()) + " | " + Method; - + Try Data = OPI_Tools.JSONString(Result); Except Data = "Not JSON: " + String(Result); EndTry; - - Data = " " + Data; - + + Data = " " + Data; + Message(Header); Message(Chars.LF); Message(Data); Message(Chars.LF); Message("---------------------------------"); Message(Chars.LF); - + If ValueIsFilled(Library) Then WriteLogFile(Data, Method, Library); EndIf; - + EndProcedure #EndRegion #Region Private -Function GetValueFromFile(Parameter, Path) - - Values = OPI_Tools.ReadJSONFile(Path); +Function GetValueFromFile(Parameter, Path) + + Values = OPI_Tools.ReadJSONFile(Path); Return ?(Values.Property(Parameter), Values[Parameter], ""); - + EndFunction Function DataFilePath() - - Path = ""; + + Path = ""; PossiblePaths = New Array; PossiblePaths.Add("./data.json"); PossiblePaths.Add("C:\GDrive\Мой Диск\data.json"); PossiblePaths.Add("D:\GD\Мой Диск\data.json"); - + For Each PossiblePath In PossiblePaths Do - + RepositoryFile = New File(PossiblePath); - + If RepositoryFile.Exists() Then Path = PossiblePath; - EndIf; - + EndIf; + EndDo; - + Return Path; - + EndFunction Function GetCommonModule(Val Name) - SetSafeMode(True); - Module = Eval(Name); - SetSafeMode(False); - Return Module; + SetSafeMode(True); + Module = Eval(Name); + SetSafeMode(False); + Return Module; EndFunction Procedure NewTest(ValueTable, Val Method, Val Synonym, Val Section) - - NewTest = ValueTable.Add(); - NewTest.Method = Method; + + NewTest = ValueTable.Add(); + NewTest.Method = Method; NewTest.Synonym = Synonym; NewTest.Section = Section; - + EndProcedure Procedure WriteParameterToFile(Val Parameter, Val Value, Val Path) - + Values = OPI_Tools.ReadJSONFile(Path); Values.Insert(Parameter, Value); - Record = New JSONWriter; + Record = New JSONWriter; JSONWriterSettings = New JSONWriterSettings(JSONLineBreak.Auto, Chars.Tab); Record.OpenFile(Path, , , JSONWriterSettings); WriteJSON(Record, Values); @@ -452,37 +452,37 @@ Procedure WriteParameterToFile(Val Parameter, Val Value, Val Path) EndProcedure Procedure WriteLogFile(Val Data, Val Method, Val Library) - + Try - - LogPath = "./docs/ru/results"; + + LogPath = "./docs/ru/results"; LibraryLogPath = LogPath + "/" + Library; - + LogDirectory = New File(LogPath); - + If Not LogDirectory.Exists() Then CreateDirectory(LogPath); EndIf; - + LibraryLogCatalog = New File(LibraryLogPath); - + If Not LibraryLogCatalog.Exists() Then CreateDirectory(LibraryLogPath); EndIf; - + FilePath = LibraryLogPath + "/" + Method + ".log"; - LogFile = New File(FilePath); - + LogFile = New File(FilePath); + If Not LogFile.Exists() Then LogDocument = New TextDocument; LogDocument.SetText(Data); LogDocument.Write(FilePath); EndIf; - + Except - Message("Failed to write log file!: " + ErrorDescription()); + Message("Failed to write log file!: " + ErrorDescription()); EndTry; - + EndProcedure #EndRegion diff --git a/src/en/OPI/src/CommonModules/OPI_Tests/Module.bsl b/src/en/OPI/src/CommonModules/OPI_Tests/Module.bsl index a8c85ecc1f..2f2eae0b27 100644 --- a/src/en/OPI/src/CommonModules/OPI_Tests/Module.bsl +++ b/src/en/OPI/src/CommonModules/OPI_Tests/Module.bsl @@ -67,56 +67,56 @@ EndFunction #Region Telegram Procedure TelegramAPI_GetBotInfo() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token", TestParameters); - + Telegram_GetBotInformation(TestParameters); - + EndProcedure Procedure TelegramAPI_GetUpdates() Export TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token", TestParameters); - + Telegram_DeleteWebhook(TestParameters); Telegram_GetUpdates(TestParameters); - + EndProcedure Procedure TelegramAPI_SetWebhook() Export TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_URL" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_URL" , TestParameters); Telegram_SetWebhook(TestParameters); Telegram_DeleteWebhook(TestParameters); - + EndProcedure Procedure TelegramAPI_SendTextMessage() Export TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); + Telegram_SendTextMessage(TestParameters); - + EndProcedure Procedure TelegramAPI_SendImage() Export TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); + Telegram_SendPicture(TestParameters); Telegram_DownloadFile(TestParameters); @@ -125,12 +125,12 @@ EndProcedure Procedure TelegramAPI_SendVideo() Export TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Video" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Video" , TestParameters); + Telegram_SendVideo(TestParameters); Telegram_DownloadFile(TestParameters); @@ -139,12 +139,12 @@ EndProcedure Procedure TelegramAPI_SendAudio() Export TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Audio" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Audio" , TestParameters); + Telegram_SendAudio(TestParameters); Telegram_DownloadFile(TestParameters); @@ -153,12 +153,12 @@ EndProcedure Procedure TelegramAPI_SendDocument() Export TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Document" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Document" , TestParameters); + Telegram_SendDocument(TestParameters); EndProcedure @@ -166,110 +166,110 @@ EndProcedure Procedure TelegramAPI_SendGIF() Export TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("GIF" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("GIF" , TestParameters); + Telegram_SendGif(TestParameters); EndProcedure Procedure TelegramAPI_SendMediaGroup() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Video" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Document" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Video" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Document" , TestParameters); + Telegram_SendMediaGroup(TestParameters); EndProcedure Procedure TelegramAPI_SendLocation() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Long" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Lat" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("Long" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Lat" , TestParameters); + Telegram_SendLocation(TestParameters); EndProcedure Procedure TelegramAPI_SendContact() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Name" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Surname" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Phone" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Name" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Surname" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Phone" , TestParameters); Telegram_SendContact(TestParameters); EndProcedure Procedure TelegramAPI_SendPoll() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID", TestParameters); - + Telegram_SendPoll(TestParameters); EndProcedure Procedure TelegramAPI_ForwardMessage() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelMessageID", TestParameters); Telegram_ForwardMessage(TestParameters); - + EndProcedure Procedure TelegramAPI_BanUnban() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChatID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID" , TestParameters); - + Telegram_Ban(TestParameters); Telegram_Unban(TestParameters); - + EndProcedure Procedure TelegramAPI_CreateInvitationLink() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID", TestParameters); - + Telegram_CreateInviteLink(TestParameters); EndProcedure Procedure TelegramAPI_PinUnpinMessage() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelMessageID", TestParameters); - + Telegram_PinMessage(TestParameters); Telegram_UnpinMessage(TestParameters); Telegram_DeleteMessage(TestParameters); @@ -277,32 +277,32 @@ Procedure TelegramAPI_PinUnpinMessage() Export EndProcedure Procedure TelegramAPI_GetMemberCount() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ChannelID", TestParameters); - + Telegram_GetParticipantCount(TestParameters); EndProcedure Procedure TelegramAPI_GetForumAvatarsList() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token", TestParameters); - + Telegram_GetForumAvatarList(TestParameters); - + EndProcedure Procedure TelegramAPI_CreateDeleteForumTopic() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ForumID", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("String" , TestParameters); + Telegram_CreateForumTopic(TestParameters); Telegram_EditForumTopic(TestParameters); Telegram_CloseForumTopic(TestParameters); @@ -313,9 +313,9 @@ Procedure TelegramAPI_CreateDeleteForumTopic() Export EndProcedure Procedure TelegramAPI_HideShowMainTopic() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ForumID", TestParameters); Telegram_HideMainForumTopic(TestParameters); @@ -324,13 +324,13 @@ Procedure TelegramAPI_HideShowMainTopic() Export EndProcedure Procedure TelegramAPI_ChangeMainTopicName() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Telegram_Token" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Telegram_ForumID", TestParameters); Telegram_ChangeMainTopicName(TestParameters); - + EndProcedure #EndRegion @@ -338,251 +338,251 @@ EndProcedure #Region VK Procedure VKAPI_CreateTokenLink() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("VK_AppID", TestParameters); - VK_CreateTokenRetrievalLink(TestParameters); - + VK_CreateTokenRetrievalLink(TestParameters); + EndProcedure Procedure VKAPI_CreateDeletePost() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Picture2", TestParameters); - + VK_CreatePost(TestParameters); VK_DeletePost(TestParameters); EndProcedure Procedure VKAPI_CreateCompositePost() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Video" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("Video" , TestParameters); + VK_CreateCompositePost(TestParameters); - + EndProcedure Procedure VKAPI_CreatePoll() Export - + VK_CreatePoll(); - + EndProcedure Procedure VKAPI_SaveDeleteImage() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); - + VK_CreateAlbum(TestParameters); VK_SavePictureToAlbum(TestParameters); VK_DeleteImage(TestParameters); VK_DeleteAlbum(TestParameters); - + EndProcedure Procedure VKAPI_CreateStory() Export - + TestParameters = New Map; OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); - + VK_CreateStory(TestParameters); - + EndProcedure Procedure VKAPI_DiscussionMethods() Export - + TestParameters = New Structure; - Parameters = GetVKParameters(); - + Parameters = GetVKParameters(); + VK_CreateDiscussion(TestParameters); VK_CloseDiscussion(TestParameters); VK_OpenDiscussion(TestParameters); - VK_PostToDiscussion(TestParameters); - + VK_PostToDiscussion(TestParameters); + OPI_VK.CloseDiscussion(TestParameters["VK_ConvID"], True, Parameters); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VKAPI_LikeRepostComment() Export - + TestParameters = New Structure(); - Parameters = GetVKParameters(); - Text = "Post from autotest"; - - Result = OPI_VK.CreatePost(Text, New Array, , , Parameters); - PostID = Result["response"]["post_id"]; - + Parameters = GetVKParameters(); + Text = "Post from autotest"; + + Result = OPI_VK.CreatePost(Text, New Array, , , Parameters); + PostID = Result["response"]["post_id"]; + OPI_TestDataRetrieval.WriteParameter("VK_PostID", PostID); OPI_TestDataRetrieval.ParameterToCollection("VK_PostID", TestParameters); - - VK_LikePost(TestParameters); - VK_MakeRepost(TestParameters); - VK_WriteComment(TestParameters); - - OPI_VK.DeletePost(PostID, Parameters); + + VK_LikePost(TestParameters); + VK_MakeRepost(TestParameters); + VK_WriteComment(TestParameters); + + OPI_VK.DeletePost(PostID , Parameters); OPI_VK.DeletePost(TestParameters["Repost"], Parameters); - + OPI_Tools.Pause(5); EndProcedure Procedure VKAPI_GetStatistics() Export - + TestParameters = New Structure(); - + VK_GetStatistics(TestParameters); - + OPI_Tools.Pause(5); EndProcedure Procedure VKAPI_GetPostStatistics() Export - + TestParameters = New Structure(); - + VK_GetPostStatistics(TestParameters); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VKAPI_CreateAdCampaign() Export - + Parameters = GetVKParameters(); - Text = "Post from autotest"; - - Result = OPI_VK.CreatePost(Text, New Array, , , Parameters); - PostID = Result["response"]["post_id"]; - + Text = "Post from autotest"; + + Result = OPI_VK.CreatePost(Text, New Array, , , Parameters); + PostID = Result["response"]["post_id"]; + OPI_TestDataRetrieval.WriteParameter("VK_PostID", PostID); - + TestParameters = New Structure(); OPI_TestDataRetrieval.ParameterToCollection("VK_AdsCabinetID", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("VK_PostID" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("VK_PostID" , TestParameters); + VK_CreateAdCampaign(TestParameters); VK_CreateAd(TestParameters); VK_PauseAdvertising(TestParameters); - + OPI_VK.DeletePost(PostID, Parameters); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VKAPI_SendMessage() Export - + TestParameters = New Structure; - - OPI_TestDataRetrieval.ParameterToCollection("VK_UserID", TestParameters); + + OPI_TestDataRetrieval.ParameterToCollection("VK_UserID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("VK_CommunityToken", TestParameters); VK_FormKeyboard(TestParameters); VK_WriteMessage(TestParameters); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VKAPI_GetProductCategories() Export - + TestParameters = New Structure; - + VK_GetProductCategoryList(TestParameters); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VKAPI_CreateProductSelection() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Picture", TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Picture2", TestParameters); - + CreateProductCollection(TestParameters); EditProductCollection(TestParameters); VK_AddProduct(TestParameters); VK_EditProduct(TestParameters); - VK_AddProductToCollection(TestParameters); + VK_AddProductToCollection(TestParameters); VK_RemoveProductFromCollection(TestParameters); VK_DeleteProduct(TestParameters); VK_DeleteCollection(TestParameters); OPI_Tools.Pause(5); - + EndProcedure Procedure VKAPI_CreateProductWithProperties() Export - + Parameters = GetVKParameters(); - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Picture", TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Picture2", TestParameters); - + VK_CreateProductProperty(TestParameters); - VK_EditProductProperty(TestParameters); - VK_AddProductPropertyVariant(TestParameters); - VK_EditProductPropertyVariant(TestParameters); + VK_EditProductProperty(TestParameters); + VK_AddProductPropertyVariant(TestParameters); + VK_EditProductPropertyVariant(TestParameters); VK_CreateProductWithProp(TestParameters); VK_GetProductsByID(TestParameters); VK_GroupProducts(TestParameters); - + OPI_VK.DeleteProduct(TestParameters["VK_MarketItemID2"], Parameters); OPI_VK.DeleteProduct(TestParameters["VK_MarketItemID3"], Parameters); - + VK_DeleteProductPropertyVariant(TestParameters); VK_DeleteProductProperty(TestParameters); - + EndProcedure Procedure VKAPI_GetProductList() Export - + TestParameters = New Structure; - + VK_GetProductList(TestParameters); - + EndProcedure Procedure VKAPI_GetSelectionList() Export - + TestParameters = New Structure; - + VK_GetSelectionList(TestParameters); - + EndProcedure Procedure VKAPI_GetPropertyList() Export - + TestParameters = New Structure; - + VK_GetPropertyList(TestParameters); EndProcedure Procedure VKAPI_GetOrderList() Export - + TestParameters = New Structure; - + VK_GetOrderList(TestParameters); - + EndProcedure Procedure VKAPI_UploadVideo() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Video", TestParameters); - + VK_UploadVideoToServer(TestParameters); - + EndProcedure #EndRegion @@ -590,135 +590,135 @@ EndProcedure #Region YandexDisk Procedure YDisk_GetDiskInfo() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("YandexDisk_Token", TestParameters); - + YandexDisk_GetDiskInfo(TestParameters); - + EndProcedure Procedure YDisk_CreateFolder() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("YandexDisk_Token", TestParameters); - + YandexDisk_CreateFolder(TestParameters); - + EndProcedure Procedure YDisk_UploadByUrlAndGetObject() Export - + Token = OPI_TestDataRetrieval.GetParameter("YandexDisk_Token"); - Path = "/" + String(New UUID) + ".png"; - URL = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/Media/logo.png"; + Path = "/" + String(New UUID) + ".png"; + URL = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/Media/logo.png"; OPI_YandexDisk.UploadFileByURL(Token, Path, URL); OPI_Tools.Pause(5); - + Result = OPI_YandexDisk.GetObject(Token, Path); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetObject"); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["type"]).Равно("file"); OPI_TestDataRetrieval.ExpectsThat(Result["path"]).Равно("disk:" + Path); OPI_YandexDisk.DeleteObject(Token, Path, False); - + OPI_Tools.Pause(5); - + EndProcedure Procedure YDisk_UploadDeleteFile() Export - + Token = OPI_TestDataRetrieval.GetParameter("YandexDisk_Token"); - Path = "/" + String(New UUID) + ".png"; + Path = "/" + String(New UUID) + ".png"; Image = OPI_TestDataRetrieval.GetBinary("Picture"); - TFN = GetTempFileName("png"); + TFN = GetTempFileName("png"); Image.Write(TFN); Result = OPI_YandexDisk.UploadFile(Token, Path, Image, True); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UploadFile"); - + Check_Empty(Result); OPI_Tools.Pause(5); - + Result = OPI_YandexDisk.DeleteObject(Token, Path, False); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteObject"); - + Check_Empty(Result); - + Result = OPI_YandexDisk.UploadFile(Token, Path, TFN, True); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UploadFile"); - + Check_Empty(Result); OPI_Tools.Pause(5); - - Result = OPI_YandexDisk.DeleteObject(Token, Path, False); - + + Result = OPI_YandexDisk.DeleteObject(Token, Path, False); + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteObject"); - - Check_Empty(Result); + + Check_Empty(Result); DeleteFiles(TFN); - + OPI_Tools.Pause(5); - + EndProcedure Procedure YDisk_CreateObjectCopy() Export - - Token = OPI_TestDataRetrieval.GetParameter("YandexDisk_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("YandexDisk_Token"); OriginalPath = "/" + String(New UUID) + ".png"; - CopyPath = "/" + String(New UUID) + ".png"; - URL = "https://raw.githubusercontent.com/Bayselonarrend/" + CopyPath = "/" + String(New UUID) + ".png"; + URL = "https://raw.githubusercontent.com/Bayselonarrend/" + "OpenIntegrations/main/Media/logo.png"; OPI_YandexDisk.UploadFileByURL(Token, OriginalPath, URL); OPI_Tools.Pause(25); - + Result = OPI_YandexDisk.CreateObjectCopy(Token, OriginalPath, CopyPath, True); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateObjectCopy"); - + OPI_Tools.Pause(5); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["type"]).Равно("file"); OPI_TestDataRetrieval.ExpectsThat(Result["path"]).Равно("disk:" + CopyPath); OPI_YandexDisk.DeleteObject(Token, OriginalPath, False); - OPI_YandexDisk.DeleteObject(Token, CopyPath, False); - + OPI_YandexDisk.DeleteObject(Token, CopyPath , False); + OPI_Tools.Pause(5); - + EndProcedure Procedure YDisk_GetDownloadLink() Export - + Token = OPI_TestDataRetrieval.GetParameter("YandexDisk_Token"); - Path = "/" + String(New UUID) + ".png"; - URL = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/Media/logo.png"; + Path = "/" + String(New UUID) + ".png"; + URL = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/Media/logo.png"; OPI_YandexDisk.UploadFileByURL(Token, Path, URL); OPI_Tools.Pause(5); - + Result = OPI_YandexDisk.GetDownloadLink(Token, Path); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetDownloadLink"); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["method"]).Равно("GET"); OPI_TestDataRetrieval.ExpectsThat(Result["href"]).ИмеетТип("String").Заполнено(); - + URL = Result["href"]; - + Result = OPI_YandexDisk.DownloadFile(Token, Path); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("BinaryData").Заполнено(); OPI_YandexDisk.DeleteObject(Token, Path, False); @@ -726,131 +726,131 @@ Procedure YDisk_GetDownloadLink() Export EndProcedure Procedure YDisk_GetFileList() Export - - Token = OPI_TestDataRetrieval.GetParameter("YandexDisk_Token"); - Count = 2; + + Token = OPI_TestDataRetrieval.GetParameter("YandexDisk_Token"); + Count = 2; Indent = 1; - + Result = OPI_YandexDisk.GetFilesList(Token, Count, Indent, "image"); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetFileList"); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["limit"]).Равно(Count); OPI_TestDataRetrieval.ExpectsThat(Result["offset"]).Равно(Indent); OPI_TestDataRetrieval.ExpectsThat(Result["items"]).ИмеетТип("Array"); - + OPI_Tools.Pause(5); - + EndProcedure Procedure YDisk_MoveObject() Export - - Token = OPI_TestDataRetrieval.GetParameter("YandexDisk_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("YandexDisk_Token"); OriginalPath = "/" + String(New UUID) + ".png"; - CopyPath = "/" + String(New UUID) + ".png"; - URL = "https://raw.githubusercontent.com/Bayselonarrend/" + CopyPath = "/" + String(New UUID) + ".png"; + URL = "https://raw.githubusercontent.com/Bayselonarrend/" + "OpenIntegrations/main/Media/logo.png"; Result = OPI_YandexDisk.UploadFileByURL(Token, OriginalPath, URL); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UploadFileByURL"); - + OPI_Tools.Pause(15); - + Result = OPI_YandexDisk.MoveObject(Token, OriginalPath, CopyPath, True); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "MoveObject"); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["type"]).Равно("file"); OPI_TestDataRetrieval.ExpectsThat(Result["path"]).Равно("disk:" + CopyPath); OPI_YandexDisk.DeleteObject(Token, OriginalPath, False); - OPI_YandexDisk.DeleteObject(Token, CopyPath, False); - + OPI_YandexDisk.DeleteObject(Token, CopyPath , False); + OPI_Tools.Pause(5); - + EndProcedure Procedure YDisk_PublicObjectActions() Export - - PUrl = "public_url"; - Map = "Map"; + + PUrl = "public_url"; + Map = "Map"; Token = OPI_TestDataRetrieval.GetParameter("YandexDisk_Token"); - Path = "/" + String(New UUID) + ".png"; - URL = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/Media/logo.png"; - + Path = "/" + String(New UUID) + ".png"; + URL = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/Media/logo.png"; + OPI_YandexDisk.UploadFileByURL(Token, Path, URL); OPI_Tools.Pause(5); - + ResultArray = New Array; - - ResultArray.Add(OPI_YandexDisk.PublishObject(Token, Path)); + + ResultArray.Add(OPI_YandexDisk.PublishObject(Token, Path)); PublicURL = ResultArray[0][PUrl]; - + Result = OPI_YandexDisk.GetDownloadLinkForPublicObject(Token, PublicURL); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetPublicObjectDownloadLink"); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип(Map).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["method"]).Равно("GET"); OPI_TestDataRetrieval.ExpectsThat(Result["href"]).ИмеетТип("String").Заполнено(); - + Result = OPI_YandexDisk.GetPublicObject(Token, PublicURL); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetPublicObject"); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип(Map).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["type"]).Равно("file"); OPI_TestDataRetrieval.ExpectsThat(Result["path"]).Равно("/"); - + ResultArray.Add(OPI_YandexDisk.SavePublicObjectToDisk(Token, PublicURL)); - + ResultArray.Add(OPI_YandexDisk.CancelObjectPublication(Token, Path)); - + Counter = 0; For Each Result In ResultArray Do - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ChangePublication"); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип(Map).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["type"]).Равно("file"); OPI_TestDataRetrieval.ExpectsThat(Result["path"]).Заполнено(); - - If Counter = 0 Then + + If Counter = 0 Then OPI_TestDataRetrieval.ExpectsThat(Result[PUrl]).ИмеетТип("String").Заполнено(); Else OPI_TestDataRetrieval.ExpectsThat(Result[PUrl]).ИмеетТип("Undefined"); EndIf; - + Counter = Counter + 1; - + EndDo; - + OPI_YandexDisk.DeleteObject(Token, Path, False); - + OPI_Tools.Pause(5); EndProcedure Procedure YDisk_GetPublishedList() Export - - Token = OPI_TestDataRetrieval.GetParameter("YandexDisk_Token"); - Count = 2; + + Token = OPI_TestDataRetrieval.GetParameter("YandexDisk_Token"); + Count = 2; Indent = 1; - + Result = OPI_YandexDisk.GetPublishedObjectsList(Token, Count, Indent); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetPublishedObjectList"); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["limit"]).Равно(Count); OPI_TestDataRetrieval.ExpectsThat(Result["offset"]).Равно(Indent); OPI_TestDataRetrieval.ExpectsThat(Result["items"]).ИмеетТип("Array"); - + OPI_Tools.Pause(5); - + EndProcedure #EndRegion @@ -858,12 +858,12 @@ EndProcedure #Region Viber Procedure Viber_GetChannelInfo() Export - - Token = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); + + Token = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); Result = OPI_Viber.GetChannelInformation(Token); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetChannelInfo"); - + Check_ViberOk(Result); OPI_Tools.Pause(5); @@ -871,13 +871,13 @@ Procedure Viber_GetChannelInfo() Export EndProcedure Procedure Viber_GetUserData() Export - - Token = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); - User = OPI_TestDataRetrieval.GetParameter("Viber_ChannelAdminID"); + + Token = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); + User = OPI_TestDataRetrieval.GetParameter("Viber_ChannelAdminID"); Result = OPI_Viber.GetUserData(Token, User); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetUserData"); - + OPI_TestDataRetrieval.ExpectsThat(Result["chat_hostname"]).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["status_message"]).Заполнено(); OPI_Tools.Pause(5); @@ -885,184 +885,184 @@ Procedure Viber_GetUserData() Export EndProcedure Procedure Viber_GetOnlineUsers() Export - - Token = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); - User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); + + Token = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); + User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); Result = OPI_Viber.GetOnlineUsers(Token, User); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetOnlineUsers"); - + OPI_TestDataRetrieval.ExpectsThat(Result["users"]).ИмеетТип("Array"); Check_ViberOk(Result); - + OPI_Tools.Pause(5); EndProcedure Procedure Viber_SendTextMessage() Export - - Text = "TestMessage"; - ChannelToken = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); - BotToken = OPI_TestDataRetrieval.GetParameter("Viber_Token"); - User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); + + Text = "TestMessage"; + ChannelToken = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); + BotToken = OPI_TestDataRetrieval.GetParameter("Viber_Token"); + User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); Administrator = OPI_TestDataRetrieval.GetParameter("Viber_ChannelAdminID"); - + ButtonArray = New Array; ButtonArray.Add("Button 1"); ButtonArray.Add("Button 2"); ButtonArray.Add("Button 3"); - + Keyboard = OPI_Viber.CreateKeyboardFromArrayButton(ButtonArray); - + Result = OPI_Viber.SendTextMessage(BotToken, Text, User, False, Keyboard); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendTextMessage"); - + OPI_TestDataRetrieval.ExpectsThat(Result["message_token"]).Заполнено(); Check_ViberOk(Result); - + Result = OPI_Viber.SendTextMessage(ChannelToken, Text, Administrator, True, Keyboard); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendTextMessage"); - + OPI_TestDataRetrieval.ExpectsThat(Result["message_token"]).Заполнено(); Check_ViberOk(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Viber_SendImage() Export - Text = "TestMessage"; - Image = OPI_TestDataRetrieval.GetParameter("Picture"); - ChannelToken = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); - BotToken = OPI_TestDataRetrieval.GetParameter("Viber_Token"); - User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); + Text = "TestMessage"; + Image = OPI_TestDataRetrieval.GetParameter("Picture"); + ChannelToken = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); + BotToken = OPI_TestDataRetrieval.GetParameter("Viber_Token"); + User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); Administrator = OPI_TestDataRetrieval.GetParameter("Viber_ChannelAdminID"); - + Result = OPI_Viber.SendImage(BotToken, Image, User, False, Text); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendPicture"); - + OPI_TestDataRetrieval.ExpectsThat(Result["message_token"]).Заполнено(); Check_ViberOk(Result); - + Result = OPI_Viber.SendImage(ChannelToken, Image, Administrator, True, Text); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendPicture"); - + OPI_TestDataRetrieval.ExpectsThat(Result["message_token"]).Заполнено(); Check_ViberOk(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Viber_SendFile() Export - - Document = OPI_TestDataRetrieval.GetParameter("Document"); - ChannelToken = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); - BotToken = OPI_TestDataRetrieval.GetParameter("Viber_Token"); - User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); + + Document = OPI_TestDataRetrieval.GetParameter("Document"); + ChannelToken = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); + BotToken = OPI_TestDataRetrieval.GetParameter("Viber_Token"); + User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); Administrator = OPI_TestDataRetrieval.GetParameter("Viber_ChannelAdminID"); - + Result = OPI_Viber.SendFile(BotToken, Document, User, False, "docx"); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendFile"); - + OPI_TestDataRetrieval.ExpectsThat(Result["message_token"]).Заполнено(); Check_ViberOk(Result); - + Result = OPI_Viber.SendFile(ChannelToken, Document, Administrator, True, "docx"); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendFile"); - + OPI_TestDataRetrieval.ExpectsThat(Result["message_token"]).Заполнено(); Check_ViberOk(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Viber_SendContact() Export - - Name = "Petr Petrov"; - Phone = "+123456789"; - ChannelToken = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); - BotToken = OPI_TestDataRetrieval.GetParameter("Viber_Token"); - User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); + + Name = "Petr Petrov"; + Phone = "+123456789"; + ChannelToken = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); + BotToken = OPI_TestDataRetrieval.GetParameter("Viber_Token"); + User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); Administrator = OPI_TestDataRetrieval.GetParameter("Viber_ChannelAdminID"); - + Result = OPI_Viber.SendContact(BotToken, Name, Phone, User, False); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendContact"); - + OPI_TestDataRetrieval.ExpectsThat(Result["message_token"]).Заполнено(); Check_ViberOk(Result); - + Result = OPI_Viber.SendContact(ChannelToken, Name, Phone, Administrator, True); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendContact"); - + OPI_TestDataRetrieval.ExpectsThat(Result["message_token"]).Заполнено(); Check_ViberOk(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Viber_SendLocation() Export - Latitude = "48.87373649724122"; - Longitude = "2.2954639195323967"; - ChannelToken = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); - BotToken = OPI_TestDataRetrieval.GetParameter("Viber_Token"); - User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); + Latitude = "48.87373649724122"; + Longitude = "2.2954639195323967"; + ChannelToken = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); + BotToken = OPI_TestDataRetrieval.GetParameter("Viber_Token"); + User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); Administrator = OPI_TestDataRetrieval.GetParameter("Viber_ChannelAdminID"); - + Result = OPI_Viber.SendLocation(BotToken, Latitude, Longitude, User, False); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendLocation"); - + OPI_TestDataRetrieval.ExpectsThat(Result["message_token"]).Заполнено(); Check_ViberOk(Result); - + Result = OPI_Viber.SendLocation(ChannelToken, Latitude, Longitude, Administrator, True); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendLocation"); - + OPI_TestDataRetrieval.ExpectsThat(Result["message_token"]).Заполнено(); Check_ViberOk(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Viber_SendLink() Export - URL = "https://github.com/Bayselonarrend/OpenIntegrations"; - ChannelToken = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); - BotToken = OPI_TestDataRetrieval.GetParameter("Viber_Token"); - User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); + URL = "https://github.com/Bayselonarrend/OpenIntegrations"; + ChannelToken = OPI_TestDataRetrieval.GetParameter("Viber_ChannelToken"); + BotToken = OPI_TestDataRetrieval.GetParameter("Viber_Token"); + User = OPI_TestDataRetrieval.GetParameter("Viber_UserID"); Administrator = OPI_TestDataRetrieval.GetParameter("Viber_ChannelAdminID"); - + Result = OPI_Viber.SendLink(BotToken, URL, User, False); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendLink"); - + OPI_TestDataRetrieval.ExpectsThat(Result["message_token"]).Заполнено(); Check_ViberOk(Result); - + Result = OPI_Viber.SendLink(ChannelToken, URL, Administrator, True); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendLink"); - + OPI_TestDataRetrieval.ExpectsThat(Result["message_token"]).Заполнено(); Check_ViberOk(Result); - + OPI_Tools.Pause(5); - + EndProcedure #EndRegion @@ -1070,53 +1070,53 @@ EndProcedure #Region GoogleWorkspace Procedure GV_GetAuthorizationLink() Export - - ClientID = OPI_TestDataRetrieval.GetParameter("Google_ClientID"); - Result = OPI_GoogleWorkspace.FormCodeRetrievalLink(ClientID); - + + ClientID = OPI_TestDataRetrieval.GetParameter("Google_ClientID"); + Result = OPI_GoogleWorkspace.FormCodeRetrievalLink(ClientID); + OPI_TestDataRetrieval.ExpectsThat(Result) - .ИмеетТип("String") + .ИмеетТип("String") .Заполнено(); - + OPI_TestDataRetrieval.WriteParameter("Google_Link", Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure GV_GetToken() Export - - ClientID = OPI_TestDataRetrieval.GetParameter("Google_ClientID"); + + ClientID = OPI_TestDataRetrieval.GetParameter("Google_ClientID"); ClientSecret = OPI_TestDataRetrieval.GetParameter("Google_ClientSecret"); - Code = OPI_TestDataRetrieval.GetParameter("Google_Code"); - + Code = OPI_TestDataRetrieval.GetParameter("Google_Code"); + Result = OPI_GoogleWorkspace.GetTokenByCode(ClientID, ClientSecret, Code); - + If ValueIsFilled(Result["access_token"]) And ValueIsFilled(Result["refresh_token"]) Then - - OPI_TestDataRetrieval.WriteParameter("Google_Token" , Result["access_token"]); + + OPI_TestDataRetrieval.WriteParameter("Google_Token" , Result["access_token"]); OPI_TestDataRetrieval.WriteParameter("Google_Refresh", Result["refresh_token"]); - + EndIf; - + OPI_Tools.Pause(5); - + EndProcedure Procedure GV_UpdateToken() Export - - ClientID = OPI_TestDataRetrieval.GetParameter("Google_ClientID"); + + ClientID = OPI_TestDataRetrieval.GetParameter("Google_ClientID"); ClientSecret = OPI_TestDataRetrieval.GetParameter("Google_ClientSecret"); RefreshToken = OPI_TestDataRetrieval.GetParameter("Google_Refresh"); - + Result = OPI_GoogleWorkspace.RefreshToken(ClientID, ClientSecret, RefreshToken); - - OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map"); + + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["access_token"]).Заполнено(); - + OPI_TestDataRetrieval.WriteParameter("Google_Token", Result["access_token"]); - + OPI_Tools.Pause(5); EndProcedure @@ -1126,181 +1126,181 @@ EndProcedure #Region GoogleCalendar Procedure GC_GetCalendarList() Export - - Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); Result = OPI_GoogleCalendar.GetCalendarList(Token); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetCalendarList"); - + OPI_TestDataRetrieval.ExpectsThat(Result) .ИмеетТип("Array"); OPI_Tools.Pause(5); - + EndProcedure Procedure GC_CreateDeleteCalendar() Export - - Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); - Name = "TestCalendar"; + + Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); + Name = "TestCalendar"; Description = "TestDescription"; - EditedName = Name + " (change.)"; - TypeMap = Type("Map"); - TypeString = Type("String"); - Summary = "summary"; - Black = "#000000"; - Yellow = "#ffd800"; - - Result = OPI_GoogleCalendar.CreateCalendar(Token, Name); - + EditedName = Name + " (change.)"; + TypeMap = Type("Map"); + TypeString = Type("String"); + Summary = "summary"; + Black = "#000000"; + Yellow = "#ffd800"; + + Result = OPI_GoogleCalendar.CreateCalendar(Token, Name); + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateCalendar"); - - OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип(TypeMap); + + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип(TypeMap); OPI_TestDataRetrieval.ExpectsThat(Result[Summary]).Равно(Name); OPI_TestDataRetrieval.ExpectsThat(Result["id"]).ИмеетТип(TypeString).Заполнено(); - + Calendar = Result["id"]; - + Result = OPI_GoogleCalendar.EditCalendarMetadata(Token , Calendar , EditedName , Description); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "EditCalendarMetadata"); - + Check_GKObject(Result, EditedName, Description); - + Result = OPI_GoogleCalendar.GetCalendarMetadata(Token, Calendar); - - // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetCalendarMetadata"); - + + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetCalendarMetadata"); + Check_GKObject(Result, EditedName, Description); Result = OPI_GoogleCalendar.AddCalendarToList(Token, Calendar); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "AddCalendarToList"); - + Check_GKObject(Result, EditedName, Description); - + Result = OPI_GoogleCalendar.EditListCalendar(Token, Calendar, Black, Yellow, False); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "EditListCalendar"); - - OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип(TypeMap); + + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип(TypeMap); OPI_TestDataRetrieval.ExpectsThat(Result[Summary]).Равно(EditedName); OPI_TestDataRetrieval.ExpectsThat(Result["foregroundColor"]).Равно(Black); OPI_TestDataRetrieval.ExpectsThat(Result["backgroundColor"]).Равно(Yellow); - + Result = OPI_GoogleCalendar.GetListCalendar(Token, Calendar); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetListCalendar"); - - OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип(TypeMap); + + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип(TypeMap); OPI_TestDataRetrieval.ExpectsThat(Result[Summary]).Равно(EditedName); OPI_TestDataRetrieval.ExpectsThat(Result["foregroundColor"]).Равно(Black); OPI_TestDataRetrieval.ExpectsThat(Result["backgroundColor"]).Равно(Yellow); Result = OPI_GoogleCalendar.ClearMainCalendar(Token); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ClearPrimaryCalendar"); - + Check_Empty(Result); - + Result = OPI_GoogleCalendar.DeleteCalendarFromList(Token, Calendar); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteCalendarInСпandwithtoа"); - + Check_Empty(Result); - + Result = OPI_GoogleCalendar.DeleteCalendar(Token, Calendar); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteCalendar"); - + Check_Empty(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure GC_CreateDeleteEvent() Export - - CurrentDate = OPI_Tools.GetCurrentDate(); - Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); - Calendar = OPI_TestDataRetrieval.GetParameter("Google_CalendarID"); + + CurrentDate = OPI_Tools.GetCurrentDate(); + Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); + Calendar = OPI_TestDataRetrieval.GetParameter("Google_CalendarID"); Name = "New event"; - Description = "TestEventDescription"; + Description = "TestEventDescription"; EditedDescription = "Test event description (change.)"; UID = "id"; Hour = 3600; Attachments = New Map; - + Attachments.Insert("Image1" , "https://opi.neocities.org/assets/images/logo_long-e8fdcca6ff8b32e679ea49a1ccdd3eac.png"); Attachments.Insert("Image2" , "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/Media/logo.png?v1"); - + EventMap = New Map; - EventMap.Insert("Description" , Description); - EventMap.Insert("Title" , Name); - EventMap.Insert("Venue" , "InOffice"); - EventMap.Insert("StartDate" , CurrentDate); - EventMap.Insert("EndDate" , EventMap["StartDate"] + Hour); + EventMap.Insert("Description" , Description); + EventMap.Insert("Title" , Name); + EventMap.Insert("Venue" , "InOffice"); + EventMap.Insert("StartDate" , CurrentDate); + EventMap.Insert("EndDate" , EventMap["StartDate"] + Hour); EventMap.Insert("ArrayOfAttachmentURLs" , Attachments); - EventMap.Insert("SendNotifications" , True); - + EventMap.Insert("SendNotifications" , True); + Result = OPI_GoogleCalendar.CreateEvent(Token, Calendar, EventMap); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateEvent"); - + Event = Result[UID]; - + Check_GKObject(Result, Name, Description); - - EventMap = New Map; + + EventMap = New Map; EventMap.Insert("Description", EditedDescription); - + Result = OPI_GoogleCalendar.EditEvent(Token, Calendar, EventMap, Event); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "EditEvent"); - + Check_GKObject(Result, Name, EditedDescription); - + Result = OPI_GoogleCalendar.GetEvent(Token, Calendar, Event); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetEvent"); - + Check_GKObject(Result, Name, EditedDescription); Result = OPI_GoogleCalendar.MoveEvent(Token, Calendar, Calendar, Event); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "MoveEvent"); - + Check_GKObject(Result, Name, EditedDescription); - - Result = OPI_GoogleCalendar.DeleteEvent(Token, Calendar, Event); - + + Result = OPI_GoogleCalendar.DeleteEvent(Token, Calendar, Event); + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteEvent"); - + Check_Empty(Result); - + OPI_Tools.Pause(5); EndProcedure Procedure GC_GetEventList() Export - - Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); Calendar = OPI_TestDataRetrieval.GetParameter("Google_CalendarID"); Result = OPI_GoogleCalendar.GetEventList(Token, Calendar); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetEventList"); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Array"); - + OPI_Tools.Pause(5); - + EndProcedure #EndRegion @@ -1308,197 +1308,197 @@ EndProcedure #Region GoogleDrive Procedure GD_GetCatalogList() Export - + MimeType_ = "mimeType"; - Name_ = "name"; - Name = "TestFolder"; - Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); - Result = OPI_GoogleDrive.GetDirectoriesList(Token, Name, True); - + Name_ = "name"; + Name = "TestFolder"; + Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); + Result = OPI_GoogleDrive.GetDirectoriesList(Token, Name, True); + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetCatalogList"); - + Result = Result[0]; - + OPI_TestDataRetrieval.ExpectsThat(Result["files"]).ИмеетТип("Array"); OPI_TestDataRetrieval.ExpectsThat(Result[MimeType_]).Равно("application/vnd.google-apps.folder"); OPI_TestDataRetrieval.ExpectsThat(Result[Name_]).Заполнено(); - + OPI_Tools.Pause(5); Identifier = Result["id"]; - + OPI_TestDataRetrieval.WriteParameter("GD_Catalog", Identifier); - + Result = OPI_GoogleDrive.GetObjectInformation(Token, Identifier); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetObjectInfo"); - + OPI_TestDataRetrieval.ExpectsThat(Result[MimeType_]).Равно("application/vnd.google-apps.folder"); OPI_TestDataRetrieval.ExpectsThat(Result[Name_]).Заполнено(); - + OPI_Tools.Pause(5); EndProcedure Procedure GD_UploadDeleteFile() Export - + ExtraBytes = 2; - - Kind_ = "kind"; - Content_ = "content"; - MIME_ = "MIME"; + + Kind_ = "kind"; + Content_ = "content"; + MIME_ = "MIME"; MimeType_ = "mimeType"; - Name_ = "name"; - Id_ = "id"; - + Name_ = "name"; + Id_ = "id"; + ArrayOfDeletions = New Array; - Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); - Image = OPI_TestDataRetrieval.GetBinary("Picture"); + Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); + Image = OPI_TestDataRetrieval.GetBinary("Picture"); ReplacementImage = OPI_TestDataRetrieval.GetBinary("Picture2"); - Directory = OPI_TestDataRetrieval.GetParameter("GD_Catalog"); - + Directory = OPI_TestDataRetrieval.GetParameter("GD_Catalog"); + Description = OPI_GoogleDrive.GetFileDescription(); Description.Insert("Parent", Directory); - + Result = OPI_GoogleDrive.UploadFile(Token, Image, Description); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UploadFile"); - + OPI_TestDataRetrieval.ExpectsThat(Result[MimeType_]).Равно(Description[MIME_]); OPI_TestDataRetrieval.ExpectsThat(Result[Name_]).Равно(Description["Name"]); Identifier = Result[Id_]; ArrayOfDeletions.Add(Identifier); - + NewName = "CopiedFile.jpeg"; - Result = OPI_GoogleDrive.CopyObject(Token, Identifier, NewName, "root"); - + Result = OPI_GoogleDrive.CopyObject(Token, Identifier, NewName, "root"); + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CopyObject"); - + OPI_Tools.Pause(5); - + OPI_TestDataRetrieval.ExpectsThat(Result[MimeType_]).Равно(Description[MIME_]); OPI_TestDataRetrieval.ExpectsThat(Result[Name_]).Равно(NewName); - + ArrayOfDeletions.Add(Result[Id_]); - + Result = OPI_GoogleDrive.DownloadFile(Token, Identifier); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DownloadFile"); - + OPI_TestDataRetrieval.ExpectsThat(Result.Size()).Равно(Image.Size() + ExtraBytes); OPI_Tools.Pause(5); - + NewName = "UpdatedFile.jpg"; - Result = OPI_GoogleDrive.UpdateFile(Token, Identifier, ReplacementImage, NewName); - + Result = OPI_GoogleDrive.UpdateFile(Token, Identifier, ReplacementImage, NewName); + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UpdateFile"); - + OPI_TestDataRetrieval.ExpectsThat(Result[MimeType_]).Равно(Description[MIME_]); OPI_TestDataRetrieval.ExpectsThat(Result[Name_]).Равно(NewName); OPI_Tools.Pause(5); - + Comment = "Yo"; - Result = OPI_GoogleDrive.CreateComment(Token, Identifier, Comment); - + Result = OPI_GoogleDrive.CreateComment(Token, Identifier, Comment); + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateComment"); - + OPI_TestDataRetrieval.ExpectsThat(Result[Content_]).Равно(Comment); OPI_TestDataRetrieval.ExpectsThat(Result[Kind_]).Равно("drive#comment"); - + OPI_Tools.Pause(5); - + For Each Deletable In ArrayOfDeletions Do - Result = OPI_GoogleDrive.DeleteObject(Token, Deletable); - + Result = OPI_GoogleDrive.DeleteObject(Token, Deletable); + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteObject"); - + OPI_TestDataRetrieval.ExpectsThat(ValueIsFilled(Result)).Равно(False); OPI_Tools.Pause(2); EndDo; - + OPI_Tools.Pause(5); - + EndProcedure Procedure GD_CreateDeleteComment() Export - - Kind_ = "kind"; - Content_ = "content"; - Id_ = "id"; + + Kind_ = "kind"; + Content_ = "content"; + Id_ = "id"; Comments_ = "comments"; - Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); + Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); Directory = OPI_TestDataRetrieval.GetParameter("GD_Catalog"); - Image = OPI_TestDataRetrieval.GetBinary("Picture"); - + Image = OPI_TestDataRetrieval.GetBinary("Picture"); + Description = OPI_GoogleDrive.GetFileDescription(); Description.Insert("Parent", Directory); - - Result = OPI_GoogleDrive.UploadFile(Token, Image, Description); + + Result = OPI_GoogleDrive.UploadFile(Token, Image, Description); Identifier = Result[Id_]; - - Comment = "NewComment"; + + Comment = "NewComment"; ResultArray = New Array; - Result = OPI_GoogleDrive.CreateComment(Token, Identifier, Comment); - + Result = OPI_GoogleDrive.CreateComment(Token, Identifier, Comment); + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateComment"); - + CommentID = Result[Id_]; - + ResultArray.Add(Result); - + Result = OPI_GoogleDrive.GetComment(Token, Identifier, CommentID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetComment"); - + ResultArray.Add(Result); - + Result = OPI_GoogleDrive.GetCommentList(Token, Identifier); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetCommentList"); - - Comments = Result[Comments_]; + + Comments = Result[Comments_]; CommentObject = Comments[Comments.UBound()]; - + ResultArray.Add(CommentObject); - - For Each Result In ResultArray Do + + For Each Result In ResultArray Do OPI_TestDataRetrieval.ExpectsThat(Result[Content_]).Равно(Comment); OPI_TestDataRetrieval.ExpectsThat(Result[Kind_]).Равно("drive#comment"); EndDo; - - Result = OPI_GoogleDrive.DeleteComment(Token, Identifier, CommentID); - + + Result = OPI_GoogleDrive.DeleteComment(Token, Identifier, CommentID); + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteComment"); - + OPI_TestDataRetrieval.ExpectsThat(ValueIsFilled(Result)).Равно(False); OPI_GoogleDrive.DeleteObject(Token, Identifier); - + EndProcedure Procedure GD_CreateCatalog() Export - - Name_ = "name"; - Name = "TestFolder"; - Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); + + Name_ = "name"; + Name = "TestFolder"; + Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); Directory = OPI_TestDataRetrieval.GetParameter("GD_Catalog"); - + ResultArray = New Array; - + ResultArray.Add(OPI_GoogleDrive.CreateFolder(Token, Name)); ResultArray.Add(OPI_GoogleDrive.CreateFolder(Token, Name, Directory)); - + For Each Result In ResultArray Do - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateFolder"); - + CatalogID = Result["id"]; - + OPI_TestDataRetrieval.ExpectsThat(Result[Name_]).Равно(Name); - + OPI_GoogleDrive.DeleteObject(Token, CatalogID); - + EndDo; EndProcedure @@ -1508,93 +1508,93 @@ EndProcedure #Region GoogleSheets Procedure GT_CreateTable() Export - + Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); - Name = "TestTable"; - + Name = "TestTable"; + SheetArray = New Array; SheetArray.Add("Sheet1"); SheetArray.Add("Sheet2"); - + Result = OPI_GoogleSheets.CreateSpreadsheet(Token, Name, SheetArray); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateSpreadsheet"); - + OPI_TestDataRetrieval.ExpectsThat(Result["properties"]["title"]).Равно(Name); For N = 0 To SheetArray.UBound() Do - + SheetName = Result["sheets"][N]["properties"]["title"]; OPI_TestDataRetrieval.ExpectsThat(SheetName).Равно(SheetArray[N]); - Sheet = Result["sheets"][N]["properties"]["sheetId"]; - Sheet = OPI_Tools.NumberToString(Sheet); - + Sheet = Result["sheets"][N]["properties"]["sheetId"]; + Sheet = OPI_Tools.NumberToString(Sheet); + EndDo; - + Spreadsheet = Result["spreadsheetId"]; - + OPI_TestDataRetrieval.WriteParameter("GS_Spreadsheet", Spreadsheet); - OPI_TestDataRetrieval.WriteParameter("GS_Sheet" , Sheet); - - Name = "Test table (new.)"; + OPI_TestDataRetrieval.WriteParameter("GS_Sheet" , Sheet); + + Name = "Test table (new.)"; Result = OPI_GoogleSheets.CreateSpreadsheet(Token, Name, SheetArray); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CopySheet (new.)"); - + Spreadsheet2 = Result["spreadsheetId"]; - + Result = OPI_GoogleSheets.CopySheet(Token, Spreadsheet, Spreadsheet2, Sheet); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CopySheet"); OPI_TestDataRetrieval.ExpectsThat(Result["title"]).Заполнено(); - + Name = "TestSheet"; - + Result = OPI_GoogleSheets.AddSheet(Token, Spreadsheet, Name); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "AddSheet"); NewSheet = Result["replies"][0]["addSheet"]["properties"]["sheetId"]; NewSheet = OPI_Tools.NumberToString(NewSheet); - - OPI_TestDataRetrieval.ExpectsThat(Result["spreadsheetId"]).Равно(Spreadsheet); + + OPI_TestDataRetrieval.ExpectsThat(Result["spreadsheetId"]).Равно(Spreadsheet); Result = OPI_GoogleSheets.DeleteSheet(Token, Spreadsheet, NewSheet); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteSheet"); - + OPI_TestDataRetrieval.ExpectsThat(Result["spreadsheetId"]).Равно(Spreadsheet); - + Name = "Test table (changed.)"; - + Result = OPI_GoogleSheets.EditSpreadsheetTitle(Token, Spreadsheet, Name); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "EditSpreadsheetTitle"); - + OPI_TestDataRetrieval.ExpectsThat(Result["spreadsheetId"]).Равно(Spreadsheet); - + EndProcedure Procedure GT_GetTable() Export - - Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); Spreadsheet = OPI_TestDataRetrieval.GetParameter("GS_Spreadsheet"); - Name = "Test table (changed.)"; + Name = "Test table (changed.)"; Result = OPI_GoogleSheets.GetSpreadsheet(Token, Spreadsheet); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetTable"); - + OPI_TestDataRetrieval.ExpectsThat(Result["properties"]["title"]).Равно(Name); EndProcedure Procedure GT_FillClearCells() Export - - Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Google_Token"); Spreadsheet = OPI_TestDataRetrieval.GetParameter("GS_Spreadsheet"); - Sheet = "Sheet2"; + Sheet = "Sheet2"; CellStructure = New Map; CellStructure.Insert("A1", "ThisIsA1"); @@ -1605,41 +1605,41 @@ Procedure GT_FillClearCells() Export CellStructure.Insert("A4", "ThisIsA4"); CellStructure.Insert("B1", "ThisIsB1"); CellStructure.Insert("B4", "ThisIsB4"); - + CellsArray = New Array; CellsArray.Add("B2"); CellsArray.Add("A3"); CellsArray.Add("B4"); Result = OPI_GoogleSheets.SetCellValues(Token, Spreadsheet, CellStructure, Sheet); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SetCellValues"); - + OPI_TestDataRetrieval.ExpectsThat(Result["spreadsheetId"]).Равно(Spreadsheet); OPI_TestDataRetrieval.ExpectsThat(Result["totalUpdatedCells"]).Равно(CellStructure.Count()); - + Result = OPI_GoogleSheets.GetCellValues(Token, Spreadsheet, CellsArray, Sheet); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetCellValues"); - + OPI_TestDataRetrieval.ExpectsThat(Result["spreadsheetId"]).Равно(Spreadsheet); OPI_TestDataRetrieval.ExpectsThat(Result["valueRanges"].Count()).Равно(CellsArray.Count()); - + Result = OPI_GoogleSheets.GetCellValues(Token, Spreadsheet, , Sheet); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetCellValues"); - + OPI_TestDataRetrieval.ExpectsThat(Result["spreadsheetId"]).Равно(Spreadsheet); - + CellsArray = New Array; CellsArray.Add("B2"); CellsArray.Add("A3"); CellsArray.Add("B4"); Result = OPI_GoogleSheets.ClearCells(Token, Spreadsheet, CellsArray, Sheet); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ClearCells"); - + OPI_TestDataRetrieval.ExpectsThat(Result["spreadsheetId"]).Равно(Spreadsheet); OPI_TestDataRetrieval.ExpectsThat(Result["clearedRanges"].Count()).Равно(CellsArray.Count()); @@ -1650,154 +1650,154 @@ EndProcedure #Region Twitter Procedure Twitter_GetAuthorizationLink() Export - + Parameters = GetTwitterParameters(); - Result = OPI_Twitter.GetAuthorizationLink(Parameters); - + Result = OPI_Twitter.GetAuthorizationLink(Parameters); + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("String").Заполнено(); - + OPI_TestDataRetrieval.WriteParameter("Twitter_URL", Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Twitter_UpdateToken() Export - + Parameters = GetTwitterParameters(); - Result = OPI_Twitter.RefreshToken(Parameters); - + Result = OPI_Twitter.RefreshToken(Parameters); + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["access_token"]).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["refresh_token"]).Заполнено(); - + Refresh = Result["refresh_token"]; - Token = Result["access_token"]; - - If ValueIsFilled(Refresh) And Not Refresh = "null" Then + Token = Result["access_token"]; + + If ValueIsFilled(Refresh) And Not Refresh = "null" Then OPI_TestDataRetrieval.WriteParameter("Twitter_Refresh", Refresh); EndIf; - + If ValueIsFilled(Token) And Not Token = "null" Then OPI_TestDataRetrieval.WriteParameter("Twitter_Token" , Token); EndIf; - + OPI_Tools.Pause(5); - + EndProcedure Procedure Twitter_CreateTextTweet() Export - + Parameters = GetTwitterParameters(); - Text = "TestTweet" + String(New UUID); - + Text = "TestTweet" + String(New UUID); + Result = OPI_Twitter.CreateTextTweet(Text, Parameters); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateTextTweet"); - + Check_TwitterText(Result, Text); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Twitter_CreateTweetWithImage() Export - + Parameters = GetTwitterParameters(); - Text = "TestTweet" + String(New UUID); - Image = OPI_TestDataRetrieval.GetBinary("Picture"); - TFN = GetTempFileName("png"); + Text = "TestTweet" + String(New UUID); + Image = OPI_TestDataRetrieval.GetBinary("Picture"); + TFN = GetTempFileName("png"); Image.Write(TFN); - - Result = OPI_Twitter.CreateImageTweet(Text, Image, Parameters); - + + Result = OPI_Twitter.CreateImageTweet(Text, Image, Parameters); + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateTweetImages"); - - Check_TwitterText(Result, Text); - - Text = "TestTweet" + String(New UUID); - Result = OPI_Twitter.CreateImageTweet(Text, TFN, Parameters); - - // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateTweetImages"); - + Check_TwitterText(Result, Text); - + + Text = "TestTweet" + String(New UUID); + Result = OPI_Twitter.CreateImageTweet(Text, TFN, Parameters); + + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateTweetImages"); + + Check_TwitterText(Result, Text); + DeleteFiles(TFN); - + OPI_Tools.Pause(20); - + EndProcedure Procedure Twitter_CreateTweetWithVideo() Export - + Parameters = GetTwitterParameters(); - Text = "TestTweet" + String(New UUID); - Video = OPI_TestDataRetrieval.GetBinary("Video"); - TFN = GetTempFileName("mp4"); + Text = "TestTweet" + String(New UUID); + Video = OPI_TestDataRetrieval.GetBinary("Video"); + TFN = GetTempFileName("mp4"); Video.Write(TFN); - - Result = OPI_Twitter.CreateVideoTweet(Text, Video, Parameters); - + + Result = OPI_Twitter.CreateVideoTweet(Text, Video, Parameters); + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateTweetVideo"); - - Check_TwitterText(Result, Text); - - Text = "TestTweet" + String(New UUID); - Result = OPI_Twitter.CreateVideoTweet(Text, TFN, Parameters); - - // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateTweetVideo"); - + Check_TwitterText(Result, Text); - + + Text = "TestTweet" + String(New UUID); + Result = OPI_Twitter.CreateVideoTweet(Text, TFN, Parameters); + + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateTweetVideo"); + + Check_TwitterText(Result, Text); + DeleteFiles(TFN); - + OPI_Tools.Pause(20); - + EndProcedure Procedure Twitter_CreateTweetWithGif() Export - + Parameters = GetTwitterParameters(); - Text = "TestTweet" + String(New UUID); - GIF = OPI_TestDataRetrieval.GetBinary("GIF"); - TFN = GetTempFileName("gif"); + Text = "TestTweet" + String(New UUID); + GIF = OPI_TestDataRetrieval.GetBinary("GIF"); + TFN = GetTempFileName("gif"); GIF.Write(TFN); - - Result = OPI_Twitter.CreateGifTweet(Text, GIF, Parameters); - + + Result = OPI_Twitter.CreateGifTweet(Text, GIF, Parameters); + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateTweetGif"); - - Check_TwitterText(Result, Text); - - Text = "TestTweet" + String(New UUID); - Result = OPI_Twitter.CreateGifTweet(Text, TFN, Parameters); - - // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateTweetGif"); - + Check_TwitterText(Result, Text); - + + Text = "TestTweet" + String(New UUID); + Result = OPI_Twitter.CreateGifTweet(Text, TFN, Parameters); + + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateTweetGif"); + + Check_TwitterText(Result, Text); + DeleteFiles(TFN); - + OPI_Tools.Pause(20); - + EndProcedure Procedure Twitter_CreateTweetWithPoll() Export - - Parameters = GetTwitterParameters(); - Text = "TestTweet" + String(New UUID); + + Parameters = GetTwitterParameters(); + Text = "TestTweet" + String(New UUID); AnswersArray = New Array; AnswersArray.Add("Option 1"); AnswersArray.Add("Option 2"); - + Result = OPI_Twitter.CreatePollTweet(Text, AnswersArray, 60, Parameters); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateTweetPoll"); - + Check_TwitterText(Result, Text); - + OPI_Tools.Pause(20); - + EndProcedure #EndRegion @@ -1805,203 +1805,203 @@ EndProcedure #Region Notion Procedure Notion_CreatePage() Export - - Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); Parent = OPI_TestDataRetrieval.GetParameter("Notion_Parent"); - Title = "TestTitle"; - + Title = "TestTitle"; + Result = OPI_Notion.CreatePage(Token, Parent, Title); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreatePage"); - + Check_NotionObject(Result); EndProcedure Procedure Notion_CreateEditDatabase() Export - - Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); Parent = OPI_TestDataRetrieval.GetParameter("Notion_Parent"); - Title = "TestTitle"; - + Title = "TestTitle"; + Properties = New Map; - Properties.Insert("Name" , "title"); - Properties.Insert("Description" , "rich_text"); - Properties.Insert("Number" , "number"); - Properties.Insert("Status" , "status"); + Properties.Insert("Name" , "title"); + Properties.Insert("Description" , "rich_text"); + Properties.Insert("Number" , "number"); + Properties.Insert("Status" , "status"); Properties.Insert("CreationDate" , "date"); - Properties.Insert("Image" , "files"); - Properties.Insert("Active" , "checkbox"); - Properties.Insert("Website" , "url"); - Properties.Insert("Email" , "email"); - Properties.Insert("Phone" , "phone_number"); - Properties.Insert("User" , "people"); - + Properties.Insert("Image" , "files"); + Properties.Insert("Active" , "checkbox"); + Properties.Insert("Website" , "url"); + Properties.Insert("Email" , "email"); + Properties.Insert("Phone" , "phone_number"); + Properties.Insert("User" , "people"); + ValueSelection = New Map; - ValueSelection.Insert("New", "green"); + ValueSelection.Insert("New" , "green"); ValueSelection.Insert("InProgress", "yellow"); - ValueSelection.Insert("Remote", "red"); + ValueSelection.Insert("Remote" , "red"); Properties.Insert("Status", ValueSelection); - - Result = OPI_Notion.CreateDatabase(Token, Parent, Title, Properties); - + + Result = OPI_Notion.CreateDatabase(Token, Parent, Title, Properties); + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateDatabase"); - + Check_NotionObject(Result, "database"); - - Base = Result["id"]; - Title = "TestTitle"; + + Base = Result["id"]; + Title = "TestTitle"; Description = "TestDescription"; - + Properties = New Map; Properties.Insert("Email", "rich_text"); // Type fields "Email" will changed with email to text Properties.Insert("Website"); // Field "Website" will deleted - + Result = OPI_Notion.EditDatabaseProperties(Token, Base, Properties, Title, Description); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "EditDatabaseProperties"); - + Check_NotionObject(Result, "database"); EndProcedure Procedure Notion_GetPageInfo() Export - + Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); - Page = OPI_TestDataRetrieval.GetParameter("Notion_Page"); - + Page = OPI_TestDataRetrieval.GetParameter("Notion_Page"); + Result = OPI_Notion.GetPage(Token, Page); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetPage"); - - Check_NotionObject(Result); - + + Check_NotionObject(Result); + EndProcedure Procedure Notion_GetDatabaseInfo() Export Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); - Base = OPI_TestDataRetrieval.GetParameter("Notion_Base"); - + Base = OPI_TestDataRetrieval.GetParameter("Notion_Base"); + Result = OPI_Notion.GetDatabase(Token, Base); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetDatabase"); - + Check_NotionObject(Result, "database"); - + EndProcedure Procedure Notion_CreatePageInDatabase() Export - + Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); - Base = OPI_TestDataRetrieval.GetParameter("Notion_Base"); - + Base = OPI_TestDataRetrieval.GetParameter("Notion_Base"); + Image = New Map; Image.Insert("Logo", OPI_TestDataRetrieval.GetParameter("Picture")); - + Properties = New Map; - Properties.Insert("Name" , "LLC Vector"); - Properties.Insert("Description" , "OurFirstClient"); - Properties.Insert("Number" , 1); - Properties.Insert("Status" , "Regular"); + Properties.Insert("Name" , "LLC Vector"); + Properties.Insert("Description" , "OurFirstClient"); + Properties.Insert("Number" , 1); + Properties.Insert("Status" , "Regular"); Properties.Insert("CreationDate" , OPI_Tools.GetCurrentDate()); - Properties.Insert("Image" , Image); - Properties.Insert("Active" , True); - Properties.Insert("Website" , "https://vector.ru"); - Properties.Insert("Email" , "mail@vector.ru"); - Properties.Insert("Phone" , "88005553535"); - Properties.Insert("Status" , "New"); - + Properties.Insert("Image" , Image); + Properties.Insert("Active" , True); + Properties.Insert("Website" , "https://vector.ru"); + Properties.Insert("Email" , "mail@vector.ru"); + Properties.Insert("Phone" , "88005553535"); + Properties.Insert("Status" , "New"); + Result = OPI_Notion.CreatePageInDatabase(Token, Base, Properties); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreatePageInDatabase"); - + Check_NotionObject(Result); - + Parent = StrReplace(Result["parent"]["database_id"], "-", ""); OPI_TestDataRetrieval.ExpectsThat(Parent).Равно(Base); - + EndProcedure Procedure Notion_EditPageProperties() Export - - Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); - Page = OPI_TestDataRetrieval.GetParameter("Notion_Page"); - Icon = OPI_TestDataRetrieval.GetParameter("Picture"); - Cover = OPI_TestDataRetrieval.GetParameter("Picture2"); + + Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); + Page = OPI_TestDataRetrieval.GetParameter("Notion_Page"); + Icon = OPI_TestDataRetrieval.GetParameter("Picture"); + Cover = OPI_TestDataRetrieval.GetParameter("Picture2"); Archive = False; - + Properties = New Map; Properties.Insert("Active" , False); - Properties.Insert("Email" , "vector@mail.ru"); - + Properties.Insert("Email" , "vector@mail.ru"); + Result = OPI_Notion.EditPageProperties(Token , Page , Properties , Icon , Cover , Archive); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "EditPageProperties"); - + Check_NotionObject(Result); - + EndProcedure Procedure Notion_CreateDeleteBlock() Export - - Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); Parent = OPI_TestDataRetrieval.GetParameter("Notion_Parent"); - Block = OPI_TestDataRetrieval.GetParameter("Notion_Block"); - - Result = OPI_Notion.ReturnBlock(Token, Block); - + Block = OPI_TestDataRetrieval.GetParameter("Notion_Block"); + + Result = OPI_Notion.ReturnBlock(Token, Block); + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ReturnBlock"); - + Check_NotionObject(Result, "block"); - + Result = OPI_Notion.CreateBlock(Token, Parent, Result); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateBlock"); - + Check_NotionObject(Result, "list"); - + Block = Result["results"][0]["id"]; - Result = OPI_Notion.ReturnChildBlocks(Token, Block); - + Result = OPI_Notion.ReturnChildBlocks(Token, Block); + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ReturnChildBlocks"); - + Check_NotionObject(Result, "list"); - + Result = OPI_Notion.DeleteBlock(Token, Block); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteBlock"); - + Check_NotionObject(Result, "block"); - + EndProcedure Procedure Notion_GetUsers() Export - - Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); Result = OPI_Notion.UserList(Token); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UserList"); - + Check_NotionObject(Result, "list"); - + EndProcedure Procedure Notion_GetUserData() Export - - Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); - User = OPI_TestDataRetrieval.GetParameter("Notion_User"); + + Token = OPI_TestDataRetrieval.GetParameter("Notion_Token"); + User = OPI_TestDataRetrieval.GetParameter("Notion_User"); Result = OPI_Notion.GetUserData(Token, User); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetUserData"); - + Check_NotionObject(Result, "user"); - + EndProcedure #EndRegion @@ -2009,160 +2009,160 @@ EndProcedure #Region Slack Procedure Slack_GetBotInfo() Export - - Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); Result = OPI_Slack.GetBotInformation(Token); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetBotInfo"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["bot_id"]).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["user_id"]).Заполнено(); - + EndProcedure Procedure Slack_GetUserList() Export - - Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); Result = OPI_Slack.GetUserList(Token); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetUserList"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["members"]).ИмеетТип("Array"); - + EndProcedure Procedure Slack_GetRegionList() Export - - Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); Result = OPI_Slack.GetWorkspaceList(Token); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetWorkspaceList"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["teams"]).ИмеетТип("Array"); - + EndProcedure Procedure Slack_SendDeleteMessage() Export - Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); + Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); Channel = OPI_TestDataRetrieval.GetParameter("Slack_Channel"); - Text = "TestMessage1"; - Text2 = "TestMessage2"; - Tags = New Array; - Image = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/Media/logo.png?v1"; - + Text = "TestMessage1"; + Text2 = "TestMessage2"; + Tags = New Array; + Image = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/Media/logo.png?v1"; + Result = OPI_Slack.SendMessage(Token, Channel, Text); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendMessage"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["channel"]).Равно(Channel); OPI_TestDataRetrieval.ExpectsThat(Result["ts"]).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["message"]["text"]).Равно(Text); - + Timestamp = Result["ts"]; - + Result = OPI_Slack.EditMessage(Token, Channel, Timestamp, Text2); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "EditMessage"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["channel"]).Равно(Channel); OPI_TestDataRetrieval.ExpectsThat(Result["ts"]).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["message"]["text"]).Равно(Text2); - + Result = OPI_Slack.GetMessageReplyList(Token, Channel, Timestamp); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetMessageReplyList"); - + OPI_TestDataRetrieval.ExpectsThat(Result["messages"]).ИмеетТип("Array"); - + Result = OPI_Slack.GetMessageLink(Token, Channel, Timestamp); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetMessageLink"); - + OPI_TestDataRetrieval.ExpectsThat(Result["channel"]).Равно(Channel); OPI_TestDataRetrieval.ExpectsThat(Result["permalink"]).Заполнено(); - + Check_SlackOk(Result); - + Tags.Add(Timestamp); - + BlockArray = New Array; - Block = OPI_Slack.GenerateImageBlock(Image, "Yo"); + Block = OPI_Slack.GenerateImageBlock(Image, "Yo"); BlockArray.Add(Block); - + Result = OPI_Slack.SendMessage(Token, Channel, Text, , BlockArray); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendMessage (image)"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["channel"]).Равно(Channel); OPI_TestDataRetrieval.ExpectsThat(Result["ts"]).Заполнено(); - + Tags.Add(Result["ts"]); - - Block = OPI_Slack.GenerateImageBlock(Image, "Yo"); + + Block = OPI_Slack.GenerateImageBlock(Image, "Yo"); JSONBlock = OPI_Tools.JSONString(Block); - + TFN = GetTempFileName("json"); - + TextDocument = New TextDocument(); TextDocument.SetText(JSONBlock); TextDocument.Write(TFN); - + Result = OPI_Slack.SendMessage(Token, Channel, Text, , TFN); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendMessage (json)"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["channel"]).Равно(Channel); OPI_TestDataRetrieval.ExpectsThat(Result["ts"]).Заполнено(); - + Tags.Add(Result["ts"]); - + Blocks = "['" + TFN + "','" + TFN + "']"; Result = OPI_Slack.SendMessage(Token, Channel, Text, , Blocks); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendMessage (json array)"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["channel"]).Равно(Channel); OPI_TestDataRetrieval.ExpectsThat(Result["ts"]).Заполнено(); - + Tags.Add(Result["ts"]); DeleteFiles(TFN); - + For Each Timestamp In Tags Do - + Result = OPI_Slack.DeleteMessage(Token, Channel, Timestamp); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteMessage"); Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["channel"]).Равно(Channel); OPI_TestDataRetrieval.ExpectsThat(Result["ts"]).Заполнено(); - + EndDo; - - Hour = 3600; - Day = 24; + + Hour = 3600; + Day = 24; Sending = OPI_Tools.GetCurrentDate() + (Day * Hour); - Result = OPI_Slack.SendMessage(Token, Channel, Text, Sending); - + Result = OPI_Slack.SendMessage(Token, Channel, Text, Sending); + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendDelayedMessage)"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["channel"]).Равно(Channel); OPI_TestDataRetrieval.ExpectsThat(Result["scheduled_message_id"]).Заполнено(); - + Timestamp = Result["scheduled_message_id"]; - Result = OPI_Slack.DeleteMessage(Token, Channel, Timestamp, True); - + Result = OPI_Slack.DeleteMessage(Token, Channel, Timestamp, True); + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteMessage"); Check_SlackOk(Result); @@ -2170,51 +2170,51 @@ Procedure Slack_SendDeleteMessage() Export EndProcedure Procedure Slack_SendDeleteEphemeral() Export - - Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); Channel = OPI_TestDataRetrieval.GetParameter("Slack_Channel"); - User = OPI_TestDataRetrieval.GetParameter("Slack_User"); - Image = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/Media/logo.png?v1"; - Text = "TestMessage1"; - - Block = OPI_Slack.GenerateImageBlock(Image, "Yo"); + User = OPI_TestDataRetrieval.GetParameter("Slack_User"); + Image = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/Media/logo.png?v1"; + Text = "TestMessage1"; + + Block = OPI_Slack.GenerateImageBlock(Image, "Yo"); Result = OPI_Slack.SendEphemeralMessage(Token, Channel, Text, User, Block); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendMessage"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["message_ts"]).Заполнено(); - + EndProcedure Procedure Slack_GetScheduledMessages() Export - - Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); Channel = OPI_TestDataRetrieval.GetParameter("Slack_Channel"); - + Result = OPI_Slack.GetDelayedMessageList(Token, Channel); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetDelayedMessageList"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["scheduled_messages"]).ИмеетТип("Array"); - + EndProcedure Procedure Slack_CreateArchiveChannel() Export - - Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); - User = OPI_TestDataRetrieval.GetParameter("Slack_User"); - Name = "testconv" + String(New UUID); - Topic = "TestTopic"; + + Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); + User = OPI_TestDataRetrieval.GetParameter("Slack_User"); + Name = "testconv" + String(New UUID); + Topic = "TestTopic"; Purpose = "TestGoal"; - + #Region CreateChannel Result = OPI_Slack.CreateChannel(Token, Name); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateChannel"); - - Data = Result["channel"]; + + Data = Result["channel"]; Channel = Data["id"]; Check_SlackOk(Result); @@ -2223,154 +2223,154 @@ Procedure Slack_CreateArchiveChannel() Export #Region SetChannelTopic Result = OPI_Slack.SetChannelTopic(Token, Channel, Topic); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SetChannelTheme"); - - Data = Result["channel"]; + + Data = Result["channel"]; Channel = Data["id"]; Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Data["name"]).Равно(Name); OPI_TestDataRetrieval.ExpectsThat(Data["topic"]["value"]).Равно(Topic); #EndRegion - + #Region SetChannelGoal Result = OPI_Slack.SetChannelGoal(Token, Channel, Purpose); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SetChannelGoal"); - + Check_SlackOk(Result); #EndRegion - + #Region GetChannel Result = OPI_Slack.GetChannel(Token, Channel); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetChannel"); - - Data = Result["channel"]; + + Data = Result["channel"]; Channel = Data["id"]; Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Data["name"]).Равно(Name); #EndRegion - + #Region InviteUsersToChannel Result = OPI_Slack.InviteUsersToChannel(Token, Channel, User); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "InviteUsersToChannel"); - - Data = Result["channel"]; + + Data = Result["channel"]; Channel = Data["id"]; Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Data["name"]).Равно(Name); #EndRegion - + #Region KickUserFromChannel Result = OPI_Slack.KickUserFromChannel(Token, Channel, User); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "KickUserFromChannel"); - + Check_SlackOk(Result); #EndRegion - + #Region GetChannelHistory Result = OPI_Slack.GetChannelHistory(Token, Channel); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetChannelHistory"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["messages"]).ИмеетТип("Array"); #EndRegion - + #Region GetChannelUserList Result = OPI_Slack.GetChannelUserList(Token, Channel); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetChannelUserList"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["members"]).ИмеетТип("Array"); #EndRegion #Region LeaveChannel Result = OPI_Slack.LeaveChannel(Token, Channel); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "LeaveChannel"); - + Check_SlackOk(Result); #EndRegion - + #Region JoinChannel Result = OPI_Slack.JoinChannel(Token, Channel); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "JoinChannel"); - - Data = Result["channel"]; + + Data = Result["channel"]; Channel = Data["id"]; Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Data["name"]).Равно(Name); #EndRegion - + #Region RenameChannel NewName = "testconv" + String(New UUID); - Result = OPI_Slack.RenameChannel(Token, Channel, NewName); - + Result = OPI_Slack.RenameChannel(Token, Channel, NewName); + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "RenameChannel"); - - Data = Result["channel"]; + + Data = Result["channel"]; Channel = Data["id"]; Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Data["name"]).Равно(NewName); #EndRegion - + #Region ArchiveChannel Result = OPI_Slack.ArchiveChannel(Token, Channel); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ArchiveChannel"); - + Check_SlackOk(Result); #EndRegion - + EndProcedure Procedure Slack_GetChannelList() Export - + Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); - + Result = OPI_Slack.GetChannelList(Token); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetChannelList"); Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["channels"]).ИмеетТип("Array"); - + EndProcedure Procedure Slack_OpenCloseDialog() Export - + Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); - User = OPI_TestDataRetrieval.GetParameter("Slack_User"); - Text = "Yo, dude"; - + User = OPI_TestDataRetrieval.GetParameter("Slack_User"); + Text = "Yo, dude"; + Result = OPI_Slack.OpenDialog(Token, User); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "OpenDialog"); Dialog = Result["channel"]["id"]; Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["channel"]).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Dialog).Заполнено(); - + Result = OPI_Slack.SendMessage(Token, Dialog, Text); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendMessage"); - + Check_SlackOk(Result); Result = OPI_Slack.CloseDialog(Token, Dialog); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CloseDialog"); Check_SlackOk(Result); @@ -2378,12 +2378,12 @@ Procedure Slack_OpenCloseDialog() Export EndProcedure Procedure Slack_GetFileList() Export - - Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); Channel = OPI_TestDataRetrieval.GetParameter("Slack_Channel"); - + Result = OPI_Slack.GetFilesList(Token, Channel); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetFileList"); Check_SlackOk(Result); @@ -2392,113 +2392,113 @@ Procedure Slack_GetFileList() Export EndProcedure Procedure Slack_UploadDeleteFile() Export - - Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); - File = OPI_TestDataRetrieval.GetBinary("Document"); - Channel = OPI_TestDataRetrieval.GetParameter("Slack_Channel"); + + Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); + File = OPI_TestDataRetrieval.GetBinary("Document"); + Channel = OPI_TestDataRetrieval.GetParameter("Slack_Channel"); ArrayOfFiles = New Array; - FileName = "megadoc.docx"; - Title = "NewFile"; - + FileName = "megadoc.docx"; + Title = "NewFile"; + Result = OPI_Slack.UploadFile(Token, File, FileName, Title); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UploadFile"); UploadedFile = Result["files"][0]; ArrayOfFiles.Add(UploadedFile["id"]); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(UploadedFile["name"]).Равно(FileName); - + Result = OPI_Slack.UploadFile(Token, File, FileName, Title, Channel); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UploadFile (to channel)"); UploadedFile = Result["files"][0]; ArrayOfFiles.Add(UploadedFile["id"]); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(UploadedFile["name"]).Равно(FileName); - + Result = OPI_Slack.GetFileData(Token, UploadedFile["id"]); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetFile"); - + UploadedFile = Result["file"]; - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(UploadedFile["name"]).Равно(FileName); - + For Each UploadedFile In ArrayOfFiles Do - + Result = OPI_Slack.DeleteFile(Token, UploadedFile); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteFile"); - + Check_SlackOk(Result); - + EndDo; EndProcedure Procedure Slack_GetExternalFileList() Export - - Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); Channel = OPI_TestDataRetrieval.GetParameter("Slack_Channel"); - + Result = OPI_Slack.GetExternalFileList(Token); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetExternalFileList"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["files"]).ИмеетТип("Array"); - + Result = OPI_Slack.GetExternalFileList(Token, Channel); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetExternalFileList"); - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(Result["files"]).ИмеетТип("Array"); - + EndProcedure Procedure Slack_UploadDeleteExternalFile() Export - - Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); - File = OPI_TestDataRetrieval.GetParameter("Document"); + + Token = OPI_TestDataRetrieval.GetParameter("Slack_Token"); + File = OPI_TestDataRetrieval.GetParameter("Document"); Channel = OPI_TestDataRetrieval.GetParameter("Slack_Channel"); - Title = "NewFile"; - + Title = "NewFile"; + Result = OPI_Slack.AddExternalFile(Token, File, Title); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "AddExternalFile"); - + UploadedFile = Result["file"]; - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(UploadedFile["title"]).Равно(Title); - + Result = OPI_Slack.GetExternalFile(Token, UploadedFile["id"]); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetExternalFile"); - + UploadedFile = Result["file"]; - + Check_SlackOk(Result); OPI_TestDataRetrieval.ExpectsThat(UploadedFile["title"]).Равно(Title); - + Result = OPI_Slack.SendExternalFile(Token, UploadedFile["id"], Channel); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendExternalFile"); - + Check_SlackOk(Result); - + Result = OPI_Slack.DeleteExternalFile(Token, UploadedFile["id"]); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendExternalFile"); - + Check_SlackOk(Result); - + EndProcedure #EndRegion @@ -2506,222 +2506,222 @@ EndProcedure #Region Airtable Procedure AT_CreateDatabase() Export - - Token = OPI_TestDataRetrieval.GetParameter("Airtable_Token"); + + Token = OPI_TestDataRetrieval.GetParameter("Airtable_Token"); Region = OPI_TestDataRetrieval.GetParameter("Airtable_Workspace"); - Name = "TestDatabase"; - + Name = "TestDatabase"; + FieldArray = New Array; FieldArray.Add(OPI_Airtable.GetNumberField("Number")); FieldArray.Add(OPI_Airtable.GetStringField("String")); - + TableName = "TestTable"; - + TableMapping = New Map; TableMapping.Insert(TableName, FieldArray); - + Result = OPI_Airtable.CreateDatabase(Token, Region, Name, TableMapping); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateDatabase"); - + OPI_TestDataRetrieval.ExpectsThat(Result["id"]).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["tables"][0]["name"]).Равно(TableName); - + Base = Result["id"]; OPI_TestDataRetrieval.WriteParameter("Airtable_Base", Base); - + Result = OPI_Airtable.GetDatabaseTables(Token, Base); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetDatabaseTables"); - + OPI_TestDataRetrieval.ExpectsThat(Result["tables"]).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["tables"]).ИмеетТип("Array"); Result = OPI_Airtable.GetListOfBases(Token); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetDatabaseList"); - + OPI_TestDataRetrieval.ExpectsThat(Result["bases"]).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["bases"]).ИмеетТип("Array"); - + EndProcedure Procedure AT_CreateTable() Export - + Token = OPI_TestDataRetrieval.GetParameter("Airtable_Token"); - Base = OPI_TestDataRetrieval.GetParameter("Airtable_Base"); - + Base = OPI_TestDataRetrieval.GetParameter("Airtable_Base"); + FieldArray = New Array; - FieldArray.Add(OPI_Airtable.GetNumberField("Number")); + FieldArray.Add(OPI_Airtable.GetNumberField("Number")); // !OInt OPI_TestDataRetrieval.WriteLog(FieldArray[0], "GetNumberField"); - + FieldArray.Add(OPI_Airtable.GetStringField("String")); // !OInt OPI_TestDataRetrieval.WriteLog(FieldArray[1], "GetStringField"); - + FieldArray.Add(OPI_Airtable.GetAttachmentField("Attachment")); // !OInt OPI_TestDataRetrieval.WriteLog(FieldArray[2], "GetAttachmentField"); - + FieldArray.Add(OPI_Airtable.GetCheckboxField("Checkbox")); // !OInt OPI_TestDataRetrieval.WriteLog(FieldArray[3], "GetCheckboxField"); - + FieldArray.Add(OPI_Airtable.GetDateField("Date")); // !OInt OPI_TestDataRetrieval.WriteLog(FieldArray[4], "GetDateField"); - + FieldArray.Add(OPI_Airtable.GetPhoneField("Phone")); // !OInt OPI_TestDataRetrieval.WriteLog(FieldArray[5], "GetPhoneField"); - + FieldArray.Add(OPI_Airtable.GetEmailField("Email")); - // !OInt OPI_TestDataRetrieval.WriteLog(FieldArray[6], "GetEmailField"); - + // !OInt OPI_TestDataRetrieval.WriteLog(FieldArray[6], "GetEmailField"); + FieldArray.Add(OPI_Airtable.GetLinkField("Link")); - // !OInt OPI_TestDataRetrieval.WriteLog(FieldArray[7], "GetLinkField"); - - TableName = "TestTable2"; + // !OInt OPI_TestDataRetrieval.WriteLog(FieldArray[7], "GetLinkField"); + + TableName = "TestTable2"; Description = "NewTable"; - + Result = OPI_Airtable.CreateTable(Token, Base, TableName, FieldArray, Description); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateTable"); - + OPI_TestDataRetrieval.ExpectsThat(Result["name"]).Равно(TableName); OPI_TestDataRetrieval.ExpectsThat(Result["description"]).Равно(Description); - - Table = Result["id"]; - TableName = "Test table 2 (change.)"; + + Table = Result["id"]; + TableName = "Test table 2 (change.)"; Description = "New table (change.)"; - + OPI_TestDataRetrieval.WriteParameter("Airtable_Table", Table); - + Result = OPI_Airtable.ModifyTable(Token, Base, Table, TableName, Description); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "EditTable"); - + OPI_TestDataRetrieval.ExpectsThat(Result["name"]).Равно(TableName); OPI_TestDataRetrieval.ExpectsThat(Result["description"]).Равно(Description); EndProcedure Procedure AT_CreateField() Export - + Token = OPI_TestDataRetrieval.GetParameter("Airtable_Token"); - Base = OPI_TestDataRetrieval.GetParameter("Airtable_Base"); + Base = OPI_TestDataRetrieval.GetParameter("Airtable_Base"); Table = OPI_TestDataRetrieval.GetParameter("Airtable_Table"); - Name = String(New UUID); - + Name = String(New UUID); + Field = OPI_Airtable.GetNumberField(Name); - + Result = OPI_Airtable.CreateField(Token, Base, Table, Field); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateField"); - + OPI_TestDataRetrieval.ExpectsThat(Result["name"]).Равно(Name); - - Field = Result["id"]; - Name = Name + "(change.)"; + + Field = Result["id"]; + Name = Name + "(change.)"; Description = "New description"; - + Result = OPI_Airtable.ModifyField(Token, Base, Table, Field, Name, Description); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ModifyField"); - + OPI_TestDataRetrieval.ExpectsThat(Result["name"]).Равно(Name); OPI_TestDataRetrieval.ExpectsThat(Result["description"]).Равно(Description); - + EndProcedure Procedure AT_CreateDeleteRecords() Export Token = OPI_TestDataRetrieval.GetParameter("Airtable_Token"); - Base = OPI_TestDataRetrieval.GetParameter("Airtable_Base"); + Base = OPI_TestDataRetrieval.GetParameter("Airtable_Base"); Table = OPI_TestDataRetrieval.GetParameter("Airtable_Table"); - - Numeric = 10; + + Numeric = 10; StringType = "Hello"; - + RowDescription1 = New Structure("Number,String", Numeric, StringType); RowDescription2 = New Structure("Number,String", Numeric, StringType); - - ArrayOfDeletions = New Array; + + ArrayOfDeletions = New Array; ArrayOfDescriptions = New Array; ArrayOfDescriptions.Add(RowDescription1); ArrayOfDescriptions.Add(RowDescription2); - + Result = OPI_Airtable.CreatePosts(Token, Base, Table, ArrayOfDescriptions); // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateRecords"); - + OPI_TestDataRetrieval.ExpectsThat(Result["records"]).ИмеетТип("Array"); OPI_TestDataRetrieval.ExpectsThat(Result["records"].Count()).Равно(2); - + For Each Record In Result["records"] Do ArrayOfDeletions.Add(Record["id"]); EndDo; - + Result = OPI_Airtable.CreatePosts(Token, Base, Table, RowDescription1); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateEntries (one)"); - + SingleRecord = Result["id"]; OPI_TestDataRetrieval.ExpectsThat(SingleRecord).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["createdTime"]).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["fields"]["Number"]).Равно(Numeric); OPI_TestDataRetrieval.ExpectsThat(TrimAll(Result["fields"]["String"])).Равно(StringType); - + Result = OPI_Airtable.GetRecord(Token, Base, Table, SingleRecord); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetRecord"); - + OPI_TestDataRetrieval.ExpectsThat(Result["id"]).Равно(SingleRecord); - - Text = "TestComment"; + + Text = "TestComment"; Result = OPI_Airtable.CreateComment(Token, Base, Table, SingleRecord, Text); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateComment"); - + OPI_TestDataRetrieval.ExpectsThat(Result["text"]).Равно(Text); - + Comment = Result["id"]; - Text = "Test comment (change.)"; - Result = OPI_Airtable.EditComment(Token, Base, Table, SingleRecord, Comment, Text); - + Text = "Test comment (change.)"; + Result = OPI_Airtable.EditComment(Token, Base, Table, SingleRecord, Comment, Text); + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "EditComment"); - + OPI_TestDataRetrieval.ExpectsThat(Result["text"]).Равно(Text); - + Result = OPI_Airtable.GetComments(Token, Base, Table, SingleRecord); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetComments"); - + OPI_TestDataRetrieval.ExpectsThat(Result["comments"]).ИмеетТип("Array"); - + Result = OPI_Airtable.DeleteComment(Token, Base, Table, SingleRecord, Comment); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteComment"); - + OPI_TestDataRetrieval.ExpectsThat(Result["deleted"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["id"]).Равно(Comment); - + Result = OPI_Airtable.GetListOfRecords(Token, Base, Table); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetEntryList"); - + OPI_TestDataRetrieval.ExpectsThat(Result["records"]).ИмеетТип("Array"); OPI_TestDataRetrieval.ExpectsThat(Result["records"]).Заполнено(); - + Result = OPI_Airtable.DeletePosts(Token, Base, Table, ArrayOfDeletions); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteRecords"); - + OPI_TestDataRetrieval.ExpectsThat(Result["records"]).ИмеетТип("Array"); OPI_TestDataRetrieval.ExpectsThat(Result["records"]).Заполнено(); - + Result = OPI_Airtable.DeletePosts(Token, Base, Table, SingleRecord); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteEntries (one)"); - + OPI_TestDataRetrieval.ExpectsThat(Result["records"]).ИмеетТип("Array"); OPI_TestDataRetrieval.ExpectsThat(Result["records"]).Заполнено(); - + EndProcedure #EndRegion @@ -2729,29 +2729,29 @@ EndProcedure #Region Dropbox Procedure DropboxAPI_GetUpdateToken() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Dropbox_Appkey" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Dropbox_Appkey" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Dropbox_Appsecret", TestParameters); - - Dropbox_GetAuthorizationLink(TestParameters); - + + Dropbox_GetAuthorizationLink(TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Dropbox_Code", TestParameters); Dropbox_GetToken(TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("Dropbox_Refresh", TestParameters); - + Dropbox_UpdateToken(TestParameters); - + EndProcedure Procedure DropboxAPI_UploadFile() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Dropbox_Token", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Picture", TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); + Dropbox_UploadFile(TestParameters); Dropbox_GetObjectInformation(TestParameters); Dropbox_GetObjectVersionList(TestParameters); @@ -2761,73 +2761,73 @@ Procedure DropboxAPI_UploadFile() Export Dropbox_MoveObject(TestParameters); Dropbox_CopyObject(TestParameters); Dropbox_DeleteObject(TestParameters); - + EndProcedure Procedure DropboxAPI_CreateFolder() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Dropbox_Token", TestParameters); - + Dropbox_CreateFolder(TestParameters); Dropbox_DownloadFolder(TestParameters); - + EndProcedure Procedure DropboxAPI_GetFolderFileList() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Dropbox_Token", TestParameters); - + Dropbox_GetFolderFileList(TestParameters); - + EndProcedure Procedure DropboxAPI_UploadFileByURL() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Dropbox_Token", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Document", TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("Document" , TestParameters); + Dropbox_UploadFileByURL(TestParameters); Dropbox_GetUploadStatusByURL(TestParameters); - + EndProcedure Procedure DropboxAPI_CreateDeleteTag() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Dropbox_Token", TestParameters); - + Dropbox_AddTag(TestParameters); Dropbox_GetTagList(TestParameters); Dropbox_DeleteTag(TestParameters); - + EndProcedure Procedure DropboxAPI_GetAccount() Export - + TestParameters = New Structure; OPI_TestDataRetrieval.ParameterToCollection("Dropbox_Token", TestParameters); - + Dropbox_GetAccountInformation(TestParameters); Dropbox_GetSpaceUsageData(TestParameters); - + EndProcedure Procedure DropboxAPI_AccessManagement() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Dropbox_Token" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Dropbox_Token" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Dropbox_OtherUser", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Dropbox_FileID" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("Dropbox_FileID" , TestParameters); + Dropbox_AddUsersToFile(TestParameters); Dropbox_PublishFolder(TestParameters); Dropbox_AddUsersToFolder(TestParameters); Dropbox_CancelFolderPublication(TestParameters); Dropbox_CancelFilePublication(TestParameters); - + EndProcedure #EndRegion @@ -2835,43 +2835,43 @@ EndProcedure #Region Bitrix24 Procedure B24_TokenManagment() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Domain" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_ClientID" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Domain" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_ClientID" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_ClientSecret", TestParameters); - + Bitrix24_GetAppAuthLink(TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Code", TestParameters); - + Bitrix24_GetToken(TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Refresh", TestParameters); - + Bitrix24_RefreshToken(TestParameters); - + EndProcedure Procedure B24_ServerTime() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Domain", TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Token" , TestParameters); - - Bitrix24_ServerTime(TestParameters); + + Bitrix24_ServerTime(TestParameters); EndProcedure Procedure B24_PostsManagment() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Domain", TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Picture2" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Picture2" , TestParameters); Bitrix24_CreatePost(TestParameters); Bitrix24_UpdatePost(TestParameters); @@ -2880,18 +2880,18 @@ Procedure B24_PostsManagment() Export Bitrix24_AddPostComment(TestParameters); Bitrix_AddPostRecipients(TestParameters); Bitrix24_DeletePost(TestParameters); - + EndProcedure Procedure B24_TaskManagment() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Domain", TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Token" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_UserID", TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); + Bitrix24_GetTaskFieldsStructure(TestParameters); Bitrix24_CreateTask(TestParameters); Bitrix24_CreateTasksDependencies(TestParameters); @@ -2910,7 +2910,7 @@ Procedure B24_TaskManagment() Export Bitrix24_StartTask(TestParameters); Bitrix24_StartWatchingTask(TestParameters); Bitrix24_StopWatchingTask(TestParameters); - Bitrix24_PauseTask(TestParameters); + Bitrix24_PauseTask(TestParameters); Bitrix24_GetTaskHistory(TestParameters); Bitrix24_GetTasksList(TestParameters); Bitrix24_CheckTaskAccesses(TestParameters); @@ -2922,35 +2922,35 @@ Procedure B24_TaskManagment() Export Bitrix24_RenewTasksChecklistElement(TestParameters); Bitrix24_DeleteTasksChecklistElement(TestParameters); Bitrix24_GetDailyPlan(TestParameters); - - Name = "Topic picture.jpg"; - Image = TestParameters["Picture"]; + + Name = "Topic picture.jpg"; + Image = TestParameters["Picture"]; DestinationID = 3; - + URL = TestParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.UploadFileToStorage(URL, Name, Image, DestinationID); - FileID = Result["result"]["ID"]; - - OPI_TestDataRetrieval.WriteParameter("Bitrix24_TaskFileID", FileID); + FileID = Result["result"]["ID"]; + + OPI_TestDataRetrieval.WriteParameter("Bitrix24_TaskFileID", FileID); TestParameters.Insert("Bitrix24_TaskFileID", FileID); - - Bitrix24_AttachFileToTopic(TestParameters); - + + Bitrix24_AttachFileToTopic(TestParameters); + OPI_Bitrix24.DeleteFile(URL, FileID); - + Bitrix24_DeleteTask(TestParameters); - + EndProcedure Procedure B24_WorkingWithDrive() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Domain", TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Picture2" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Picture2" , TestParameters); Bitrix24_GetStoragesList(TestParameters); Bitrix24_GetAppStorage(TestParameters); @@ -2979,34 +2979,34 @@ Procedure B24_WorkingWithDrive() Export Bitrxi24_MarkFolderAsDeleted(TestParameters); Bitrix24_RestoreFolder(TestParameters); Bitrix24_DeleteFolder(TestParameters); - + EndProcedure Procedure B24_CommentsManagment() Export TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Domain", TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Token" , TestParameters); - + CurrentDate = OPI_Tools.GetCurrentDate(); - Hour = 3600; - Day = 24; + Hour = 3600; + Day = 24; Responsible = 1; - + TaskData = New Structure; - TaskData.Insert("TITLE" , "New task"); - TaskData.Insert("DESCRIPTION" , "New task description"); - TaskData.Insert("PRIORITY" , "2"); - TaskData.Insert("DEADLINE" , CurrentDate + Hour * Day); + TaskData.Insert("TITLE" , "New task"); + TaskData.Insert("DESCRIPTION" , "New task description"); + TaskData.Insert("PRIORITY" , "2"); + TaskData.Insert("DEADLINE" , CurrentDate + Hour * Day); TaskData.Insert("RESPONSIBLE_ID", Responsible); - + URL = TestParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.CreateTask(URL, TaskData); - TaskID = Result["result"]["task"]["id"]; - - OPI_TestDataRetrieval.WriteParameter("Bitrix24_CommentsTaskID", TaskID); + TaskID = Result["result"]["task"]["id"]; + + OPI_TestDataRetrieval.WriteParameter("Bitrix24_CommentsTaskID", TaskID); TestParameters.Insert("Bitrix24_CommentsTaskID", TaskID); Bitrix24_AddTaskComment(TestParameters); @@ -3017,36 +3017,36 @@ Procedure B24_CommentsManagment() Export Bitrix24_GetTaskCommentsList(TestParameters); Bitrix24_GetTaskComment(TestParameters); Bitrix24_DeleteTaskComment(TestParameters); - - OPI_Bitrix24.DeleteTask(URL, TaskID); - + + OPI_Bitrix24.DeleteTask(URL, TaskID); + EndProcedure Procedure B24_Timekeeping() Export TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Domain", TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Token" , TestParameters); - + CurrentDate = OPI_Tools.GetCurrentDate(); - Hour = 3600; - Day = 24; + Hour = 3600; + Day = 24; Responsible = 1; - + TaskData = New Structure; - TaskData.Insert("TITLE" , "New task"); - TaskData.Insert("DESCRIPTION" , "New task description"); - TaskData.Insert("PRIORITY" , "2"); - TaskData.Insert("DEADLINE" , CurrentDate + Hour * Day); + TaskData.Insert("TITLE" , "New task"); + TaskData.Insert("DESCRIPTION" , "New task description"); + TaskData.Insert("PRIORITY" , "2"); + TaskData.Insert("DEADLINE" , CurrentDate + Hour * Day); TaskData.Insert("RESPONSIBLE_ID", Responsible); - + URL = TestParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.CreateTask(URL, TaskData); - TaskID = Result["result"]["task"]["id"]; - - OPI_TestDataRetrieval.WriteParameter("Bitrix24_ElapsedTaskID", TaskID); + TaskID = Result["result"]["task"]["id"]; + + OPI_TestDataRetrieval.WriteParameter("Bitrix24_ElapsedTaskID", TaskID); TestParameters.Insert("Bitrix24_ElapsedTaskID", TaskID); Bitrix24_AddTaskTimeAccounting(TestParameters); @@ -3054,59 +3054,59 @@ Procedure B24_Timekeeping() Export Bitrix24_GetTaskTimeAccountingList(TestParameters); Bitrix24_UpdateTaskTimeAccounting(TestParameters); Bitrix24_DeleteTaskTimeAccounting(TestParameters); - - OPI_Bitrix24.DeleteTask(URL, TaskID); - + + OPI_Bitrix24.DeleteTask(URL, TaskID); + EndProcedure Procedure B24_Kanban() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Domain", TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Token" , TestParameters); - + CurrentDate = OPI_Tools.GetCurrentDate(); - Hour = 3600; - Day = 24; + Hour = 3600; + Day = 24; Responsible = 1; - + TaskData = New Structure; - TaskData.Insert("TITLE" , "New task"); - TaskData.Insert("DESCRIPTION" , "New task description"); - TaskData.Insert("PRIORITY" , "2"); - TaskData.Insert("DEADLINE" , CurrentDate + Hour * Day); + TaskData.Insert("TITLE" , "New task"); + TaskData.Insert("DESCRIPTION" , "New task description"); + TaskData.Insert("PRIORITY" , "2"); + TaskData.Insert("DEADLINE" , CurrentDate + Hour * Day); TaskData.Insert("RESPONSIBLE_ID", Responsible); - + URL = TestParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.CreateTask(URL, TaskData); - TaskID = Result["result"]["task"]["id"]; - - OPI_TestDataRetrieval.WriteParameter("Bitrix24_KanbanTaskID", TaskID); + TaskID = Result["result"]["task"]["id"]; + + OPI_TestDataRetrieval.WriteParameter("Bitrix24_KanbanTaskID", TaskID); TestParameters.Insert("Bitrix24_KanbanTaskID", TaskID); - + Bitrix24_AddKanbanStage(TestParameters); Bitrix24_GetKanbanStages(TestParameters); Bitrix24_MoveTaskToKanbanStage(TestParameters); Bitrix24_UpdateKanbansStage(TestParameters); - - OPI_Bitrix24.DeleteTask(URL, TaskID); - + + OPI_Bitrix24.DeleteTask(URL, TaskID); + Bitrix24_DeleteKanbanStage(TestParameters); - + EndProcedure Procedure B24_ChatManagment() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Domain", TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Picture2" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Document" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Picture2" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Document" , TestParameters); + Bitrix24_GetUserStatus(TestParameters); Bitrix24_SetUserStatus(TestParameters); Bitrix24_GetUsers(TestParameters); @@ -3134,23 +3134,23 @@ Procedure B24_ChatManagment() Export Bitrix24_ReadAll(TestParameters); Bitrix24_ChangeChatOwner(TestParameters); Bitrix24_LeaveChat(TestParameters); - + EndProcedure Procedure B24_NotificationsManagment() Export - + TestParameters = New Structure; - OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_URL" , TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Domain", TestParameters); OPI_TestDataRetrieval.ParameterToCollection("Bitrix24_Token" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Picture2" , TestParameters); - OPI_TestDataRetrieval.ParameterToCollection("Document" , TestParameters); - + OPI_TestDataRetrieval.ParameterToCollection("Picture" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Picture2" , TestParameters); + OPI_TestDataRetrieval.ParameterToCollection("Document" , TestParameters); + Bitrix24_CreatePersonalNotification(TestParameters); Bitrix24_CreateSystemNotification(TestParameters); Bitrix24_DeleteNotification(TestParameters); - + EndProcedure #EndRegion @@ -3161,127 +3161,127 @@ EndProcedure #Region Private -Function GetVKParameters() - - Parameters = New Structure; +Function GetVKParameters() + + Parameters = New Structure; GroupNumber = OPI_TestDataRetrieval.GetParameter("VK_GroupID"); - + Parameters.Insert("access_token" , OPI_TestDataRetrieval.GetParameter("VK_Token")); - Parameters.Insert("owner_id" , "-" + GroupNumber); - Parameters.Insert("app_id" , OPI_TestDataRetrieval.GetParameter("VK_AppID")); - Parameters.Insert("group_id" , GroupNumber); - + Parameters.Insert("owner_id" , "-" + GroupNumber); + Parameters.Insert("app_id" , OPI_TestDataRetrieval.GetParameter("VK_AppID")); + Parameters.Insert("group_id" , GroupNumber); + Return Parameters; - + EndFunction -Function GetTwitterParameters() - +Function GetTwitterParameters() + Parameters = New Map; - - Parameters.Insert("redirect_uri" , OPI_TestDataRetrieval.GetParameter("Twitter_Redirect")); - Parameters.Insert("client_id" , OPI_TestDataRetrieval.GetParameter("Twitter_ClinetID")); - Parameters.Insert("client_secret" , OPI_TestDataRetrieval.GetParameter("Twitter_ClientSecret")); - Parameters.Insert("access_token" , OPI_TestDataRetrieval.GetParameter("Twitter_Token")); - Parameters.Insert("refresh_token" , OPI_TestDataRetrieval.GetParameter("Twitter_Refresh")); - Parameters.Insert("oauth_token" , OPI_TestDataRetrieval.GetParameter("Twitter_OAuthToken")); + + Parameters.Insert("redirect_uri" , OPI_TestDataRetrieval.GetParameter("Twitter_Redirect")); + Parameters.Insert("client_id" , OPI_TestDataRetrieval.GetParameter("Twitter_ClinetID")); + Parameters.Insert("client_secret" , OPI_TestDataRetrieval.GetParameter("Twitter_ClientSecret")); + Parameters.Insert("access_token" , OPI_TestDataRetrieval.GetParameter("Twitter_Token")); + Parameters.Insert("refresh_token" , OPI_TestDataRetrieval.GetParameter("Twitter_Refresh")); + Parameters.Insert("oauth_token" , OPI_TestDataRetrieval.GetParameter("Twitter_OAuthToken")); Parameters.Insert("oauth_token_secret" , OPI_TestDataRetrieval.GetParameter("Twitter_OAuthSecret")); - - Parameters.Insert("oauth_consumer_key" + + Parameters.Insert("oauth_consumer_key" , OPI_TestDataRetrieval.GetParameter("Twitter_OAuthConsumerKey")); - Parameters.Insert("oauth_consumer_secret" + Parameters.Insert("oauth_consumer_secret" , OPI_TestDataRetrieval.GetParameter("Twitter_OAuthConsumerSecret")); Return Parameters; - + EndFunction #Region Checks -Procedure Check_Empty(Val Result) +Procedure Check_Empty(Val Result) OPI_TestDataRetrieval.ExpectsThat(ValueIsFilled(Result)).Равно(False); EndProcedure -Procedure Check_String(Val Result) - OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("String"); +Procedure Check_String(Val Result) + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("String"); EndProcedure Procedure Check_BinaryData(Val Result, Val Size = Undefined) - + MinimumSize = 500000; - - OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("BinaryData"); - + + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("BinaryData"); + If Not Size = Undefined Then - OPI_TestDataRetrieval.ExpectsThat(Result.Size() >= Size).Равно(True); + OPI_TestDataRetrieval.ExpectsThat(Result.Size() >= Size).Равно(True); Else OPI_TestDataRetrieval.ExpectsThat(Result.Size() > MinimumSize).Равно(True); EndIf; - + EndProcedure Procedure Check_Array(Val Result, Val Count = Undefined) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Array"); - + If Not Count = Undefined Then - OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетДлину(Count); - EndIf; - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетДлину(Count); + EndIf; + EndProcedure Procedure Check_Map(Val Result) - OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); + EndProcedure Procedure Check_Structure(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Structure").Заполнено(); - + EndProcedure Procedure Check_TelegramTrue(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]).Равно(True); - + EndProcedure Procedure Check_TelegramBotInformation(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["username"]).Заполнено(); - + EndProcedure Procedure Check_TelegramArray(Result) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map") .Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Array"); - + EndProcedure Procedure Check_TelegramWebhookSetup(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["description"]).Равно("Webhook was set"); - + EndProcedure Procedure Check_TelegramWebhookDeletion(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["description"]).Заполнено(); - + EndProcedure Procedure Check_TelegramMessage(Val Result, Val Text) @@ -3289,16 +3289,16 @@ Procedure Check_TelegramMessage(Val Result, Val Text) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["text"]).Равно(Text); - + EndProcedure Procedure Check_TelegramImage(Val Result, Val Text) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map") .Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["caption"]).Равно(Text); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["photo"]).ИмеетТип("Array"); - + EndProcedure Procedure Check_TelegramVideo(Val Result, Val Text) @@ -3307,7 +3307,7 @@ Procedure Check_TelegramVideo(Val Result, Val Text) OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["caption"]).Равно(Text); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["video"]["mime_type"]).Равно("video/mp4"); - + EndProcedure Procedure Check_TelegramAudio(Val Result, Val Text) @@ -3316,7 +3316,7 @@ Procedure Check_TelegramAudio(Val Result, Val Text) OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["caption"]).Равно(Text); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["audio"]["mime_type"]).Равно("audio/mpeg"); - + EndProcedure Procedure Check_TelegramDocument(Val Result, Val Text) @@ -3324,20 +3324,20 @@ Procedure Check_TelegramDocument(Val Result, Val Text) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["caption"]).Равно(Text); - OPI_TestDataRetrieval.ExpectsThat(Result["result"]["document"]).ИмеетТип("Map").Заполнено(); - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]["document"]).ИмеетТип("Map").Заполнено(); + EndProcedure Procedure Check_TelegramGif(Val Result, Val Text) Result_ = "result"; - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result[Result_]["caption"]).Равно(Text); OPI_TestDataRetrieval.ExpectsThat(Result[Result_]["document"]).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result[Result_]["animation"]["mime_type"]).Равно("video/mp4"); - + EndProcedure Procedure Check_TelegramMediaGroup(Val Result) @@ -3345,15 +3345,15 @@ Procedure Check_TelegramMediaGroup(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Array"); - + EndProcedure Procedure Check_TelegramLocation(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); - OPI_TestDataRetrieval.ExpectsThat(Result["result"]["location"]).ИмеетТип("Map").Заполнено(); - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]["location"]).ИмеетТип("Map").Заполнено(); + EndProcedure Procedure Check_TelegramContact(Val Result, Val Name) @@ -3362,7 +3362,7 @@ Procedure Check_TelegramContact(Val Result, Val Name) OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["contact"]).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["contact"]["first_name"]).Равно(Name); - + EndProcedure Procedure Check_TelegramPoll(Val Result, Val Question) @@ -3371,22 +3371,22 @@ Procedure Check_TelegramPoll(Val Result, Val Question) OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["poll"]).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["poll"]["question"]).Равно(Question); - + EndProcedure Procedure Check_TelegramForward(Val Result, Val MessageID) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["forward_origin"]["message_id"]).Равно(Number(MessageID)); - + EndProcedure Procedure Check_TelegramBan(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["description"]).Равно("Bad Request: can't remove chat owner"); - + EndProcedure Procedure Check_TelegramInvitation(Val Result, Val Title, Val UnixExpiration) @@ -3397,7 +3397,7 @@ Procedure Check_TelegramInvitation(Val Result, Val Title, Val UnixExpiration) OPI_TestDataRetrieval.ExpectsThat(Result[Result_]["member_limit"]).Равно(200); OPI_TestDataRetrieval.ExpectsThat(Result[Result_]["name"]).Равно(Title); OPI_TestDataRetrieval.ExpectsThat(Result[Result_]["expire_date"]).Равно(Number(UnixExpiration)); - + EndProcedure Procedure Check_TelegramNumber(Val Result) @@ -3405,7 +3405,7 @@ Procedure Check_TelegramNumber(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Number"); - + EndProcedure Procedure Check_TelegramCreateTopic(Val Result, Val Name, Icon) @@ -3414,60 +3414,60 @@ Procedure Check_TelegramCreateTopic(Val Result, Val Name, Icon) OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["name"]).Равно(Name); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["icon_custom_emoji_id"]).Равно(Icon); - + EndProcedure Procedure Check_VKPost(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["post_id"]).ИмеетТип("Number").Заполнено(); - + EndProcedure Procedure Check_VKTrue(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["response"]).ИмеетТип("Number").Равно(1); - + EndProcedure Procedure Check_VKAlbum(Val Result, Val Description) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["description"]).Равно(Description); - + EndProcedure Procedure Check_VKAlbumPicture(Val Result, Val ImageDescription, Val AlbumID) Response = "response"; - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result[Response][0]["text"]).Равно(ImageDescription); OPI_TestDataRetrieval.ExpectsThat(Result[Response][0]["album_id"]).Равно(AlbumID); - + EndProcedure Procedure Check_VKStory(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["count"]).ИмеетТип("Number").Равно(1); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["items"]).ИмеетТип("Array").Заполнено(); - + EndProcedure Procedure Check_VKDiscussion(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); - OPI_TestDataRetrieval.ExpectsThat(Result["response"]).ИмеетТип("Number").Заполнено(); - + OPI_TestDataRetrieval.ExpectsThat(Result["response"]).ИмеетТип("Number").Заполнено(); + EndProcedure Procedure Check_VKLike(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["likes"]).ИмеетТип("Number").Заполнено(); - + EndProcedure Procedure Check_VKRepost(Val Result) @@ -3475,37 +3475,37 @@ Procedure Check_VKRepost(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["success"]).ИмеетТип("Number").Равно(1); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["wall_repost_count"]).ИмеетТип("Number").Равно(1); - + EndProcedure Procedure Check_VKComment(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["comment_id"]).ИмеетТип("Number").Заполнено(); - + EndProcedure Procedure Check_VKStatistic(Val Result) - + TypeMap = "Map"; - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип(TypeMap).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["response"][0]["visitors"]).ИмеетТип(TypeMap).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["response"][0]["reach"]).ИмеетТип(TypeMap).Заполнено(); - + EndProcedure Procedure Check_VKPostsStatistic(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Array").ИмеетДлину(2); - + EndProcedure Procedure Check_VKNumber(Val Result) - OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map"); + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["response"]).ИмеетТип("Number").Заполнено(); - + EndProcedure Procedure Check_VKCollection(Val Result) @@ -3513,59 +3513,59 @@ Procedure Check_VKCollection(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["albums_count"]).ИмеетТип("Number").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["market_album_id"]).ИмеетТип("Number").Заполнено(); - + EndProcedure Procedure Check_VKProduct(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["market_item_id"]).ИмеетТип("Number").Заполнено(); - + EndProcedure Procedure Check_VKProp(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["property_id"]).ИмеетТип("Number").Заполнено(); - + EndProcedure Procedure Check_VKPropVariant(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["variant_id"]).ИмеетТип("Number").Заполнено(); - + EndProcedure Procedure Check_VKProductData(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["items"]).ИмеетТип("Array").ИмеетДлину(2); - + EndProcedure Procedure Check_VKProductsGroup(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["response"]["item_group_id"]).ИмеетТип("Number").Заполнено(); - + EndProcedure Procedure Check_VKVideo(Val Result) OPI_TestDataRetrieval.ExpectsThat(Result["video_id"]).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["video_hash"]).Заполнено(); - + EndProcedure Procedure Check_YaDiskDrive(Val Result) Map_ = "Map"; - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип(Map_).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["system_folders"]).ИмеетТип(Map_); OPI_TestDataRetrieval.ExpectsThat(Result["user"]).ИмеетТип(Map_); - + EndProcedure Procedure Check_YaDiskFolder(Val Result, Val Path) @@ -3573,69 +3573,69 @@ Procedure Check_YaDiskFolder(Val Result, Val Path) OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["type"]).Равно("dir"); OPI_TestDataRetrieval.ExpectsThat(Result["path"]).Равно("disk:" + Path); - + EndProcedure Procedure Check_GKObject(Val Result, Val Name, Val Description) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["summary"]).Равно(Name); OPI_TestDataRetrieval.ExpectsThat(Result["description"]).Равно(Description); OPI_TestDataRetrieval.ExpectsThat(Result["id"]).ИмеетТип("String").Заполнено(); - + EndProcedure Procedure Check_TwitterText(Val Result, Val Text) - + ReplyText = Result["data"]["text"]; ReplyText = Left(ReplyText, StrLen(Text)); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(ReplyText).Равно(Text); EndProcedure Procedure Check_ViberOk(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["status_message"]).Равно("ok"); OPI_TestDataRetrieval.ExpectsThat(Result["status"]).Равно(0); EndProcedure Procedure Check_NotionObject(Val Result, Val View = "page") - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["object"]).Равно(View); - + EndProcedure Procedure Check_SlackOk(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["ok"]).Равно(True); EndProcedure Procedure Check_DropboxFile(Val Result, Val Path) - + OPI_TestDataRetrieval.ExpectsThat(Result["path_display"]).Равно(Path); - + EndProcedure Procedure Check_DropboxMetadata(Val Result, Val Path) - + OPI_TestDataRetrieval.ExpectsThat(Result["metadata"]["path_display"]).Равно(Path); - + EndProcedure Procedure Check_DropboxArray(Val Result, Val Count = Undefined) - + OPI_TestDataRetrieval.ExpectsThat(Result["entries"]).ИмеетТип("Array"); - + If Not Count = Undefined Then OPI_TestDataRetrieval.ExpectsThat(Result["entries"].Count()).Равно(Count); EndIf; - + EndProcedure Procedure Check_DropboxWork(Val Result) @@ -3647,10 +3647,10 @@ Procedure Check_DropboxStatus(Val Result) EndProcedure Procedure Check_DropboxTags(Val Result, Val Count) - + OPI_TestDataRetrieval.ExpectsThat(Result["paths_to_tags"]).ИмеетТип("Array"); OPI_TestDataRetrieval.ExpectsThat(Result["paths_to_tags"].Count()).Равно(Count); - + EndProcedure Procedure Check_DropboxAccount(Val Result) @@ -3673,38 +3673,38 @@ Procedure Check_DropboxPublicFolder(Val Result) EndProcedure Procedure Check_BitrixTime(Val Result) - + Time = Result["result"]; - + If Not TypeOf(Time) = Type("Date") Then - Time = XMLValue(Type("Date"), Time); + Time = XMLValue(Type("Date"), Time); EndIf; - + OPI_TestDataRetrieval.ExpectsThat(Time).ИмеетТип("Date").Заполнено(); - + EndProcedure Procedure Check_BitrixAuth(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["access_token"]).Заполнено(); OPI_TestDataRetrieval.ExpectsThat(Result["refresh_token"]).Заполнено(); EndProcedure Procedure Check_BitrixNumber(Val Result) - OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Number").Заполнено(); + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Number").Заполнено(); EndProcedure Procedure Check_BitrixTrue(Val Result) - OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Boolean").Равно(True); -EndProcedure + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Boolean").Равно(True); +EndProcedure Procedure Check_BitrixBool(Val Result) - OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Boolean"); + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Boolean"); EndProcedure Procedure Check_BitrixString(Val Result) - OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("String").Заполнено(); + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("String").Заполнено(); EndProcedure Procedure Check_BitrixArray(Val Result) @@ -3720,22 +3720,22 @@ Procedure Check_BitrixList(Val Result) EndProcedure Procedure Check_BitrixObjectsArray(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Array"); OPI_TestDataRetrieval.ExpectsThat(Result["result"][0]["ID"]).Заполнено(); - + EndProcedure Procedure Check_BitrixFields(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]["fields"]).Заполнено(); - + EndProcedure Procedure Check_BitrixTask(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]["task"]).Заполнено(); - + EndProcedure Procedure Check_BitrixTasksList(Val Result) @@ -3758,75 +3758,75 @@ Procedure Check_BitrixAttachment(Val Result) EndProcedure Procedure Check_BitrixAvailableActions(Val Result, Val Count) - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Map"); - + Actions = Result["result"]["allowedActions"]; OPI_TestDataRetrieval.ExpectsThat(Actions).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Actions.Count()).Равно(Count); - + EndProcedure Procedure Check_BitrixComment(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["POST_MESSAGE"]).Заполнено(); - + EndProcedure Procedure Check_BitrixResult(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["text"]).Заполнено(); EndProcedure Procedure Check_BitrixUndefined(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Undefined"); OPI_TestDataRetrieval.ExpectsThat(Result["time"]).Заполнено(); EndProcedure Procedure Check_BitrixCommentsList(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Array"); OPI_TestDataRetrieval.ExpectsThat(Result["result"][0]["POST_MESSAGE"]).Заполнено(); - + EndProcedure Procedure Check_BitrixResultsList(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Array"); OPI_TestDataRetrieval.ExpectsThat(Result["result"][0]["text"]).Заполнено(); - + EndProcedure Procedure Check_BitrixMessages(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]["messages"]).ИмеетТип("Array"); - + EndProcedure Procedure Check_BitrixDialog(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["dialogId"]).Заполнено(); - + EndProcedure Procedure Check_BitrixMessage(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["id"]).Заполнено(); - + EndProcedure Procedure Check_BitrixFileMessage(Val Result) - + OPI_TestDataRetrieval.ExpectsThat(Result["result"]).ИмеетТип("Map"); OPI_TestDataRetrieval.ExpectsThat(Result["result"]["MESSAGE_ID"]).Заполнено(); - + EndProcedure #EndRegion @@ -3837,825 +3837,825 @@ EndProcedure Procedure Telegram_GetBotInformation(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; + Token = FunctionParameters["Telegram_Token"]; Result = OPI_Telegram.GetBotInformation(Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetBotInfo", "Telegram"); - + Check_TelegramBotInformation(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_GetUpdates(FunctionParameters) - - Token = FunctionParameters["Telegram_Token"]; + + Token = FunctionParameters["Telegram_Token"]; Result = OPI_Telegram.GetUpdates(Token); // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetUpdates", "Telegram"); - + Check_TelegramArray(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_SetWebhook(FunctionParameters) - + Token = FunctionParameters["Telegram_Token"]; - URL = FunctionParameters["Telegram_URL"]; - + URL = FunctionParameters["Telegram_URL"]; + Result = OPI_Telegram.SetWebhook(Token, URL); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SetWebhook", "Telegram"); - + Check_TelegramWebhookSetup(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_DeleteWebhook(FunctionParameters) - - Token = FunctionParameters["Telegram_Token"]; + + Token = FunctionParameters["Telegram_Token"]; Result = OPI_Telegram.DeleteWebhook(Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteWebhook", "Telegram"); - + Check_TelegramWebhookDeletion(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_SendTextMessage(FunctionParameters) - - Token = FunctionParameters["Telegram_Token"]; - ChatID = FunctionParameters["Telegram_ChatID"]; - ChannelID = FunctionParameters["Telegram_ChannelID"]; - Text = FunctionParameters["String"]; - + + Token = FunctionParameters["Telegram_Token"]; + ChatID = FunctionParameters["Telegram_ChatID"]; + ChannelID = FunctionParameters["Telegram_ChannelID"]; + Text = FunctionParameters["String"]; + Result = OPI_Telegram.SendTextMessage(Token, ChatID, Text); - - // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendTextMessage", "Telegram"); - + + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendTextMessage", "Telegram"); + Check_TelegramMessage(Result, Text); // SKIP - + Result = OPI_Telegram.SendTextMessage(Token, ChannelID, Text); - + // END - - // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendTextMessage (channel)"); - + + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendTextMessage (channel)"); + Check_TelegramMessage(Result, Text); - + MessageID = OPI_Tools.NumberToString(Result["result"]["message_id"]); OPI_TestDataRetrieval.WriteParameter("Telegram_ChannelMessageID", MessageID); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_SendPicture(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - ChatID = FunctionParameters["Telegram_ChatID"]; + Token = FunctionParameters["Telegram_Token"]; + ChatID = FunctionParameters["Telegram_ChatID"]; ChannelID = FunctionParameters["Telegram_ChannelID"]; - Text = FunctionParameters["String"]; - Image = FunctionParameters["Picture"]; - + Text = FunctionParameters["String"]; + Image = FunctionParameters["Picture"]; + ImagePath = GetTempFileName("png"); FileCopy(Image, ImagePath); - + ImageDD = New BinaryData(ImagePath); - + Result = OPI_Telegram.SendImage(Token, ChatID, Text, Image); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendImage", "Telegram"); - + Check_TelegramImage(Result, Text); // SKIP - + Result = OPI_Telegram.SendImage(Token, ChannelID, Text, ImagePath); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendImage (Path)"); - + Check_TelegramImage(Result, Text); // SKIP - + Result = OPI_Telegram.SendImage(Token, ChannelID, Text, ImageDD); - - // END - + + // END + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendImage (DD)"); - + Check_TelegramImage(Result, Text); - + DeleteFiles(ImagePath); - + FileID = Result["result"]["photo"][0]["file_id"]; OPI_TestDataRetrieval.WriteParameter("Telegram_FileID", FileID); - + FunctionParameters.Insert("Telegram_FileID", FileID); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_SendVideo(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - ChatID = FunctionParameters["Telegram_ChatID"]; + Token = FunctionParameters["Telegram_Token"]; + ChatID = FunctionParameters["Telegram_ChatID"]; ChannelID = FunctionParameters["Telegram_ChannelID"]; - Text = FunctionParameters["String"]; - Video = FunctionParameters["Video"]; - + Text = FunctionParameters["String"]; + Video = FunctionParameters["Video"]; + VideoPath = GetTempFileName("mp4"); FileCopy(Video, VideoPath); - + VideoDD = New BinaryData(VideoPath); - + Result = OPI_Telegram.SendVideo(Token, ChatID, Text, Video); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendVideo", "Telegram"); - + Check_TelegramVideo(Result, Text); // SKIP - + Result = OPI_Telegram.SendVideo(Token, ChannelID, Text, VideoPath); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendVideo (Path)"); - + Check_TelegramVideo(Result, Text); // SKIP - + Result = OPI_Telegram.SendVideo(Token, ChannelID, Text, VideoDD); - - // END - + + // END + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendVideo (DD)"); - + Check_TelegramVideo(Result, Text); - + DeleteFiles(VideoPath); - + FileID = Result["result"]["video"]["file_id"]; OPI_TestDataRetrieval.WriteParameter("Telegram_FileID", FileID); - + FunctionParameters.Insert("Telegram_FileID", FileID); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_SendAudio(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - ChatID = FunctionParameters["Telegram_ChatID"]; + Token = FunctionParameters["Telegram_Token"]; + ChatID = FunctionParameters["Telegram_ChatID"]; ChannelID = FunctionParameters["Telegram_ChannelID"]; - Text = FunctionParameters["String"]; - Audio = FunctionParameters["Audio"]; - + Text = FunctionParameters["String"]; + Audio = FunctionParameters["Audio"]; + AudioPath = GetTempFileName("mp3"); FileCopy(Audio, AudioPath); - + AudioDD = New BinaryData(AudioPath); - + Result = OPI_Telegram.SendAudio(Token, ChatID, Text, Audio); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendAudio", "Telegram"); - + Check_TelegramAudio(Result, Text); // SKIP - + Result = OPI_Telegram.SendAudio(Token, ChannelID, Text, AudioPath); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendAudio (Path)"); - + Check_TelegramAudio(Result, Text); // SKIP - + Result = OPI_Telegram.SendAudio(Token, ChannelID, Text, AudioDD); - - // END - + + // END + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendAudio (DD)"); - + Check_TelegramAudio(Result, Text); - + DeleteFiles(AudioPath); - + FileID = Result["result"]["audio"]["file_id"]; OPI_TestDataRetrieval.WriteParameter("Telegram_FileID", FileID); - + FunctionParameters.Insert("Telegram_FileID", FileID); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_SendDocument(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - ChatID = FunctionParameters["Telegram_ChatID"]; + Token = FunctionParameters["Telegram_Token"]; + ChatID = FunctionParameters["Telegram_ChatID"]; ChannelID = FunctionParameters["Telegram_ChannelID"]; - Text = FunctionParameters["String"]; - Document = FunctionParameters["Document"]; - + Text = FunctionParameters["String"]; + Document = FunctionParameters["Document"]; + DocumentPath = GetTempFileName("docx"); FileCopy(Document, DocumentPath); - + DocumentDD = New BinaryData(DocumentPath); - + Result = OPI_Telegram.SendDocument(Token, ChatID, Text, Document); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendDocument", "Telegram"); - + Check_TelegramDocument(Result, Text); // SKIP - + Result = OPI_Telegram.SendDocument(Token, ChatID, Text, Document, , , "customname.docx"); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendDocument (with name)", "Telegram"); - + Check_TelegramDocument(Result, Text); // SKIP - + Result = OPI_Telegram.SendDocument(Token, ChannelID, Text, DocumentPath); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendDocument (Path)"); - + Check_TelegramDocument(Result, Text); // SKIP - + Result = OPI_Telegram.SendDocument(Token, ChannelID, Text, DocumentDD, , , "customname.docx"); - - // END - + + // END + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendDocument (DD)"); - + Check_TelegramDocument(Result, Text); - + DeleteFiles(DocumentPath); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_SendGif(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - ChatID = FunctionParameters["Telegram_ChatID"]; + Token = FunctionParameters["Telegram_Token"]; + ChatID = FunctionParameters["Telegram_ChatID"]; ChannelID = FunctionParameters["Telegram_ChannelID"]; - Text = FunctionParameters["String"]; - GIF = FunctionParameters["GIF"]; - + Text = FunctionParameters["String"]; + GIF = FunctionParameters["GIF"]; + GifPath = GetTempFileName("gif"); FileCopy(GIF, GifPath); - + GifDD = New BinaryData(GifPath); - + Result = OPI_Telegram.SendGif(Token, ChatID, Text, GIF); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendGif", "Telegram"); - + Check_TelegramGif(Result, Text); // SKIP - + Result = OPI_Telegram.SendGif(Token, ChannelID, Text, GifPath); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendGif (Path)"); - + Check_TelegramGif(Result, Text); // SKIP - + Result = OPI_Telegram.SendGif(Token, ChannelID, Text, GifDD); - - // END - + + // END + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendGif (DD)"); - + Check_TelegramGif(Result, Text); - + DeleteFiles(GifPath); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_SendMediaGroup(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; + Token = FunctionParameters["Telegram_Token"]; ChatID = FunctionParameters["Telegram_ChatID"]; - Text = FunctionParameters["String"]; - Image = FunctionParameters["Picture"]; - Video = FunctionParameters["Video"]; - + Text = FunctionParameters["String"]; + Image = FunctionParameters["Picture"]; + Video = FunctionParameters["Video"]; + ImagePath = GetTempFileName("png"); FileCopy(Image, ImagePath); - + VideoPath = GetTempFileName("mp4"); FileCopy(Video, VideoPath); - + VideoDD = New BinaryData(VideoPath); - + MediaGroup = New Map; MediaGroup.Insert(ImagePath, "photo"); - MediaGroup.Insert(VideoDD , "video"); - + MediaGroup.Insert(VideoDD , "video"); + Result = OPI_Telegram.SendMediaGroup(Token, ChatID, Text, MediaGroup); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendMediaGroup", "Telegram"); - + Check_TelegramMediaGroup(Result); - - DocumentURL = FunctionParameters["Document"]; + + DocumentURL = FunctionParameters["Document"]; DocumentPath = GetTempFileName("docx"); - ChannelID = FunctionParameters["Telegram_ChannelID"]; - + ChannelID = FunctionParameters["Telegram_ChannelID"]; + FileCopy(DocumentURL, DocumentPath); - + MediaGroup = New Map; MediaGroup.Insert(DocumentURL , "document"); - MediaGroup.Insert(DocumentPath, "document"); - + MediaGroup.Insert(DocumentPath, "document"); + Result = OPI_Telegram.SendMediaGroup(Token, ChannelID, Text, MediaGroup); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendMediaGroup (docs)", "Telegram"); - + Check_TelegramMediaGroup(Result); - + DeleteFiles(VideoPath); DeleteFiles(ImagePath); DeleteFiles(DocumentPath); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_SendLocation(FunctionParameters) - - Token = FunctionParameters["Telegram_Token"]; - ChatID = FunctionParameters["Telegram_ChatID"]; - ChannelID = FunctionParameters["Telegram_ChannelID"]; - Width = FunctionParameters["Lat"]; + + Token = FunctionParameters["Telegram_Token"]; + ChatID = FunctionParameters["Telegram_ChatID"]; + ChannelID = FunctionParameters["Telegram_ChannelID"]; + Width = FunctionParameters["Lat"]; Longitude = FunctionParameters["Long"]; - + Result = OPI_Telegram.SendLocation(Token, ChatID, Width, Longitude); - - // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendLocation", "Telegram"); - + + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendLocation", "Telegram"); + Check_TelegramLocation(Result); // SKIP - + Result = OPI_Telegram.SendLocation(Token, ChannelID, Width, Longitude); - + // END - - // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendLocation (channel)"); - + + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendLocation (channel)"); + Check_TelegramLocation(Result); OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_SendContact(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - ChatID = FunctionParameters["Telegram_ChatID"]; - ChannelID = FunctionParameters["Telegram_ChannelID"]; - Name = FunctionParameters["Name"]; - LastName = FunctionParameters["Surname"]; - Phone = FunctionParameters["Phone"]; - + Token = FunctionParameters["Telegram_Token"]; + ChatID = FunctionParameters["Telegram_ChatID"]; + ChannelID = FunctionParameters["Telegram_ChannelID"]; + Name = FunctionParameters["Name"]; + LastName = FunctionParameters["Surname"]; + Phone = FunctionParameters["Phone"]; + Result = OPI_Telegram.SendContact(Token, ChatID , Name, LastName, Phone); - - // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendContact", "Telegram"); - + + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendContact", "Telegram"); + Check_TelegramContact(Result, Name); // SKIP OPI_Tools.Pause(20); // SKIP - + Result = OPI_Telegram.SendContact(Token, ChannelID, Name, LastName, Phone); - + // END - - // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendContact (channel)"); - + + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendContact (channel)"); + Check_TelegramContact(Result, Name); OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_SendPoll(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - ChatID = FunctionParameters["Telegram_ChatID"]; - ChannelID = FunctionParameters["Telegram_ChannelID"]; - Question = "What's your favorite color?"; - + Token = FunctionParameters["Telegram_Token"]; + ChatID = FunctionParameters["Telegram_ChatID"]; + ChannelID = FunctionParameters["Telegram_ChannelID"]; + Question = "What's your favorite color?"; + AnswersArray = New Array; AnswersArray.Add("Red"); AnswersArray.Add("Yellow"); AnswersArray.Add("Green"); AnswersArray.Add("Blue"); - + Result = OPI_Telegram.SendPoll(Token, ChatID , Question, AnswersArray, False); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendSurvey", "Telegram"); - + Check_TelegramPoll(Result, Question); // SKIP - + Result = OPI_Telegram.SendPoll(Token, ChannelID, Question, AnswersArray, True); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendPoll (channel)"); - + Check_TelegramPoll(Result, Question); // SKIP - + // END - + StringArray = "['Red', 'Yellow', 'Green', 'Blue']"; - + Result = OPI_Telegram.SendPoll(Token, ChannelID, Question, StringArray, True); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendPoll (string array)"); - + Check_TelegramPoll(Result, Question); OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_DownloadFile(FunctionParameters) - + FileID = FunctionParameters["Telegram_FileID"]; - Token = FunctionParameters["Telegram_Token"]; + Token = FunctionParameters["Telegram_Token"]; Result = OPI_Telegram.DownloadFile(Token, FileID); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DownloadFile", "Telegram"); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("BinaryData"); - + EndProcedure Procedure Telegram_ForwardMessage(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - ChatID = FunctionParameters["Telegram_ChatID"]; + Token = FunctionParameters["Telegram_Token"]; + ChatID = FunctionParameters["Telegram_ChatID"]; ChannelID = FunctionParameters["Telegram_ChannelID"]; MessageID = FunctionParameters["Telegram_ChannelMessageID"]; - + Result = OPI_Telegram.ForwardMessage(Token, MessageID, ChannelID, ChatID); - + // END // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ForwardMessage", "Telegram"); - + Check_TelegramForward(Result, MessageID); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_Ban(FunctionParameters) - - Token = FunctionParameters["Telegram_Token"]; - UserID = FunctionParameters["Telegram_ChatID"]; + + Token = FunctionParameters["Telegram_Token"]; + UserID = FunctionParameters["Telegram_ChatID"]; ChannelID = FunctionParameters["Telegram_ChannelID"]; - + Result = OPI_Telegram.Ban(Token, ChannelID, UserID); // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "Ban", "Telegram"); - + Check_TelegramBan(Result); OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_Unban(FunctionParameters) - - Token = FunctionParameters["Telegram_Token"]; - UserID = FunctionParameters["Telegram_ChatID"]; + + Token = FunctionParameters["Telegram_Token"]; + UserID = FunctionParameters["Telegram_ChatID"]; ChannelID = FunctionParameters["Telegram_ChannelID"]; - + Result = OPI_Telegram.Unban(Token, ChannelID, UserID); // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "Unban", "Telegram"); - + Check_TelegramBan(Result); OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_CreateInviteLink(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - ChannelID = FunctionParameters["Telegram_ChannelID"]; - Day = 86400; + Token = FunctionParameters["Telegram_Token"]; + ChannelID = FunctionParameters["Telegram_ChannelID"]; + Day = 86400; CurrentDate = OPI_Tools.GetCurrentDate(); - Title = "Link " + String(CurrentDate); - Expiration = CurrentDate + Day; + Title = "Link " + String(CurrentDate); + Expiration = CurrentDate + Day; UnixExpiration = OPI_Tools.UNIXTime(Expiration); - + Result = OPI_Telegram.CreateInvitationLink(Token, ChannelID, Title, Expiration, 200); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateInvitationLink", "Telegram"); Check_TelegramInvitation(Result, Title, UnixExpiration); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_PinMessage(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; + Token = FunctionParameters["Telegram_Token"]; ChannelID = FunctionParameters["Telegram_ChannelID"]; MessageID = FunctionParameters["Telegram_ChannelMessageID"]; - + Result = OPI_Telegram.PinMessage(Token, ChannelID, MessageID); // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "PinMessage", "Telegram"); - + Check_TelegramTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_UnpinMessage(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; + Token = FunctionParameters["Telegram_Token"]; ChannelID = FunctionParameters["Telegram_ChannelID"]; MessageID = FunctionParameters["Telegram_ChannelMessageID"]; - + Result = OPI_Telegram.UnpinMessage(Token, ChannelID, MessageID); // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DetachMessage", "Telegram"); - + Check_TelegramTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_GetParticipantCount(FunctionParameters) - - Token = FunctionParameters["Telegram_Token"]; + + Token = FunctionParameters["Telegram_Token"]; ChannelID = FunctionParameters["Telegram_ChannelID"]; - + Result = OPI_Telegram.GetParticipantCount(Token, ChannelID); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetMemberCount", "Telegram"); - + Check_TelegramNumber(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_GetForumAvatarList(FunctionParameters) - - Token = FunctionParameters["Telegram_Token"]; + + Token = FunctionParameters["Telegram_Token"]; Result = OPI_Telegram.GetAvatarIconList(Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetAvatarIconList", "Telegram"); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("Map").Заполнено(); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_CreateForumTopic(FunctionParameters) - - Token = FunctionParameters["Telegram_Token"]; + + Token = FunctionParameters["Telegram_Token"]; Chat = FunctionParameters["Telegram_ForumID"]; Icon = "5357419403325481346"; Name = "TestTopic " + String(New UUID); - + Result = OPI_Telegram.CreateForumThread(Token, Chat, Name, Icon); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateForumTopic", "Telegram"); - + Topic = Result["result"]["message_thread_id"]; - + FunctionParameters.Insert("Telegram_TopicID", Topic); OPI_Tools.AddField("Telegram_TopicID", Topic, "String", FunctionParameters); OPI_TestDataRetrieval.WriteParameter("Telegram_TopicID", FunctionParameters["Telegram_TopicID"]); - + Check_TelegramCreateTopic(Result, Name, Icon); - + ChatTopic = Chat + "*" + Topic; - Text = FunctionParameters["String"]; + Text = FunctionParameters["String"]; Result = OPI_Telegram.SendTextMessage(Token, ChatTopic, Text); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendTextMessage (forum)"); - + Check_TelegramMessage(Result, Text); - + EndProcedure Procedure Telegram_EditForumTopic(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - Chat = FunctionParameters["Telegram_ForumID"]; - Topic = FunctionParameters["Telegram_TopicID"]; + Token = FunctionParameters["Telegram_Token"]; + Chat = FunctionParameters["Telegram_ForumID"]; + Topic = FunctionParameters["Telegram_TopicID"]; NewName = "NewTestTitle"; NewIcon = "5310132165583840589"; Result = OPI_Telegram.EditForumTopic(Token, Chat, Topic, NewName, NewIcon); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ChangeForumTheme", "Telegram"); - + Check_TelegramTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_CloseForumTopic(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - Chat = FunctionParameters["Telegram_ForumID"]; + Token = FunctionParameters["Telegram_Token"]; + Chat = FunctionParameters["Telegram_ForumID"]; Topic = FunctionParameters["Telegram_TopicID"]; OPI_Telegram.OpenForumThread(Token, Chat); // SKIP - + Result = OPI_Telegram.CloseForumThread(Token, Chat); // Closes main topic - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CloseForumTopic (main)"); - + Check_TelegramTrue(Result); // SKIP - + Result = OPI_Telegram.CloseForumThread(Token, Chat, Topic); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CloseForumTopic", "Telegram"); - + Check_TelegramTrue(Result); - + OPI_Tools.Pause(25); - + EndProcedure Procedure Telegram_OpenForumTopic(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - Chat = FunctionParameters["Telegram_ForumID"]; + Token = FunctionParameters["Telegram_Token"]; + Chat = FunctionParameters["Telegram_ForumID"]; Topic = FunctionParameters["Telegram_TopicID"]; Result = OPI_Telegram.OpenForumThread(Token, Chat); // Opens main topic - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "OpenForumTopic (main)"); - + Check_TelegramTrue(Result); // SKIP - + Result = OPI_Telegram.OpenForumThread(Token, Chat, Topic); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "OpenForumTopic", "Telegram"); - + Check_TelegramTrue(Result); - + OPI_Tools.Pause(25); - + EndProcedure Procedure Telegram_DeleteForumTopic(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - Chat = FunctionParameters["Telegram_ForumID"]; + Token = FunctionParameters["Telegram_Token"]; + Chat = FunctionParameters["Telegram_ForumID"]; Topic = FunctionParameters["Telegram_TopicID"]; - - Result = OPI_Telegram.DeleteForumTopic(Token, Chat, Topic); - + + Result = OPI_Telegram.DeleteForumTopic(Token, Chat, Topic); + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteForumTopic", "Telegram"); - + Check_TelegramTrue(Result); - + OPI_Tools.Pause(25); - + EndProcedure Procedure Telegram_ClearPinnedMessagesList(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; - Chat = FunctionParameters["Telegram_ForumID"]; + Token = FunctionParameters["Telegram_Token"]; + Chat = FunctionParameters["Telegram_ForumID"]; Topic = FunctionParameters["Telegram_TopicID"]; - + Result = OPI_Telegram.ClearThreadPinnedMessagesList(Token, Chat); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ClearMainForumThemePinnedMessages", "Telegram)"); - + Check_TelegramTrue(Result); // SKIP - + Result = OPI_Telegram.ClearThreadPinnedMessagesList(Token, Chat, Topic); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ClearForumThemePinnedMessages", "Telegram"); - + Check_TelegramTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_HideMainForumTopic(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; + Token = FunctionParameters["Telegram_Token"]; Chat = FunctionParameters["Telegram_ForumID"]; - + Result = OPI_Telegram.HideMainForumTopic(Token, Chat); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "HideMainForumTheme", "Telegram"); - + Check_TelegramTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_ShowMainForumTopic(FunctionParameters) - Token = FunctionParameters["Telegram_Token"]; + Token = FunctionParameters["Telegram_Token"]; Chat = FunctionParameters["Telegram_ForumID"]; - + Result = OPI_Telegram.ShowMainForumTopic(Token, Chat); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ShowMainForumTheme", "Telegram"); - + Check_TelegramTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_ChangeMainTopicName(FunctionParameters) - Title = "New main thread name " + String(New UUID); - Token = FunctionParameters["Telegram_Token"]; - Chat = FunctionParameters["Telegram_ForumID"]; - + Title = "New main thread name " + String(New UUID); + Token = FunctionParameters["Telegram_Token"]; + Chat = FunctionParameters["Telegram_ForumID"]; + Result = OPI_Telegram.EditMainForumTopicName(Token, Chat, Title); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ChangeMainForumThemeName", "Telegram"); - + Check_TelegramTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Telegram_DeleteMessage(FunctionParameters) - - Token = FunctionParameters["Telegram_Token"]; - ChatID = FunctionParameters["Telegram_ChannelID"]; + + Token = FunctionParameters["Telegram_Token"]; + ChatID = FunctionParameters["Telegram_ChannelID"]; MessageID = FunctionParameters["Telegram_ChannelMessageID"]; - + Result = OPI_Telegram.DeleteMessage(Token, ChatID, MessageID); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteMessage", "Telegram"); - + Check_TelegramTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure #EndRegion @@ -4665,373 +4665,373 @@ EndProcedure Procedure VK_CreateTokenRetrievalLink(FunctionParameters) Application = FunctionParameters["VK_AppID"]; - Result = OPI_VK.CreateTokenRetrievalLink(Application); - + Result = OPI_VK.CreateTokenRetrievalLink(Application); + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateTokenRequestLink", "VK"); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("String").Заполнено(); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_CreatePost(FunctionParameters) - + Parameters = GetVKParameters(); - Text = "Post from autotest"; - URL = "https://github.com/Bayselonarrend/OpenIntegrations"; - - Image = FunctionParameters["Picture"]; // URL, Path or Binary Data + Text = "Post from autotest"; + URL = "https://github.com/Bayselonarrend/OpenIntegrations"; + + Image = FunctionParameters["Picture"]; // URL, Path or Binary Data Image2 = FunctionParameters["Picture2"]; // URL, Path or Binary Data - - TFN = GetTempFileName("png"); + + TFN = GetTempFileName("png"); FileCopy(Image2, TFN); - + ImageArray = New Array; ImageArray.Add(Image); ImageArray.Add(TFN); - + Result = OPI_VK.CreatePost(Text, ImageArray, True, URL, Parameters); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreatePost", "VK"); Check_VKPost(Result); // SKIP PostID = Result["response"]["post_id"]; // SKIP Result = OPI_VK.DeletePost(PostID, Parameters); // SKIP - + Result = OPI_VK.CreatePost(Text, Image, False , , Parameters); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreatePost (single image)"); - Check_VKPost(Result); - - PostID = Result["response"]["post_id"]; - Result = OPI_VK.DeletePost(PostID, Parameters); - - OPI_Tools.Pause(5); - + Check_VKPost(Result); + + PostID = Result["response"]["post_id"]; + Result = OPI_VK.DeletePost(PostID, Parameters); + + OPI_Tools.Pause(5); + Result = OPI_VK.CreatePost(Text, TFN , True, URL, Parameters); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreatePost (single path)"); - Check_VKPost(Result); - + Check_VKPost(Result); + PostID = Result["response"]["post_id"]; OPI_Tools.AddField("VK_PostID", PostID, "String", FunctionParameters); OPI_TestDataRetrieval.WriteParameter("VK_PostID", FunctionParameters["VK_PostID"]); - + DeleteFiles(TFN); OPI_Tools.Pause(5); - + EndProcedure Procedure VK_DeletePost(FunctionParameters) - + Parameters = GetVKParameters(); - PostID = FunctionParameters["VK_PostID"]; - + PostID = FunctionParameters["VK_PostID"]; + Result = OPI_VK.DeletePost(PostID, Parameters); // END // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeletePost", "VK"); - + Check_VKTrue(Result); - + EndProcedure Procedure VK_CreateCompositePost(FunctionParameters) Parameters = GetVKParameters(); - Text = "Post from autotest"; - URL = "https://github.com/Bayselonarrend/OpenIntegrations"; - + Text = "Post from autotest"; + URL = "https://github.com/Bayselonarrend/OpenIntegrations"; + Image = FunctionParameters["Picture"]; // URL, Path or Binary Data Video = FunctionParameters["Video"]; // URL, Path or Binary Data - - TFN = GetTempFileName("png"); + + TFN = GetTempFileName("png"); FileCopy(Image, TFN); - + ImageUpload = OPI_VK.UploadPhotoToServer(TFN, Parameters)["response"][0]; VideoUpload = OPI_VK.UploadVideoToServer(Video, "NewVideo", , , Parameters); - + ImageOwner = OPI_Tools.NumberToString(ImageUpload["owner_id"]); VideoOwner = OPI_Tools.NumberToString(VideoUpload["owner_id"]); - + ImageID = OPI_Tools.NumberToString(ImageUpload["id"]); VideoID = OPI_Tools.NumberToString(VideoUpload["video_id"]); - + AttachmentsArray = New Array; AttachmentsArray.Add("photo" + ImageOwner + "_" + ImageID); AttachmentsArray.Add("video" + VideoOwner + "_" + VideoID); - + Result = OPI_VK.CreateCompositePost(Text, AttachmentsArray, False, URL, Parameters); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateCompositePost", "VK"); - + Check_VKPost(Result); - DeleteFiles(TFN); - + DeleteFiles(TFN); + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_CreatePoll() Parameters = GetVKParameters(); - Question = "What's your favorite color?"; - + Question = "What's your favorite color?"; + OptionArray = New Array; OptionArray.Add("Red"); OptionArray.Add("Yellow"); OptionArray.Add("Green"); - + Result = OPI_VK.CreatePoll(Question, OptionArray, , Parameters); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreatePoll", "VK"); - + Check_VKPost(Result); - + PostID = Result["response"]["post_id"]; OPI_VK.DeletePost(PostID, Parameters); - + OPI_Tools.Pause(10); - + EndProcedure Procedure VK_CreateAlbum(FunctionParameters) - - Parameters = GetVKParameters(); - Name = "AlbumFromAutoTest"; + + Parameters = GetVKParameters(); + Name = "AlbumFromAutoTest"; Description = "NewAlbumFromAutoTest"; - + Result = OPI_VK.CreateAlbum(Name, Description, Parameters); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateAlbum", "VK"); - + Check_VKAlbum(Result, Description); - + AlbumID = Result["response"]["id"]; FunctionParameters.Insert("VK_AlbumID", AlbumID); OPI_TestDataRetrieval.WriteParameter("VK_AlbumID", AlbumID); - + EndProcedure Procedure VK_SavePictureToAlbum(FunctionParameters) - - Parameters = GetVKParameters(); + + Parameters = GetVKParameters(); ImageDescription = "AutoTestImage"; - AlbumID = FunctionParameters["VK_AlbumID"]; - + AlbumID = FunctionParameters["VK_AlbumID"]; + Image = FunctionParameters["Picture"]; // URL, Path to file or Binary Data - TFN = GetTempFileName("png"); + TFN = GetTempFileName("png"); FileCopy(Image, TFN); - + Image = New BinaryData(TFN); - + Result = OPI_VK.SaveImageToAlbum(AlbumID, Image, ImageDescription, Parameters); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SaveImageToAlbum", "VK"); - + Check_VKAlbumPicture(Result, ImageDescription, AlbumID); // SKIP - + ImageID = Result["response"][0]["id"]; // SKIP - Result = OPI_VK.DeleteImage(ImageID, Parameters); // SKIP - + Result = OPI_VK.DeleteImage(ImageID, Parameters); // SKIP + Result = OPI_VK.SaveImageToAlbum(AlbumID, TFN, ImageDescription, Parameters); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SaveImageToAlbum (path)"); - + Check_VKAlbumPicture(Result, ImageDescription, AlbumID); // SKIP - + ImageID = Result["response"][0]["id"]; FunctionParameters.Insert("VK_PictureID", ImageID); OPI_TestDataRetrieval.WriteParameter("VK_PictureID", ImageID); - + DeleteFiles(TFN); OPI_Tools.Pause(5); - + EndProcedure Procedure VK_DeleteImage(FunctionParameters) - + Parameters = GetVKParameters(); - ImageID = FunctionParameters["VK_PictureID"]; - + ImageID = FunctionParameters["VK_PictureID"]; + Result = OPI_VK.DeleteImage(ImageID, Parameters); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteImage", "VK"); - + Check_VKTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_DeleteAlbum(FunctionParameters) - + Parameters = GetVKParameters(); - AlbumID = FunctionParameters["VK_AlbumID"]; - + AlbumID = FunctionParameters["VK_AlbumID"]; + Result = OPI_VK.DeleteAlbum(AlbumID, Parameters); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteAlbum", "VK"); - + Check_VKTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_CreateStory(FunctionParameters) Parameters = GetVKParameters(); - URL = "https://github.com/Bayselonarrend/OpenIntegrations"; + URL = "https://github.com/Bayselonarrend/OpenIntegrations"; Image = FunctionParameters["Picture"]; // URL, Path to file or Binary Data - TFN = GetTempFileName("png"); + TFN = GetTempFileName("png"); FileCopy(Image, TFN); Image = New BinaryData(TFN); - + Result = OPI_VK.CreateStory(Image , URL, Parameters); // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateStory", "VK"); - + Check_VKStory(Result); // SKIP - + Result = OPI_VK.CreateStory(TFN, , Parameters); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateStory (path)"); - + Check_VKStory(Result); - + DeleteFiles(TFN); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_CreateDiscussion(FunctionParameters) Parameters = GetVKParameters(); - Name = "Discussing: Which color is better?"; - Message = "Red, yellow, blue, or some other?"; - + Name = "Discussing: Which color is better?"; + Message = "Red, yellow, blue, or some other?"; + Result = OPI_VK.CreateDiscussion(Name, Message, Parameters); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateDiscussion", "VK"); - + Check_VKDiscussion(Result); - + DiscussionID = Result["response"]; FunctionParameters.Insert("VK_ConvID", DiscussionID); - OPI_TestDataRetrieval.WriteParameter("VK_ConvID", DiscussionID); - + OPI_TestDataRetrieval.WriteParameter("VK_ConvID", DiscussionID); + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_CloseDiscussion(FunctionParameters) - - Parameters = GetVKParameters(); + + Parameters = GetVKParameters(); DiscussionID = FunctionParameters["VK_ConvID"]; - Result = OPI_VK.CloseDiscussion(DiscussionID, False, Parameters); - + Result = OPI_VK.CloseDiscussion(DiscussionID, False, Parameters); + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CloseDiscussion", "VK"); - + Check_VKTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_OpenDiscussion(FunctionParameters) - - Parameters = GetVKParameters(); + + Parameters = GetVKParameters(); DiscussionID = FunctionParameters["VK_ConvID"]; - Result = OPI_VK.OpenDiscussion(DiscussionID, Parameters); - + Result = OPI_VK.OpenDiscussion(DiscussionID, Parameters); + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "OpenDiscussion", "VK"); - + Check_VKTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_PostToDiscussion(FunctionParameters) - - Parameters = GetVKParameters(); + + Parameters = GetVKParameters(); DiscussionID = FunctionParameters["VK_ConvID"]; - Message = "I like yellow more"; - + Message = "I like yellow more"; + Result = OPI_VK.WriteInDiscussion(DiscussionID, Message, Parameters); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "PostInDiscussion", "VK"); - + Check_VKDiscussion(Result); - + EndProcedure Procedure VK_LikePost(FunctionParameters) Parameters = GetVKParameters(); - PostID = FunctionParameters["VK_PostID"]; - + PostID = FunctionParameters["VK_PostID"]; + Result = OPI_VK.LikePost(PostID, , Parameters); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "Like", "VK"); - + Check_VKLike(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_MakeRepost(FunctionParameters) - + Parameters = GetVKParameters(); - PostID = 2571; - WallID = -218704372; - + PostID = 2571; + WallID = -218704372; + Result = OPI_VK.MakeRepost(PostID, WallID, , , Parameters); // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "MakeRepost", "VK"); - + Check_VKRepost(Result); - + FunctionParameters.Insert("Repost", Result["response"]["post_id"]); - + OPI_Tools.Pause(5); EndProcedure @@ -5039,81 +5039,81 @@ EndProcedure Procedure VK_WriteComment(FunctionParameters) Parameters = GetVKParameters(); - Text = "NewComment"; - PostID = FunctionParameters["VK_PostID"]; - WallID = Parameters["owner_id"]; - + Text = "NewComment"; + PostID = FunctionParameters["VK_PostID"]; + WallID = Parameters["owner_id"]; + Result = OPI_VK.WriteComment(PostID, WallID, Text, Parameters); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "WriteComment", "VK"); - + Check_VKComment(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_GetStatistics(FunctionParameters) Parameters = GetVKParameters(); - + CurrentDate = OPI_Tools.GetCurrentDate(); - StartDate = BegOfDay(CurrentDate); - EndDate = EndOfDay(StartDate); - + StartDate = BegOfDay(CurrentDate); + EndDate = EndOfDay(StartDate); + Result = OPI_VK.GetStatistics(StartDate, EndDate, Parameters); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetStatistics", "VK"); - + Check_VKStatistic(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_GetPostStatistics(FunctionParameters) Parameters = GetVKParameters(); - + ArrayOfPosts = New Array; ArrayOfPosts.Add(214); ArrayOfPosts.Add(215); - + Result = OPI_VK.GetPostStatistics(ArrayOfPosts, Parameters); // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetPostStatistics", "VK"); - + Check_VKPostsStatistic(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_CreateAdCampaign(FunctionParameters) Parameters = GetVKParameters(); - + AccountID = FunctionParameters["VK_AdsCabinetID"]; - Name = "New campaign"; - + Name = "New campaign"; + Result = OPI_VK.CreateAdvertisingCampaign(AccountID, Name, Parameters); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateAdvertisingCampaign", "VK"); - + Check_Map(Result); - + CampaignID = Result["response"][0]["id"]; OPI_TestDataRetrieval.WriteParameter("VK_AdsCampaignID", CampaignID); FunctionParameters.Insert("VK_AdsCampaignID", CampaignID); - + EndProcedure Procedure VK_CreateAd(FunctionParameters) @@ -5121,260 +5121,260 @@ Procedure VK_CreateAd(FunctionParameters) Parameters = GetVKParameters(); CampaignNumber = FunctionParameters["VK_AdsCampaignID"]; - DailyLimit = 150; + DailyLimit = 150; CategoryNumber = 126; - PostID = FunctionParameters["VK_PostID"]; - AccountID = FunctionParameters["VK_AdsCabinetID"]; - + PostID = FunctionParameters["VK_PostID"]; + AccountID = FunctionParameters["VK_AdsCabinetID"]; + Result = OPI_VK.CreateAd(CampaignNumber , DailyLimit , CategoryNumber , PostID , AccountID , Parameters); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateAd", "VK"); - + Check_Map(Result); - + AnnouncementID = Result["response"][0]["id"]; OPI_TestDataRetrieval.WriteParameter("VK_AdsPostID", AnnouncementID); FunctionParameters.Insert("VK_AdsPostID", AnnouncementID); - + EndProcedure Procedure VK_PauseAdvertising(FunctionParameters) Parameters = GetVKParameters(); - + AccountID = FunctionParameters["VK_AdsCabinetID"]; - AdID = FunctionParameters["VK_AdsPostID"]; - + AdID = FunctionParameters["VK_AdsPostID"]; + Result = OPI_VK.PauseAdvertising(AccountID, AdID, Parameters); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "PauseAdvertisement", "VK"); - + Check_Map(Result); - + EndProcedure Procedure VK_FormKeyboard(FunctionParameters) ButtonArray = New Array; ButtonArray.Add("Button 1"); - ButtonArray.Add("Button 2"); - + ButtonArray.Add("Button 2"); + Keyboard = OPI_VK.FormKeyboard(ButtonArray); - + // END - + Check_String(Keyboard); - + EndProcedure Procedure VK_WriteMessage(FunctionParameters) Parameters = GetVKParameters(); - - Text = "Message from autotest"; - UserID = FunctionParameters["VK_UserID"]; + + Text = "Message from autotest"; + UserID = FunctionParameters["VK_UserID"]; Communitytoken = FunctionParameters["VK_CommunityToken"]; - + ButtonArray = New Array; ButtonArray.Add("Button 1"); - ButtonArray.Add("Button 2"); - + ButtonArray.Add("Button 2"); + Keyboard = OPI_VK.FormKeyboard(ButtonArray); - Result = OPI_VK.WriteMessage(Text, UserID, Communitytoken, Keyboard, Parameters); - + Result = OPI_VK.WriteMessage(Text, UserID, Communitytoken, Keyboard, Parameters); + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendMessage", "VK"); - - Check_VKNumber(Result); - + + Check_VKNumber(Result); + EndProcedure Procedure VK_GetProductCategoryList(FunctionParameters) Parameters = GetVKParameters(); - + Result = OPI_VK.GetProductCategoryList(Parameters); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetProductCategoryList", "VK"); - + Check_Map(Result); - + EndProcedure Procedure CreateProductCollection(FunctionParameters) Parameters = GetVKParameters(); - - Name = "TestCollection"; - Image = FunctionParameters["Picture"]; - Main = True; + + Name = "TestCollection"; + Image = FunctionParameters["Picture"]; + Main = True; Hidden = False; - + Result = OPI_VK.CreateProductCollection(Name , Image , Main , Hidden - , Parameters); - + , Parameters); + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateProductCollection", "VK"); - + Check_VKCollection(Result); - + OPI_Tools.Pause(5); - + SelectionID = Result["response"]["market_album_id"]; OPI_TestDataRetrieval.WriteParameter("VK_MarketAlbumID", SelectionID); FunctionParameters.Insert("VK_MarketAlbumID", SelectionID); - + EndProcedure Procedure EditProductCollection(FunctionParameters) Parameters = GetVKParameters(); - - Name = "EditedCollection"; - Selection = FunctionParameters["VK_MarketAlbumID"]; - + + Name = "EditedCollection"; + Selection = FunctionParameters["VK_MarketAlbumID"]; + Result = OPI_VK.EditProductCollection(Name, Selection, , , , Parameters); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "EditProductCollection", "VK"); - + Check_VKTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_AddProduct(FunctionParameters) Parameters = GetVKParameters(); - - Image1 = FunctionParameters["Picture"]; // URL, Path to file or binary Data - Image2 = FunctionParameters["Picture2"]; // URL, Path to file or binary Data - Selection = FunctionParameters["VK_MarketAlbumID"]; - + + Image1 = FunctionParameters["Picture"]; // URL, Path to file or binary Data + Image2 = FunctionParameters["Picture2"]; // URL, Path to file or binary Data + Selection = FunctionParameters["VK_MarketAlbumID"]; + ImageArray = New Array; ImageArray.Add(Image1); ImageArray.Add(Image2); - + ProductDescription = New Map(); - ProductDescription.Insert("Name" , "TestProduct"); - ProductDescription.Insert("Description" , "Product description"); - ProductDescription.Insert("Category" , "20173"); - ProductDescription.Insert("Price" , 1); - ProductDescription.Insert("OldPrice" , 15); - ProductDescription.Insert("MainPhoto" , Image1); - ProductDescription.Insert("URL" , "https://github.com/Bayselonarrend/OpenIntegrations"); - ProductDescription.Insert("AdditionalPhotos" , ImageArray); - ProductDescription.Insert("MainInGroup" , True); - ProductDescription.Insert("Width" , 20); - ProductDescription.Insert("Height" , 30); - ProductDescription.Insert("Depth" , 40); - ProductDescription.Insert("Weight" , 100); - ProductDescription.Insert("SKU" , "12345"); + ProductDescription.Insert("Name" , "TestProduct"); + ProductDescription.Insert("Description" , "Product description"); + ProductDescription.Insert("Category" , "20173"); + ProductDescription.Insert("Price" , 1); + ProductDescription.Insert("OldPrice" , 15); + ProductDescription.Insert("MainPhoto" , Image1); + ProductDescription.Insert("URL" , "https://github.com/Bayselonarrend/OpenIntegrations"); + ProductDescription.Insert("AdditionalPhotos" , ImageArray); + ProductDescription.Insert("MainInGroup" , True); + ProductDescription.Insert("Width" , 20); + ProductDescription.Insert("Height" , 30); + ProductDescription.Insert("Depth" , 40); + ProductDescription.Insert("Weight" , 100); + ProductDescription.Insert("SKU" , "12345"); ProductDescription.Insert("AvailableBalance" , "10"); - - Result = OPI_VK.AddProduct(ProductDescription, Selection, Parameters); - - // END - + + Result = OPI_VK.AddProduct(ProductDescription, Selection, Parameters); + + // END + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "AddProduct", "VK"); - + Check_VKProduct(Result); - + ProductID = Result["response"]["market_item_id"]; OPI_TestDataRetrieval.WriteParameter("VK_MarketItemID", ProductID); FunctionParameters.Insert("VK_MarketItemID", ProductID); - + EndProcedure Procedure VK_EditProduct(FunctionParameters) Parameters = GetVKParameters(); - - Product = FunctionParameters["VK_MarketItemID"]; - + + Product = FunctionParameters["VK_MarketItemID"]; + ProductDescription = New Map; ProductDescription.Insert("Name", "EditedTestProduct"); - + Result = OPI_VK.EditProduct(Product, ProductDescription, , Parameters); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "EditProduct", "VK"); - + Check_VKTrue(Result); - + EndProcedure Procedure VK_AddProductToCollection(FunctionParameters) Parameters = GetVKParameters(); - - Product = FunctionParameters["VK_MarketItemID"]; + + Product = FunctionParameters["VK_MarketItemID"]; Selection = FunctionParameters["VK_MarketAlbumID"]; - + Result = OPI_VK.AddProductToCollection(Product, Selection, Parameters); - - // END - + + // END + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "AddProductToCollection", "VK"); - + Check_VKNumber(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_RemoveProductFromCollection(FunctionParameters) Parameters = GetVKParameters(); - - Product = FunctionParameters["VK_MarketItemID"]; + + Product = FunctionParameters["VK_MarketItemID"]; Selection = FunctionParameters["VK_MarketAlbumID"]; - - Result = OPI_VK.RemoveProductFromSelection(Product, Selection, Parameters); - + + Result = OPI_VK.RemoveProductFromSelection(Product, Selection, Parameters); + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "RemoveProductFromCollection", "VK"); - + Check_VKTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_DeleteProduct(FunctionParameters) Parameters = GetVKParameters(); - + Product = FunctionParameters["VK_MarketItemID"]; - + Result = OPI_VK.DeleteProduct(Product, Parameters); - - // END - + + // END + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteProduct", "VK"); - + Check_VKTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_DeleteCollection(FunctionParameters) @@ -5382,235 +5382,235 @@ Procedure VK_DeleteCollection(FunctionParameters) Parameters = GetVKParameters(); Selection = FunctionParameters["VK_MarketAlbumID"]; - - Result = OPI_VK.DeleteSelection(Selection, Parameters); - + + Result = OPI_VK.DeleteSelection(Selection, Parameters); + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteCollection", "VK"); - + Check_VKTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_CreateProductProperty(FunctionParameters) Parameters = GetVKParameters(); - + Name = "Color"; - + Result = OPI_VK.CreateProductProperty(Name, Parameters); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateProductProperty", "VK"); - + Check_VKProp(Result); - + OPI_Tools.Pause(5); - + Property = Result["response"]["property_id"]; Property = OPI_Tools.NumberToString(Property); - + OPI_TestDataRetrieval.WriteParameter("VK_PropID", Property); FunctionParameters.Insert("VK_PropID", Property); - + EndProcedure Procedure VK_EditProductProperty(FunctionParameters) Parameters = GetVKParameters(); - - Name = "Color (change.)"; + + Name = "Color (change.)"; Property = FunctionParameters["VK_PropID"]; - + Result = OPI_VK.EditProductProperty(Name, Property, Parameters); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "EditProductProperty", "VK"); - + OPI_Tools.Pause(5); - + Check_VKTrue(Result); - + EndProcedure Procedure VK_AddProductPropertyVariant(FunctionParameters) - Counter = 1; // SKIP + Counter = 1; // SKIP Parameters = GetVKParameters(); - - Property = FunctionParameters["VK_PropID"]; + + Property = FunctionParameters["VK_PropID"]; OptionArray = New Array; OptionArray.Add("Yellow"); OptionArray.Add("Blue"); OptionArray.Add("Red"); - + For Each Value In OptionArray Do - + Result = OPI_VK.AddProductPropertyVariant(Value, Property, Parameters); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "AddProductPropertyVariant", "VK"); - - Check_VKPropVariant(Result); // SKIP + + Check_VKPropVariant(Result); // SKIP OPI_Tools.Pause(5); // SKIP - - VariantID = Result["response"]["variant_id"]; // SKIP + + VariantID = Result["response"]["variant_id"]; // SKIP ParameterName = "VK_PropVarID" + String(Counter); // SKIP - + OPI_TestDataRetrieval.WriteParameter(ParameterName, VariantID); // SKIP FunctionParameters.Insert(ParameterName, VariantID); Counter = Counter + 1; // SKIP - - EndDo; - + + EndDo; + // END - + EndProcedure Procedure VK_EditProductPropertyVariant(FunctionParameters) - + Parameters = GetVKParameters(); - + Property = FunctionParameters["VK_PropID"]; - Option = FunctionParameters["VK_PropVarID1"]; - Value = "New variant name"; - + Option = FunctionParameters["VK_PropVarID1"]; + Value = "New variant name"; + Result = OPI_VK.EditProductPropertyVariant(Value , Property , Option , Parameters); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "EditProductPropertyVariant", "VK"); - + Check_VKTrue(Result); - + EndProcedure Procedure VK_CreateProductWithProp(FunctionParameters) Parameters = GetVKParameters(); - - Image1 = FunctionParameters["Picture"]; - Image2 = FunctionParameters["Picture2"]; + + Image1 = FunctionParameters["Picture"]; + Image2 = FunctionParameters["Picture2"]; PropVariant1 = FunctionParameters["VK_PropVarID1"]; PropVariant2 = FunctionParameters["VK_PropVarID2"]; - + ImageArray = New Array; ImageArray.Add(Image1); ImageArray.Add(Image2); - + Product = New Map(); - Product.Insert("Name" , "Test product (with prop)"); - Product.Insert("Description" , "Product description"); - Product.Insert("Category" , "20173"); - Product.Insert("Price" , 1); - Product.Insert("OldPrice" , 15); - Product.Insert("MainPhoto" , Image1); - Product.Insert("URL" , "https://github.com/Bayselonarrend/OpenIntegrations"); - Product.Insert("AdditionalPhotos" , ImageArray); - Product.Insert("MainInGroup" , True); - Product.Insert("GroupNumber" , Undefined); - Product.Insert("Width" , 20); - Product.Insert("Height" , 30); - Product.Insert("Depth" , 40); - Product.Insert("Weight" , 100); - Product.Insert("SKU" , 12345); + Product.Insert("Name" , "Test product (with prop)"); + Product.Insert("Description" , "Product description"); + Product.Insert("Category" , "20173"); + Product.Insert("Price" , 1); + Product.Insert("OldPrice" , 15); + Product.Insert("MainPhoto" , Image1); + Product.Insert("URL" , "https://github.com/Bayselonarrend/OpenIntegrations"); + Product.Insert("AdditionalPhotos" , ImageArray); + Product.Insert("MainInGroup" , True); + Product.Insert("GroupNumber" , Undefined); + Product.Insert("Width" , 20); + Product.Insert("Height" , 30); + Product.Insert("Depth" , 40); + Product.Insert("Weight" , 100); + Product.Insert("SKU" , 12345); Product.Insert("AvailableBalance" , "10"); - Product.Insert("PropertyValues" , PropVariant1); - - Result = OPI_VK.AddProduct(Product, , Parameters); - + Product.Insert("PropertyValues" , PropVariant1); + + Result = OPI_VK.AddProduct(Product, , Parameters); + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ProductWithProp1"); - + Check_VKProduct(Result); - + ProductID = Result["response"]["market_item_id"]; OPI_TestDataRetrieval.WriteParameter("VK_MarketItemID2", ProductID); FunctionParameters.Insert("VK_MarketItemID2", ProductID); - - Product.Insert("Name" , "Test product (another)"); + + Product.Insert("Name" , "Test product (another)"); Product.Insert("PropertyValues", PropVariant2); - Result = OPI_VK.AddProduct(Product, , Parameters); - + Result = OPI_VK.AddProduct(Product, , Parameters); + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ProductWithProp2"); - + Check_VKProduct(Result); - + ProductID = Result["response"]["market_item_id"]; OPI_TestDataRetrieval.WriteParameter("VK_MarketItemID3", ProductID); FunctionParameters.Insert("VK_MarketItemID3", ProductID); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_GetProductsByID(FunctionParameters) Parameters = GetVKParameters(); - + Item1 = FunctionParameters["VK_MarketItemID2"]; Item2 = FunctionParameters["VK_MarketItemID3"]; - + ProductsArray = New Array; ProductsArray.Add(Item1); ProductsArray.Add(Item2); - + Result = OPI_VK.GetProductsByID(ProductsArray, Parameters); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetProductsByID", "VK"); - + Check_VKProductData(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_GroupProducts(FunctionParameters) - + Parameters = GetVKParameters(); - + Item1 = FunctionParameters["VK_MarketItemID2"]; Item2 = FunctionParameters["VK_MarketItemID3"]; - + ProductsArray = New Array; ProductsArray.Add(Item1); ProductsArray.Add(Item2); - + Result = OPI_VK.GroupProducts(ProductsArray, , Parameters); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GroupProducts", "VK"); - + Check_VKProductsGroup(Result); - + OPI_Tools.Pause(5); - + EndProcedure - + Procedure VK_DeleteProductPropertyVariant(FunctionParameters) Parameters = GetVKParameters(); Option = FunctionParameters["VK_PropVarID1"]; - + Result = OPI_VK.DeleteProductPropertyVariant(Option, Parameters); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteProductPropertyVariant", "VK"); - + Check_VKTrue(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure VK_DeleteProductProperty(FunctionParameters) @@ -5618,93 +5618,93 @@ Procedure VK_DeleteProductProperty(FunctionParameters) Parameters = GetVKParameters(); Property = FunctionParameters["VK_PropID"]; - + Result = OPI_VK.DeleteProductProperty(Property, Parameters); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteProductProperty"); - + OPI_Tools.Pause(5); - + Check_VKTrue(Result); - + EndProcedure Procedure VK_GetProductList(FunctionParameters) - Parameters = GetVKParameters(); - Result = OPI_VK.GetProductList(, Parameters); - + Parameters = GetVKParameters(); + Result = OPI_VK.GetProductList(, Parameters); + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetProductList", "VK"); - + Check_Array(Result); OPI_Tools.Pause(5); - + EndProcedure Procedure VK_GetSelectionList(FunctionParameters) - Parameters = GetVKParameters(); - Result = OPI_VK.GetSelectionList(Parameters); - + Parameters = GetVKParameters(); + Result = OPI_VK.GetSelectionList(Parameters); + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetCollectionList", "VK"); - + Check_Array(Result); OPI_Tools.Pause(5); - + EndProcedure Procedure VK_GetPropertyList(FunctionParameters) - Parameters = GetVKParameters(); - Result = OPI_VK.GetPropertyList(Parameters); - + Parameters = GetVKParameters(); + Result = OPI_VK.GetPropertyList(Parameters); + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetPropertyList", "VK"); - + Check_Array(Result); OPI_Tools.Pause(5); - + EndProcedure Procedure VK_GetOrderList(FunctionParameters) Parameters = GetVKParameters(); - Result = OPI_VK.GetOrderList(Parameters); - + Result = OPI_VK.GetOrderList(Parameters); + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetOrderList", "VK"); - + Check_Array(Result); OPI_Tools.Pause(5); - + EndProcedure Procedure VK_UploadVideoToServer(FunctionParameters) - + Parameters = GetVKParameters(); - - Video = FunctionParameters["Video"]; - Name = "NewVideo"; + + Video = FunctionParameters["Video"]; + Name = "NewVideo"; Description = "Video description"; - + Result = OPI_VK.UploadVideoToServer(Video, Name, Description, , Parameters); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UploadVideoToServer", "VK"); - + Check_VKVideo(Result); - + OPI_Tools.Pause(5); - + EndProcedure #EndRegion @@ -5715,554 +5715,554 @@ Procedure Dropbox_GetAuthorizationLink(FunctionParameters) AppKey = FunctionParameters["Dropbox_Appkey"]; Result = OPI_Dropbox.GetAuthorizationLink(AppKey); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetAuthorizationLink", "Dropbox"); - + OPI_TestDataRetrieval.ExpectsThat(Result).ИмеетТип("String"); - + EndProcedure Procedure Dropbox_GetToken(FunctionParameters) - - AppKey = FunctionParameters["Dropbox_Appkey"]; + + AppKey = FunctionParameters["Dropbox_Appkey"]; AppSecret = FunctionParameters["Dropbox_Appsecret"]; - Code = FunctionParameters["Dropbox_Code"]; + Code = FunctionParameters["Dropbox_Code"]; Result = OPI_Dropbox.GetToken(AppKey, AppSecret, Code); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetToken"); - - Token = Result["access_token"]; + + Token = Result["access_token"]; Refresh = Result["refresh_token"]; - + If ValueIsFilled(Token) Then OPI_TestDataRetrieval.WriteParameter("Dropbox_Token", Token); EndIf; - + If ValueIsFilled(Refresh) Then OPI_TestDataRetrieval.WriteParameter("Dropbox_Refresh", Refresh); EndIf; - + EndProcedure Procedure Dropbox_UpdateToken(FunctionParameters) - AppKey = FunctionParameters["Dropbox_Appkey"]; - AppSecret = FunctionParameters["Dropbox_Appsecret"]; + AppKey = FunctionParameters["Dropbox_Appkey"]; + AppSecret = FunctionParameters["Dropbox_Appsecret"]; RefreshToken = FunctionParameters["Dropbox_Refresh"]; - + Result = OPI_Dropbox.RefreshToken(AppKey, AppSecret, RefreshToken); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UpdateToken"); - + Token = Result["access_token"]; - + OPI_TestDataRetrieval.ExpectsThat(Token).Заполнено(); OPI_TestDataRetrieval.WriteParameter("Dropbox_Token", Token); - + EndProcedure Procedure Dropbox_GetObjectInformation(FunctionParameters) - - Path = "/New/pic.png"; + + Path = "/New/pic.png"; Token = FunctionParameters["Dropbox_Token"]; - + Result = OPI_Dropbox.GetObjectInformation(Token, Path, True); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetObjectInfo", "Dropbox"); Check_DropboxFile(Result, Path); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_GetPreview(FunctionParameters) - + Token = FunctionParameters["Dropbox_Token"]; - Path = "/New/mydoc.docx"; - + Path = "/New/mydoc.docx"; + Result = OPI_Dropbox.GetPreview(Token, Path); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetPreview", "Dropbox"); - + Check_BinaryData(Result, 120000); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_UploadFile(FunctionParameters) - Path = "/New/pic.png"; + Path = "/New/pic.png"; Token = FunctionParameters["Dropbox_Token"]; Image = FunctionParameters["Picture"]; - + ImagePath = GetTempFileName("png"); FileCopy(Image, ImagePath); - + Result = OPI_Dropbox.UploadFile(Token, ImagePath, Path, True); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UploadFile", "Dropbox"); - + Check_DropboxFile(Result, Path); DeleteFiles(ImagePath); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_UploadFileByURL(FunctionParameters) - - Path = "/New/url_doc.docx"; + + Path = "/New/url_doc.docx"; Token = FunctionParameters["Dropbox_Token"]; - URL = FunctionParameters["Document"]; - + URL = FunctionParameters["Document"]; + Result = OPI_Dropbox.UploadFileByURL(Token, URL, Path); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UploadFileByURL", "Dropbox"); - + Check_DropboxWork(Result); - + Work = Result["async_job_id"]; - + FunctionParameters.Insert("Dropbox_Job", Work); OPI_TestDataRetrieval.WriteParameter("Dropbox_Job", Work); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_GetUploadStatusByURL(FunctionParameters) - Token = FunctionParameters["Dropbox_Token"]; + Token = FunctionParameters["Dropbox_Token"]; WorkID = FunctionParameters["Dropbox_Job"]; - Status = "in_progress"; - - WHile Status = "in_progress" Do - + Status = "in_progress"; + + WHile Status = "in_progress" Do + Result = OPI_Dropbox.GetUploadStatusByURL(Token, WorkID); Status = Result[".tag"]; - + OPI_Tools.Pause(5); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetUploadStatusByUrl", "Dropbox"); - + EndDo; - + // END - + Check_DropboxStatus(Result); - - Path = "/New/url_doc.docx"; + + Path = "/New/url_doc.docx"; Result = OPI_Dropbox.DeleteObject(Token, Path); - + Check_DropboxMetadata(Result, Path); - OPI_Tools.Pause(5); - + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_DeleteObject(FunctionParameters) - - Path = "/New/pic.png"; - Token = FunctionParameters["Dropbox_Token"]; - + + Path = "/New/pic.png"; + Token = FunctionParameters["Dropbox_Token"]; + Result = OPI_Dropbox.DeleteObject(Token, Path); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteObject", "Dropbox"); Check_DropboxMetadata(Result, Path); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_CopyObject(FunctionParameters) - + Original = "/New/pic.png"; - Copy = "/New/pic_copy.png"; - Token = FunctionParameters["Dropbox_Token"]; - + Copy = "/New/pic_copy.png"; + Token = FunctionParameters["Dropbox_Token"]; + Result = OPI_Dropbox.CopyObject(Token, Original, Copy); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CopyObject", "Dropbox"); - + Check_DropboxMetadata(Result, Copy); - + Result = OPI_Dropbox.DeleteObject(Token, Copy); Check_DropboxMetadata(Result, Copy); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_MoveObject(FunctionParameters) - + OriginalPath = "/New/pic.png"; - TargetPath = "/pic.png"; - Token = FunctionParameters["Dropbox_Token"]; - + TargetPath = "/pic.png"; + Token = FunctionParameters["Dropbox_Token"]; + Result = OPI_Dropbox.MoveObject(Token, OriginalPath, TargetPath); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "MoveObject", "Dropbox"); - + Check_DropboxMetadata(Result, TargetPath); - + Result = OPI_Dropbox.MoveObject(Token, TargetPath, OriginalPath); Check_DropboxMetadata(Result, OriginalPath); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_CreateFolder(FunctionParameters) - + Token = FunctionParameters["Dropbox_Token"]; - Path = "/New catalog"; - + Path = "/New catalog"; + Result = OPI_Dropbox.CreateFolder(Token, Path); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateFolder", "Dropbox"); - + Check_DropboxMetadata(Result, Path); - + Result = OPI_Dropbox.DeleteObject(Token, Path); Check_DropboxMetadata(Result, Path); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_DownloadFile(FunctionParameters) Token = FunctionParameters["Dropbox_Token"]; - Path = "/New/pic.png"; - + Path = "/New/pic.png"; + Result = OPI_Dropbox.DownloadFile(Token, Path); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DownloadFile", "Dropbox"); - + Check_BinaryData(Result, 2000000); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_DownloadFolder(FunctionParameters) - + Token = FunctionParameters["Dropbox_Token"]; - Path = "/New"; - + Path = "/New"; + Result = OPI_Dropbox.DownloadFolder(Token, Path); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DownloadFolder", "Dropbox"); - + Check_BinaryData(Result); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_GetFolderFileList(FunctionParameters) - - Path = "/New"; + + Path = "/New"; Token = FunctionParameters["Dropbox_Token"]; - + Result = OPI_Dropbox.GetListOfFolderFiles(Token, Path, True); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetFolderFileList", "Dropbox"); Check_DropboxArray(Result); - + OPI_Tools.Pause(5); - -EndProcedure + +EndProcedure Procedure Dropbox_GetObjectVersionList(FunctionParameters) Token = FunctionParameters["Dropbox_Token"]; - Path = "/New/pic.png"; - + Path = "/New/pic.png"; + Result = OPI_Dropbox.GetObjectVersionList(Token, Path, 1); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetObjectVersionList", "Dropbox"); - + Check_DropboxArray(Result, 1); - + Revision = Result["entries"][0]["rev"]; - + FunctionParameters.Insert("Dropbox_FileRevision", Revision); OPI_TestDataRetrieval.WriteParameter("Dropbox_FileRevision", Revision); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_RestoreObjectToVersion(FunctionParameters) - + Version = FunctionParameters["Dropbox_FileRevision"]; - Token = FunctionParameters["Dropbox_Token"]; - Path = "/New/pic.png"; - + Token = FunctionParameters["Dropbox_Token"]; + Path = "/New/pic.png"; + Result = OPI_Dropbox.RestoreObjectToVersion(Token, Path, Version); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "RestoreObjectToVersion", "Dropbox"); - + Check_DropboxFile(Result, Path); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_GetTagList(FunctionParameters) Token = FunctionParameters["Dropbox_Token"]; - + PathsArray = New Array; PathsArray.Add("/New/Dogs.mp3"); - PathsArray.Add("/New/mydoc.docx"); - + PathsArray.Add("/New/mydoc.docx"); + Result = OPI_Dropbox.GetTagList(Token, PathsArray); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetTagList", "Dropbox"); - + Check_DropboxTags(Result, PathsArray.Count()); - + Result = OPI_Dropbox.GetTagList(Token, "/New/mydoc.docx"); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetTagList (single)"); - + Check_DropboxTags(Result, 1); - + HasTag = False; - + For Each Tag In Result["paths_to_tags"][0]["tags"] Do If Tag["tag_text"] = "important" Then - HasTag = True; + HasTag = True; EndIf; EndDo; - + OPI_TestDataRetrieval.ExpectsThat(HasTag).Равно(True); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_AddTag(FunctionParameters) - - Tag = "Important"; + + Tag = "Important"; Token = FunctionParameters["Dropbox_Token"]; - Path = "/New/mydoc.docx"; - + Path = "/New/mydoc.docx"; + Result = OPI_Dropbox.AddTag(Token, Path, Tag); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "AddTag", "Dropbox"); - + Check_Empty(Result); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_DeleteTag(FunctionParameters) - - Tag = "Important"; + + Tag = "Important"; Token = FunctionParameters["Dropbox_Token"]; - Path = "/New/mydoc.docx"; - + Path = "/New/mydoc.docx"; + Result = OPI_Dropbox.DeleteTag(Token, Path, Tag); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteTag", "Dropbox"); - + Check_Empty(Result); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_GetAccountInformation(FunctionParameters) - + Token = FunctionParameters["Dropbox_Token"]; - + Result = OPI_Dropbox.GetAccountInformation(Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetAccountInfo", "Dropbox"); - + Check_DropboxAccount(Result); - + Result = OPI_Dropbox.GetAccountInformation(Token, Result["account_id"]); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetAccountInfo (external)"); - + Check_DropboxAccount(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure Dropbox_GetSpaceUsageData(FunctionParameters) - + Token = FunctionParameters["Dropbox_Token"]; - + Result = OPI_Dropbox.GetSpaceUsageData(Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetSpaceUsageData", "Dropbox"); - + Check_DropboxSpace(Result); - + EndProcedure Procedure Dropbox_AddUsersToFile(FunctionParameters) - + Token = FunctionParameters["Dropbox_Token"]; Email = FunctionParameters["Dropbox_OtherUser"]; - File = FunctionParameters["Dropbox_FileID"]; - + File = FunctionParameters["Dropbox_FileID"]; + Result = OPI_Dropbox.AddUsersToFile(Token, File, Email, False); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "AddUsersToFile", "Dropbox"); - + Check_DropboxMember(Result, Email, False); - + Mails = New Array; Mails.Add(Email); - + Result = OPI_Dropbox.AddUsersToFile(Token, File, Mails, True); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "AddUsersToFile (new.) "); - + Check_DropboxMember(Result, Email, True); - + EndProcedure Procedure Dropbox_PublishFolder(FunctionParameters) - + Token = FunctionParameters["Dropbox_Token"]; - Path = "/New"; - + Path = "/New"; + Result = OPI_Dropbox.PublishFolder(Token, Path); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "PublishFolder", "Dropbox"); - + Check_DropboxPublicFolder(Result); - + FolderID = Result["shared_folder_id"]; - + FunctionParameters.Insert("Dropbox_SharedFolder", FolderID); OPI_TestDataRetrieval.WriteParameter("Dropbox_SharedFolder", FolderID); - - OPI_Tools.Pause(5); + + OPI_Tools.Pause(5); EndProcedure Procedure Dropbox_CancelFolderPublication(FunctionParameters) - - Token = FunctionParameters["Dropbox_Token"]; + + Token = FunctionParameters["Dropbox_Token"]; Folder = FunctionParameters["Dropbox_SharedFolder"]; - - Result = OPI_Dropbox.CancelFolderPublication(Token, Folder); + + Result = OPI_Dropbox.CancelFolderPublication(Token, Folder); CurrentStatus = "in_progress"; - JobID = Result["async_job_id"]; - + JobID = Result["async_job_id"]; + WHile CurrentStatus = "in_progress" Do - Result = OPI_Dropbox.GetAsynchronousChangeStatus(Token, JobID); - CurrentStatus = Result[".tag"]; + Result = OPI_Dropbox.GetAsynchronousChangeStatus(Token, JobID); + CurrentStatus = Result[".tag"]; OPI_Tools.Pause(3); EndDo; - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UnpublishFolder", "Dropbox"); - + Check_DropboxStatus(Result); - - OPI_Tools.Pause(5); - + + OPI_Tools.Pause(5); + EndProcedure Procedure Dropbox_AddUsersToFolder(FunctionParameters) - - Token = FunctionParameters["Dropbox_Token"]; - Email = FunctionParameters["Dropbox_OtherUser"]; + + Token = FunctionParameters["Dropbox_Token"]; + Email = FunctionParameters["Dropbox_OtherUser"]; Folder = FunctionParameters["Dropbox_SharedFolder"]; // shared_folder_id - + Result = OPI_Dropbox.AddUsersToFolder(Token, Folder, Email, False); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "AddUsersToFolder", "Dropbox"); - + Check_Empty(Result); - + Mails = New Array; Mails.Add(Email); - + Result = OPI_Dropbox.AddUsersToFolder(Token, Folder, Mails, True); - + Check_Empty(Result); - + EndProcedure Procedure Dropbox_CancelFilePublication(FunctionParameters) - - Token = FunctionParameters["Dropbox_Token"]; + + Token = FunctionParameters["Dropbox_Token"]; File = FunctionParameters["Dropbox_FileID"]; - + Result = OPI_Dropbox.CancelFilePublication(Token, File); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UnpublishFile", "Dropbox"); - + Check_Empty(Result); - + EndProcedure #EndRegion @@ -6270,2230 +6270,2230 @@ EndProcedure #Region Bitrix24 Procedure Bitrix24_GetAppAuthLink(FunctionParameters) - - Domain = FunctionParameters["Bitrix24_Domain"]; + + Domain = FunctionParameters["Bitrix24_Domain"]; ClientID = FunctionParameters["Bitrix24_ClientID"]; - + Result = OPI_Bitrix24.GetAppAuthLink(Domain, ClientID); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetAppAuthLink", "Bitrix24"); - + Check_String(Result); - + OPI_TestDataRetrieval.WriteParameter("Bitrix24_AuthURL", Result); EndProcedure Procedure Bitrix24_GetToken(FunctionParameters) - - ClientID = FunctionParameters["Bitrix24_ClientID"]; + + ClientID = FunctionParameters["Bitrix24_ClientID"]; ClientSecret = FunctionParameters["Bitrix24_ClientSecret"]; - Code = FunctionParameters["Bitrix24_Code"]; - + Code = FunctionParameters["Bitrix24_Code"]; + Result = OPI_Bitrix24.GetToken(ClientID, ClientSecret, Code); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetToken", "Bitrix24"); - + If ValueIsFilled(Result["access_token"]) And ValueIsFilled(Result["refresh_token"]) Then - OPI_TestDataRetrieval.WriteParameter("Bitrix24_Token" , Result["access_token"]); + OPI_TestDataRetrieval.WriteParameter("Bitrix24_Token" , Result["access_token"]); OPI_TestDataRetrieval.WriteParameter("Bitrix24_Refresh", Result["refresh_token"]); EndIf; - + EndProcedure Procedure Bitrix24_RefreshToken(FunctionParameters) - - ClientID = FunctionParameters["Bitrix24_ClientID"]; + + ClientID = FunctionParameters["Bitrix24_ClientID"]; ClientSecret = FunctionParameters["Bitrix24_ClientSecret"]; - Refresh = FunctionParameters["Bitrix24_Refresh"]; - + Refresh = FunctionParameters["Bitrix24_Refresh"]; + Result = OPI_Bitrix24.RefreshToken(ClientID, ClientSecret, Refresh); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "RefreshToken", "Bitrix24"); - + Check_BitrixAuth(Result); - + If ValueIsFilled(Result["access_token"]) And ValueIsFilled(Result["refresh_token"]) Then - OPI_TestDataRetrieval.WriteParameter("Bitrix24_Token" , Result["access_token"]); + OPI_TestDataRetrieval.WriteParameter("Bitrix24_Token" , Result["access_token"]); OPI_TestDataRetrieval.WriteParameter("Bitrix24_Refresh", Result["refresh_token"]); EndIf; - + EndProcedure Procedure Bitrix24_ServerTime(FunctionParameters) - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.ServerTime(URL); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ServerTime (wh)", "Bitrix24"); - + Check_BitrixTime(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.ServerTime(URL, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ServerTime", "Bitrix24"); - - Check_BitrixTime(Result); - + + Check_BitrixTime(Result); + EndProcedure Procedure Bitrix24_CreatePost(FunctionParameters) - - Text = "Text of post"; - Title = "Post title"; + + Text = "Text of post"; + Title = "Post title"; Image1 = FunctionParameters["Picture"]; // URL, Path or Binary Data Image2 = FunctionParameters["Picture2"]; // URL, Path or Binary Data - + Files = New Map; Files.Insert("1.png", Image1); Files.Insert("2.png", Image2); - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.CreatePost(URL, Text, , Files, Title, True); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreatePost (wh)", "Bitrix24"); - + Check_BitrixNumber(Result); // SKIP - + PostID = Result["result"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookPostID", PostID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookPostID", PostID); // SKIP FunctionParameters.Insert("Bitrix24_HookPostID", PostID); // SKIP - URL = FunctionParameters["Bitrix24_Domain"]; + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.CreatePost(URL, Text, , Files, Title, , Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreatePost", "Bitrix24"); - - Check_BitrixNumber(Result); - + + Check_BitrixNumber(Result); + PostID = Result["result"]; - - OPI_TestDataRetrieval.WriteParameter("Bitrix24_PostID", PostID); + + OPI_TestDataRetrieval.WriteParameter("Bitrix24_PostID", PostID); FunctionParameters.Insert("Bitrix24_PostID", PostID); - + EndProcedure Procedure Bitrix24_UpdatePost(FunctionParameters) - - Text = "New post text"; - Title = "New post title"; + + Text = "New post text"; + Title = "New post title"; Image1 = FunctionParameters["Picture"]; // URL, Path or Binary Data PostID = FunctionParameters["Bitrix24_PostID"]; - + Files = New Map; Files.Insert("1.png", Image1); - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.UpdatePost(URL, PostID, Text, , Files, Title); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UpdatePost (wh)", "Bitrix24"); - + Check_BitrixNumber(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; PostID = FunctionParameters["Bitrix24_HookPostID"]; - + Result = OPI_Bitrix24.UpdatePost(URL, PostID, Text, , Files, Title, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UpdatePost", "Bitrix24"); - - Check_BitrixNumber(Result); - + + Check_BitrixNumber(Result); + EndProcedure Procedure Bitrix24_DeletePost(FunctionParameters) - - PostID = FunctionParameters["Bitrix24_HookPostID"]; - URL = FunctionParameters["Bitrix24_URL"]; - + + PostID = FunctionParameters["Bitrix24_HookPostID"]; + URL = FunctionParameters["Bitrix24_URL"]; + Result = OPI_Bitrix24.DeletePost(URL, PostID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeletePost (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - + PostID = FunctionParameters["Bitrix24_PostID"]; - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; - + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; + Result = OPI_Bitrix24.DeletePost(URL, PostID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeletePost", "Bitrix24"); - - Check_BitrixTrue(Result); - + + Check_BitrixTrue(Result); + EndProcedure Procedure Bitrix24_GetImportantPostViewers(FunctionParameters) - - PostID = FunctionParameters["Bitrix24_HookPostID"]; - URL = FunctionParameters["Bitrix24_URL"]; - + + PostID = FunctionParameters["Bitrix24_HookPostID"]; + URL = FunctionParameters["Bitrix24_URL"]; + Result = OPI_Bitrix24.GetImportantPostViewers(URL, PostID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetImportantPostViewers (wh)", "Bitrix24"); - + Check_BitrixArray(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetImportantPostViewers(URL, PostID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetImportantPostViewers", "Bitrix24"); - - Check_BitrixArray(Result); - + + Check_BitrixArray(Result); + EndProcedure Procedure Bitrix24_GetPosts(FunctionParameters) - - PostID = FunctionParameters["Bitrix24_PostID"]; - URL = FunctionParameters["Bitrix24_URL"]; - + + PostID = FunctionParameters["Bitrix24_PostID"]; + URL = FunctionParameters["Bitrix24_URL"]; + Result = OPI_Bitrix24.GetPosts(URL, PostID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetPosts (wh)", "Bitrix24"); - + Check_BitrixObjectsArray(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetPosts(URL, PostID, , Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetPosts", "Bitrix24"); - - Check_BitrixObjectsArray(Result); - + + Check_BitrixObjectsArray(Result); + EndProcedure Procedure Bitrix24_AddPostComment(FunctionParameters) - - Text = "Comment for post"; - PostID = FunctionParameters["Bitrix24_PostID"]; - URL = FunctionParameters["Bitrix24_URL"]; - + + Text = "Comment for post"; + PostID = FunctionParameters["Bitrix24_PostID"]; + URL = FunctionParameters["Bitrix24_URL"]; + Result = OPI_Bitrix24.AddPostComment(URL, PostID, Text); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "AddPostComment (wh)", "Bitrix24"); - + Check_BitrixNumber(Result); // SKIP - - Text = "Another comment"; - URL = FunctionParameters["Bitrix24_Domain"]; + + Text = "Another comment"; + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.AddPostComment(URL, PostID, Text, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "AddPostComment", "Bitrix24"); - - Check_BitrixNumber(Result); - + + Check_BitrixNumber(Result); + EndProcedure Procedure Bitrix_AddPostRecipients(FunctionParameters) - + Visibility = "UA"; - PostID = FunctionParameters["Bitrix24_PostID"]; - URL = FunctionParameters["Bitrix24_URL"]; - + PostID = FunctionParameters["Bitrix24_PostID"]; + URL = FunctionParameters["Bitrix24_URL"]; + Result = OPI_Bitrix24.AddPostRecipients(URL, PostID, Visibility); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "AddPostRecipients (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.AddPostRecipients(URL, PostID, Visibility, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "AddPostRecipients", "Bitrix24"); - - Check_BitrixTrue(Result); - + + Check_BitrixTrue(Result); + EndProcedure Procedure Bitrix24_GetTaskFieldsStructure(FunctionParameters) - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.GetTaskFieldsStructure(URL); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetTaskFieldsStructure (wh)", "Bitrix24"); - + Check_BitrixFields(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetTaskFieldsStructure(URL, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetTaskFieldsStructure", "Bitrix24"); - - Check_BitrixFields(Result); - + + Check_BitrixFields(Result); + EndProcedure Procedure Bitrix24_CreateTask(FunctionParameters) - + // The complete structure of the fields can be obtained by the GetTaskFieldsStructure() function() - + CurrentDate = OPI_Tools.GetCurrentDate(); - Hour = 3600; - Day = 24; + Hour = 3600; + Day = 24; Responsible = 1; - + TaskData = New Structure; - TaskData.Insert("TITLE" , "New task"); - TaskData.Insert("DESCRIPTION" , "New task description"); - TaskData.Insert("PRIORITY" , "2"); - TaskData.Insert("DEADLINE" , CurrentDate + Hour * Day); + TaskData.Insert("TITLE" , "New task"); + TaskData.Insert("DESCRIPTION" , "New task description"); + TaskData.Insert("PRIORITY" , "2"); + TaskData.Insert("DEADLINE" , CurrentDate + Hour * Day); TaskData.Insert("RESPONSIBLE_ID", Responsible); - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.CreateTask(URL, TaskData); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - + TaskID = Result["result"]["task"]["id"]; // SKIP - - OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookTaskID", TaskID); // SKIP + + OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookTaskID", TaskID); // SKIP FunctionParameters.Insert("Bitrix24_HookTaskID", TaskID); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.CreateTask(URL, TaskData, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateTask", "Bitrix24"); - - Check_BitrixTask(Result); - + + Check_BitrixTask(Result); + TaskID = Result["result"]["task"]["id"]; - - OPI_TestDataRetrieval.WriteParameter("Bitrix24_TaskID", TaskID); + + OPI_TestDataRetrieval.WriteParameter("Bitrix24_TaskID", TaskID); FunctionParameters.Insert("Bitrix24_TaskID", TaskID); - + OPI_Tools.Pause(5); EndProcedure Procedure Bitrix24_UpdateTask(FunctionParameters) - + // The complete structure of the fields can be obtained by the GetTaskFieldsStructure() function() - + TaskData = New Structure; - TaskData.Insert("TITLE", "Another task title"); + TaskData.Insert("TITLE" , "Another task title"); TaskData.Insert("DESCRIPTION", "Another task description"); - TaskData.Insert("PRIORITY", "1"); - - URL = FunctionParameters["Bitrix24_URL"]; + TaskData.Insert("PRIORITY" , "1"); + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.UpdateTask(URL, TaskID, TaskData); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UpdateTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.UpdateTask(URL, TaskID, TaskData, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UpdateTask", "Bitrix24"); - - Check_BitrixTask(Result); - + + Check_BitrixTask(Result); + EndProcedure Procedure Bitrix24_GetTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.GetTask(URL, TaskID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.GetTask(URL, TaskID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetTask", "Bitrix24"); - + Check_BitrixTask(Result); - + EndProcedure Procedure Bitrix24_ApproveTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.ApproveTask(URL, TaskID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ApproveTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.ApproveTask(URL, TaskID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ApproveTask", "Bitrix24"); - + Check_BitrixTask(Result); - + EndProcedure Procedure Bitrix24_DisapproveTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.DisapproveTask(URL, TaskID); - + Check_Map(Result); // SKIP - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DisapproveTask (wh)", "Bitrix24"); - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.DisapproveTask(URL, TaskID, Token); - + // END - + Check_Map(Result); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DisapproveTask", "Bitrix24"); - + EndProcedure Procedure Bitrix24_CompleteTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.CompleteTask(URL, TaskID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CompleteTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.CompleteTask(URL, TaskID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CompleteTask", "Bitrix24"); - + Check_BitrixTask(Result); - + EndProcedure Procedure Bitrix24_RenewTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.RenewTask(URL, TaskID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "RenewTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.RenewTask(URL, TaskID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "RenewTask", "Bitrix24"); - + Check_BitrixTask(Result); - + EndProcedure Procedure Bitrix24_DeferTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.DeferTask(URL, TaskID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeferTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.DeferTask(URL, TaskID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeferTask", "Bitrix24"); - + Check_BitrixTask(Result); - + EndProcedure Procedure Bitrix24_StartTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.StartTask(URL, TaskID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "StartTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.StartTask(URL, TaskID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "StartTask", "Bitrix24"); - + Check_BitrixTask(Result); - + EndProcedure Procedure Bitrix24_StartWatchingTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.StartWatchingTask(URL, TaskID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "StartWatchingTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.StartWatchingTask(URL, TaskID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "StartWatchingTask", "Bitrix24"); - + Check_BitrixTask(Result); - + EndProcedure Procedure Bitrix24_StopWatchingTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.StopWatchingTask(URL, TaskID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "StopWatchingTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.StopWatchingTask(URL, TaskID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "StopWatchingTask", "Bitrix24"); - + Check_BitrixTask(Result); - + EndProcedure Procedure Bitrix24_PauseTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.PauseTask(URL, TaskID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "PauseTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.PauseTask(URL, TaskID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "PauseTask", "Bitrix24"); - + Check_BitrixTask(Result); - + EndProcedure Procedure Bitrix24_DeleteTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.DeleteTask(URL, TaskID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.DeleteTask(URL, TaskID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteTask", "Bitrix24"); - + Check_BitrixTask(Result); - + EndProcedure Procedure Bitrix24_DelegateTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; UserID = FunctionParameters["Bitrix24_UserID"]; - + Result = OPI_Bitrix24.DelegateTask(URL, TaskID, UserID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DelegateTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.DelegateTask(URL, TaskID, UserID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DelegateTask", "Bitrix24"); - + Check_BitrixTask(Result); - + EndProcedure Procedure Bitrix24_AddTaskToFavorites(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.AddTaskToFavorites(URL, TaskID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "StopWatchingTask (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.AddTaskToFavorites(URL, TaskID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "AddTaskToFavorites", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_RemoveTaskFromFavorites(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.RemoveTaskFromFavorites(URL, TaskID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "RemoveTaskFromFavorites (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.RemoveTaskFromFavorites(URL, TaskID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "RemoveTaskFromFavorites", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_GetTaskHistory(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.GetTaskHistory(URL, TaskID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetTaskHistory (wh)", "Bitrix24"); - + Check_BitrixList(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.GetTaskHistory(URL, TaskID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetTaskHistory", "Bitrix24"); - + Check_BitrixList(Result); - + EndProcedure Procedure Bitrix24_GetTasksList(FunctionParameters) - + // Full filter structer you can find at GetTasksFilterStructure method Filter = New Structure; Filter.Insert("CREATED_BY" , 1); Filter.Insert("RESPONSIBLE_ID", 10); - + Indent = 1; - URL = FunctionParameters["Bitrix24_URL"]; - + URL = FunctionParameters["Bitrix24_URL"]; + Result = OPI_Bitrix24.GetTasksList(URL, Filter); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetTasksList (wh)", "Bitrix24"); - + Check_BitrixTasksList(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetTasksList(URL, , Indent, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetTasksList", "Bitrix24"); - + Check_BitrixTasksList(Result); - + EndProcedure Procedure Bitrix24_GetStoragesList(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; Result = OPI_Bitrix24.GetStoragesList(URL); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetStoragesList (wh)", "Bitrix24"); - + Check_BitrixStorage(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetStoragesList(URL, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetStoragesList", "Bitrix24"); - + Check_BitrixStorage(Result); - + EndProcedure Procedure Bitrix24_GetAppStorage(FunctionParameters) - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetAppSotrage(URL, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetAppSotrage", "Bitrix24"); - + Check_BitrixObject(Result); - + StorageID = Result["result"]["ID"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_StorageID", StorageID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_StorageID", StorageID); // SKIP FunctionParameters.Insert("Bitrix24_StorageID", StorageID); // SKIP - + EndProcedure Procedure Bitrix24_UploadFileToStorage(FunctionParameters) - - Filename2 = "Picture2.jpg"; - Name = "Picture1.jpg"; - + + Filename2 = "Picture2.jpg"; + Name = "Picture1.jpg"; + Image2 = FunctionParameters["Picture"]; // Local path, URL or Binary Data - Image = FunctionParameters["Picture2"]; // Local path, URL or Binary Data - + Image = FunctionParameters["Picture2"]; // Local path, URL or Binary Data + DestinationID = 3; - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.UploadFileToStorage(URL, Filename2, Image2, DestinationID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UploadFileInХранorще (хуto)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - + FileID = Result["result"]["ID"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookFileID", FileID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookFileID", FileID); // SKIP FunctionParameters.Insert("Bitrix24_HookFileID", FileID); // SKIP - URL = FunctionParameters["Bitrix24_Domain"]; + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.UploadFileToStorage(URL, Name, Image, DestinationID, , Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UploadFileInХранorще", "Bitrix24"); - - Check_BitrixObject(Result); - - FileID = Result["result"]["ID"]; - OPI_TestDataRetrieval.WriteParameter("Bitrix24_FileID", FileID); - FunctionParameters.Insert("Bitrix24_FileID", FileID); - + + Check_BitrixObject(Result); + + FileID = Result["result"]["ID"]; + OPI_TestDataRetrieval.WriteParameter("Bitrix24_FileID", FileID); + FunctionParameters.Insert("Bitrix24_FileID", FileID); + EndProcedure Procedure Bitrix24_DeleteFile(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; FileID = FunctionParameters["Bitrix24_HookFileID"]; - + Result = OPI_Bitrix24.DeleteFile(URL, FileID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteFile (хуto)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; FileID = FunctionParameters["Bitrix24_FileID"]; - + Result = OPI_Bitrix24.DeleteFile(URL, FileID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteFile", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_CreateStorageFolder(FunctionParameters) - + StorageID = 3; - Name = "New catalog"; + Name = "New catalog"; Filename2 = "New folder 2"; - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.CreateStorageFolder(URL, StorageID, Filename2); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateStorageFolder (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - + FolderID = Result["result"]["ID"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookFolderID", FolderID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookFolderID", FolderID); // SKIP FunctionParameters.Insert("Bitrix24_HookFolderID", FolderID); // SKIP - URL = FunctionParameters["Bitrix24_Domain"]; + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.CreateStorageFolder(URL, StorageID, Name, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateStorageFolder", "Bitrix24"); - - Check_BitrixObject(Result); - + + Check_BitrixObject(Result); + FolderID = Result["result"]["ID"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_FolderID", FolderID); // SKIP - FunctionParameters.Insert("Bitrix24_FolderID", FolderID); // SKIP - + OPI_TestDataRetrieval.WriteParameter("Bitrix24_FolderID", FolderID); // SKIP + FunctionParameters.Insert("Bitrix24_FolderID", FolderID); // SKIP + EndProcedure Procedure Bitrix24_DeleteFolder(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; FolderID = FunctionParameters["Bitrix24_HookFolderID"]; - + Result = OPI_Bitrix24.DeleteFolder(URL, FolderID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteFolder (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; FolderID = FunctionParameters["Bitrix24_FolderID"]; - + Result = OPI_Bitrix24.DeleteFolder(URL, FolderID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteFolder", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_GetStorage(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; StorageID = 3; - + Result = OPI_Bitrix24.GetStorage(URL, StorageID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetStorage (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetStorage(URL, StorageID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetStorage", "Bitrix24"); - + Check_BitrixObject(Result); - + EndProcedure Procedure Bitrix24_GetStorageObjects(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - StorageID = 3; - + + URL = FunctionParameters["Bitrix24_URL"]; + StorageID = 3; + Result = OPI_Bitrix24.GetStorageObjects(URL, StorageID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetStorageObjects (wh)", "Bitrix24"); - + Check_BitrixArray(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetStorageObjects(URL, StorageID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetStorageObjects", "Bitrix24"); - + Check_BitrixArray(Result); - + EndProcedure Procedure Bitrix24_RenameStorage(FunctionParameters) - - Name = "New storage name"; - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + Name = "New storage name"; + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; StorageID = FunctionParameters["Bitrix24_StorageID"]; - + Result = OPI_Bitrix24.RenameStorage(URL, StorageID, Name, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "RenameStorage", "Bitrix24"); - + Check_BitrixObject(Result); - + EndProcedure Procedure Bitrix24_GetFolderInformation(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; FolderID = FunctionParameters["Bitrix24_FolderID"]; - + Result = OPI_Bitrix24.GetFolderInformation(URL, FolderID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetFolderInformation (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetFolderInformation(URL, FolderID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetFolderInformation", "Bitrix24"); - + Check_BitrixObject(Result); - + EndProcedure Procedure Bitrix24_CreateSubfolder(FunctionParameters) - - FolderID = FunctionParameters["Bitrix24_FolderID"]; - Name = "New subfolder"; + + FolderID = FunctionParameters["Bitrix24_FolderID"]; + Name = "New subfolder"; Filename2 = "New subfolder 2"; - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.CreateSubfolder(URL, FolderID, Filename2); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateSubfolder (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - + SubfolderID = Result["result"]["ID"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookSubfolderID", SubfolderID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookSubfolderID", SubfolderID); // SKIP FunctionParameters.Insert("Bitrix24_HookSubfolderID", SubfolderID); // SKIP - URL = FunctionParameters["Bitrix24_Domain"]; + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.CreateSubfolder(URL, FolderID, Name, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateSubfolder", "Bitrix24"); - - Check_BitrixObject(Result); - + + Check_BitrixObject(Result); + SubfolderID = Result["result"]["ID"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_SubfolderID", SubfolderID); // SKIP - FunctionParameters.Insert("Bitrix24_SubfolderID", SubfolderID); // SKIP - + OPI_TestDataRetrieval.WriteParameter("Bitrix24_SubfolderID", SubfolderID); // SKIP + FunctionParameters.Insert("Bitrix24_SubfolderID", SubfolderID); // SKIP + EndProcedure Procedure Bitrxi24_MakeFolderCopy(FunctionParameters) - - DestinationID = FunctionParameters["Bitrix24_HookSubfolderID"]; - FolderID = FunctionParameters["Bitrix24_SubfolderID"]; - - URL = FunctionParameters["Bitrix24_URL"]; - - Result = OPI_Bitrix24.MakeFolderCopy(URL, FolderID, DestinationID); - - // !OInt OPI_TestDataRetrieval.WriteLog(Result, "MakeFolderCopy (wh)", "Bitrix24"); - - Check_BitrixObject(Result); // SKIP - - DestinationID = FunctionParameters["Bitrix24_SubfolderID"]; - FolderID = FunctionParameters["Bitrix24_HookSubfolderID"]; - URL = FunctionParameters["Bitrix24_Domain"]; + DestinationID = FunctionParameters["Bitrix24_HookSubfolderID"]; + FolderID = FunctionParameters["Bitrix24_SubfolderID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + + Result = OPI_Bitrix24.MakeFolderCopy(URL, FolderID, DestinationID); + + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "MakeFolderCopy (wh)", "Bitrix24"); + + Check_BitrixObject(Result); // SKIP + + DestinationID = FunctionParameters["Bitrix24_SubfolderID"]; + FolderID = FunctionParameters["Bitrix24_HookSubfolderID"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.MakeFolderCopy(URL, FolderID, DestinationID, Token); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "MakeFolderCopy", "Bitrix24"); - - Check_BitrixObject(Result); - + + Check_BitrixObject(Result); + EndProcedure Procedure Bitrix24_GetFolderExternalLink(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; FolderID = FunctionParameters["Bitrix24_FolderID"]; - + Result = OPI_Bitrix24.GetFolderExternalLink(URL, FolderID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetFolderExternalLink (wh)", "Bitrix24"); - + Check_BitrixString(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetFolderExternalLink(URL, FolderID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetFolderExternalLink", "Bitrix24"); - + Check_BitrixString(Result); - + EndProcedure Procedure Bitrix24_GetFolderFilterStructure(FunctionParameters) - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.GetFolderFilterStructure(URL); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetFolderFilterStructure (wh)", "Bitrix24"); - + Check_Structure(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetFolderFilterStructure(URL, True, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetFolderFilterStructure", "Bitrix24"); - + Check_Structure(Result); - + EndProcedure Procedure Bitrix24_GetFolderItems(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; FolderID = FunctionParameters["Bitrix24_FolderID"]; - + Result = OPI_Bitrix24.GetFolderItems(URL, FolderID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetFolderItems (wh)", "Bitrix24"); - + Check_BitrixArray(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetFolderItems(URL, FolderID, , Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetFolderItems", "Bitrix24"); - + Check_BitrixArray(Result); - + EndProcedure Procedure Bitrxi24_MarkFolderAsDeleted(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; FolderID = FunctionParameters["Bitrix24_FolderID"]; - + Result = OPI_Bitrix24.MarkFolderAsDeleted(URL, FolderID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "MarkFolderAsDeleted (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.MarkFolderAsDeleted(URL, FolderID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "MarkFolderAsDeleted", "Bitrix24"); - + Check_BitrixObject(Result); - + EndProcedure Procedure Bitrix24_RestoreFolder(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; FolderID = FunctionParameters["Bitrix24_FolderID"]; - + Result = OPI_Bitrix24.RestoreFolder(URL, FolderID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "RestoreFolder (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.RestoreFolder(URL, FolderID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "RestoreFolder", "Bitrix24"); - + Check_BitrixObject(Result); - + EndProcedure Procedure Bitrix24_MoveFolder(FunctionParameters) - + DestinationID = FunctionParameters["Bitrix24_HookfolderID"]; - FolderID = FunctionParameters["Bitrix24_SubfolderID"]; - + FolderID = FunctionParameters["Bitrix24_SubfolderID"]; + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.MoveFolder(URL, FolderID, DestinationID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "MoveFolder (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - + FolderID = FunctionParameters["Bitrix24_HookSubfolderID"]; - URL = FunctionParameters["Bitrix24_Domain"]; + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.MoveFolder(URL, FolderID, DestinationID, Token); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "MoveFolder", "Bitrix24"); - - Check_BitrixObject(Result); - + + Check_BitrixObject(Result); + EndProcedure Procedure Bitrix24_RenameFolder(FunctionParameters) - - Name = "New catalog"; + + Name = "New catalog"; Filename2 = "New folder 2"; - + FolderID2 = FunctionParameters["Bitrix24_HookFolderID"]; - URL = FunctionParameters["Bitrix24_URL"]; - + URL = FunctionParameters["Bitrix24_URL"]; + Result = OPI_Bitrix24.RenameFolder(URL, FolderID2, Filename2); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "RenameFolder (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP FolderID = FunctionParameters["Bitrix24_FolderID"]; - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; - + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; + Result = OPI_Bitrix24.RenameFolder(URL, FolderID, Name, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "RenameFolder", "Bitrix24"); - - Check_BitrixObject(Result); - + + Check_BitrixObject(Result); + EndProcedure Procedure Bitrxi24_UploadFileToFolder(FunctionParameters) - - Filename2 = "Picture2.jpg"; - Name = "Picture1.jpg"; - + + Filename2 = "Picture2.jpg"; + Name = "Picture1.jpg"; + Image2 = FunctionParameters["Picture"]; // Local path, URL or Binary Data - Image = FunctionParameters["Picture2"]; // Local path, URL or Binary Data - + Image = FunctionParameters["Picture2"]; // Local path, URL or Binary Data + DestinationID = FunctionParameters["Bitrix24_FolderID"]; - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.UploadFileToFolder(URL, Filename2, Image2, DestinationID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UploadFileInDirectory (хуto)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - + FileID = Result["result"]["ID"]; // SKIP OPI_Bitrix24.DeleteFile(URL, FileID); // SKIP - URL = FunctionParameters["Bitrix24_Domain"]; + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.UploadFileToFolder(URL, Name, Image, DestinationID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UploadFileInDirectory", "Bitrix24"); - - Check_BitrixObject(Result); - + + Check_BitrixObject(Result); + FileID = Result["result"]["ID"]; - Result = OPI_Bitrix24.DeleteFile(URL, FileID, Token); - + Result = OPI_Bitrix24.DeleteFile(URL, FileID, Token); + EndProcedure Procedure Bitrix24_MakeFileCopy(FunctionParameters) - + FolderID = FunctionParameters["Bitrix24_HookFolderID"]; - FileID = FunctionParameters["Bitrix24_FileID"]; - + FileID = FunctionParameters["Bitrix24_FileID"]; + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.MakeFileCopy(URL, FileID, FolderID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "MakeFileCopy (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - + FolderID = FunctionParameters["Bitrix24_FolderID"]; - URL = FunctionParameters["Bitrix24_Domain"]; + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.MakeFileCopy(URL, FileID, FolderID, Token); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "MakeFileCopy", "Bitrix24"); - - Check_BitrixObject(Result); - + + Check_BitrixObject(Result); + EndProcedure Procedure Bitrix24_GetFileInformation(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; FileID = FunctionParameters["Bitrix24_FileID"]; - + Result = OPI_Bitrix24.GetFileInformation(URL, FileID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetFileInformation (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetFileInformation(URL, FileID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetFileInformation", "Bitrix24"); - + Check_BitrixObject(Result); - + EndProcedure Procedure Bitrix24_GetFileExternalLink(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; FileID = FunctionParameters["Bitrix24_FileID"]; - + Result = OPI_Bitrix24.GetFileExternalLink(URL, FileID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetFileExternalLink (wh)", "Bitrix24"); - + Check_BitrixString(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetFileExternalLink(URL, FileID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetFileExternalLink", "Bitrix24"); - + Check_BitrixString(Result); - + EndProcedure Procedure Bitrxi24_MarkFileAsDeleted(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; FileID = FunctionParameters["Bitrix24_FileID"]; - + Result = OPI_Bitrix24.MarkFileAsDeleted(URL, FileID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "MarkFileAsDeleted (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.MarkFileAsDeleted(URL, FileID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "MarkFileAsDeleted", "Bitrix24"); - + Check_BitrixObject(Result); - + EndProcedure Procedure Bitrix24_RestoreFile(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; FileID = FunctionParameters["Bitrix24_FileID"]; - + Result = OPI_Bitrix24.RestoreFile(URL, FileID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "RestoreFile (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.RestoreFile(URL, FileID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "RestoreFile", "Bitrix24"); - + Check_BitrixObject(Result); - + EndProcedure Procedure Bitrix24_RenameFile(FunctionParameters) - - Name = "New file name.jpg"; + + Name = "New file name.jpg"; Filename2 = "New file name 2.jpg"; - + FileID2 = FunctionParameters["Bitrix24_HookFileID"]; - URL = FunctionParameters["Bitrix24_URL"]; - + URL = FunctionParameters["Bitrix24_URL"]; + Result = OPI_Bitrix24.RenameFile(URL, FileID2, Filename2); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "RenameFile (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP FileID = FunctionParameters["Bitrix24_FileID"]; - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; - + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; + Result = OPI_Bitrix24.RenameFile(URL, FileID, Name, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "RenameFile", "Bitrix24"); - - Check_BitrixObject(Result); - + + Check_BitrixObject(Result); + EndProcedure Procedure Bitrix24_MoveFileToFolder(FunctionParameters) - + FolderID = FunctionParameters["Bitrix24_HookSubFolderID"]; - FileID = FunctionParameters["Bitrix24_FileID"]; - + FileID = FunctionParameters["Bitrix24_FileID"]; + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.MoveFileToFolder(URL, FileID, FolderID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "MoveFileToFolder (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - + FolderID = FunctionParameters["Bitrix24_SubFolderID"]; - URL = FunctionParameters["Bitrix24_Domain"]; + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.MoveFileToFolder(URL, FileID, FolderID, Token); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "MoveFileToFolder", "Bitrix24"); - - Check_BitrixObject(Result); - + + Check_BitrixObject(Result); + EndProcedure Procedure Bitrix24_AttachFileToTopic(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; FileID = FunctionParameters["Bitrix24_TaskFileID"]; - + Result = OPI_Bitrix24.AttachFileToTopic(URL, TaskID, FileID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "AttachFileToTopic (wh)", "Bitrix24"); - + Check_BitrixAttachment(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.AttachFileToTopic(URL, TaskID, FileID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "AttachFileToTopic", "Bitrix24"); - + Check_BitrixAttachment(Result); - + EndProcedure Procedure Bitrix24_CheckTaskAccesses(FunctionParameters) - + ArrayOfUsers = New Array; ArrayOfUsers.Add("1"); ArrayOfUsers.Add("10"); - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.CheckTaskAccesses(URL, TaskID, ArrayOfUsers); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CheckTaskAccesses (wh)", "Bitrix24"); - + Check_BitrixAvailableActions(Result, ArrayOfUsers.Count()); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.CheckTaskAccesses(URL, TaskID, ArrayOfUsers, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CheckTaskAccesses", "Bitrix24"); - + Check_BitrixAvailableActions(Result, ArrayOfUsers.Count()); - + EndProcedure Procedure Bitrix24_MuteTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.MuteTask(URL, TaskID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "MuteTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.MuteTask(URL, TaskID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "MuteTask", "Bitrix24"); - + Check_BitrixTask(Result); - + EndProcedure Procedure Bitrix24_UnmuteTask(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.UnmuteTask(URL, TaskID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UnmuteTask (wh)", "Bitrix24"); - + Check_BitrixTask(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.UnmuteTask(URL, TaskID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UnmuteTask", "Bitrix24"); - + Check_BitrixTask(Result); - + EndProcedure Procedure Bitrix24_AddTaskComment(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_CommentsTaskID"]; - + Text = "Task impossible, let's split up"; - + Result = OPI_Bitrix24.AddTaskComment(URL, TaskID, Text); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "AddTaskComment (wh)", "Bitrix24"); - + Check_BitrixNumber(Result); // SKIP - + CommentID = Result["result"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookCommentID", CommentID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookCommentID", CommentID); // SKIP FunctionParameters.Insert("Bitrix24_HookCommentID", CommentID); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Text = "Task uninpossible, don't split up"; - + Result = OPI_Bitrix24.AddTaskComment(URL, TaskID, Text, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "AddTaskComment", "Bitrix24"); - + Check_BitrixNumber(Result); - + CommentID = Result["result"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_CommentID", CommentID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_CommentID", CommentID); // SKIP FunctionParameters.Insert("Bitrix24_CommentID", CommentID); // SKIP - + EndProcedure Procedure Bitrix24_DeleteTaskComment(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - TaskID = FunctionParameters["Bitrix24_CommentsTaskID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + TaskID = FunctionParameters["Bitrix24_CommentsTaskID"]; CommentID = FunctionParameters["Bitrix24_HookCommentID"]; - + Result = OPI_Bitrix24.DeleteTaskComment(URL, TaskID, CommentID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteCommentTasks (хуto)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; CommentID = FunctionParameters["Bitrix24_CommentID"]; - + Result = OPI_Bitrix24.DeleteTaskComment(URL, TaskID, CommentID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteCommentTasks", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_CreateResultFromComment(FunctionParameters) - URL = FunctionParameters["Bitrix24_URL"]; + URL = FunctionParameters["Bitrix24_URL"]; CommentID = FunctionParameters["Bitrix24_HookCommentID"]; - + Result = OPI_Bitrix24.CreateResultFromComment(URL, CommentID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateResultFromComment (wh)", "Bitrix24"); - + Check_BitrixResult(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; CommentID = FunctionParameters["Bitrix24_CommentID"]; - + Result = OPI_Bitrix24.CreateResultFromComment(URL, CommentID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateResultFromComment", "Bitrix24"); - + Check_BitrixResult(Result); - + EndProcedure Procedure Bitrix24_DeleteResultFromComment(FunctionParameters) Export - URL = FunctionParameters["Bitrix24_URL"]; + URL = FunctionParameters["Bitrix24_URL"]; CommentID = FunctionParameters["Bitrix24_HookCommentID"]; - + Result = OPI_Bitrix24.DeleteResultFromComment(URL, CommentID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "Delete result from comment)", "Bitrix24"); - + Check_BitrixUndefined(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; CommentID = FunctionParameters["Bitrix24_CommentID"]; - + Result = OPI_Bitrix24.DeleteResultFromComment(URL, CommentID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteResultFromComment", "Bitrix24"); - + Check_BitrixUndefined(Result); - + EndProcedure Procedure Bitrix24_GetResultsList(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_CommentsTaskID"]; - + Result = OPI_Bitrix24.GetResultsList(URL, TaskID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetResultsList (wh)", "Bitrix24"); - + Check_BitrixResultsList(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetResultsList(URL, TaskID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetResultsList", "Bitrix24"); - + Check_BitrixResultsList(Result); - + EndProcedure Procedure Bitrix24_GetTaskCommentsList(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_CommentsTaskID"]; - + Result = OPI_Bitrix24.GetTaskCommentsList(URL, TaskID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetCommentListTasks (хуto)", "Bitrix24"); - + Check_BitrixCommentsList(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetTaskCommentsList(URL, TaskID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetCommentListTasks", "Bitrix24"); - + Check_BitrixCommentsList(Result); - + EndProcedure Procedure Bitrix24_GetTaskComment(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; CommentID = FunctionParameters["Bitrix24_HookCommentID"]; - TaskID = FunctionParameters["Bitrix24_CommentsTaskID"]; - + TaskID = FunctionParameters["Bitrix24_CommentsTaskID"]; + Result = OPI_Bitrix24.GetTaskComment(URL, TaskID, CommentID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetTaskComment (wh)", "Bitrix24"); - + Check_BitrixComment(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; CommentID = FunctionParameters["Bitrix24_CommentID"]; - + Result = OPI_Bitrix24.GetTaskComment(URL, TaskID, CommentID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetTaskComment", "Bitrix24"); - + Check_BitrixComment(Result); - + EndProcedure Procedure Bitrix24_UpdateTaskComment(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - TaskID = FunctionParameters["Bitrix24_CommentsTaskID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + TaskID = FunctionParameters["Bitrix24_CommentsTaskID"]; CommentID = FunctionParameters["Bitrix24_HookCommentID"]; - + Text = "The task has been changed, do not split up"; - + Result = OPI_Bitrix24.UpdateTaskComment(URL, TaskID, CommentID, Text); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "EditCommentTasks (хуto)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; CommentID = FunctionParameters["Bitrix24_CommentID"]; - + Text = "The task has been changed, let's split up"; - + Result = OPI_Bitrix24.UpdateTaskComment(URL, TaskID, CommentID, Text, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "EditCommentTasks", "Bitrix24"); - + Check_BitrixTrue(Result); EndProcedure Procedure Bitrix24_CreateTasksDependencies(FunctionParameters) - - FromID = FunctionParameters["Bitrix24_HookTaskID"]; + + FromID = FunctionParameters["Bitrix24_HookTaskID"]; DestinationID = FunctionParameters["Bitrix24_TaskID"]; - LinkType = 0; - + LinkType = 0; + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.CreateTasksDependencies(URL, FromID, DestinationID, LinkType); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateTasksDependencies (wh)", "Bitrix24"); - + Check_BitrixArray(Result); // SKIP - + Result = OPI_Bitrix24.DeleteTasksDependencies(URL, FromID, DestinationID, LinkType); // SKIP - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteTasksDependencies (wh)", "Bitrix24"); - - FromID = FunctionParameters["Bitrix24_TaskID"]; + + FromID = FunctionParameters["Bitrix24_TaskID"]; DestinationID = FunctionParameters["Bitrix24_HookTaskID"]; - LinkType = 2; - - URL = FunctionParameters["Bitrix24_Domain"]; + LinkType = 2; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.CreateTasksDependencies(URL, FromID, DestinationID, LinkType, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateTasksDependencies", "Bitrix24"); - - Check_BitrixArray(Result); - + + Check_BitrixArray(Result); + Result = OPI_Bitrix24.DeleteTasksDependencies(URL, FromID, DestinationID, LinkType, Token); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteTasksDependencies", "Bitrix24"); - + EndProcedure Procedure Bitrix24_AddKanbanStage(FunctionParameters) - - Name = "New stage"; + + Name = "New stage"; Color = "0026FF"; - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.AddKanbanStage(URL, Name, Color, 6); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "AddKanbanStage (wh)", "Bitrix24"); - + Check_BitrixNumber(Result); // SKIP - + PrevStageID = Result["result"]; - - OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookStageID", PrevStageID); // SKIP + + OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookStageID", PrevStageID); // SKIP FunctionParameters.Insert("Bitrix24_HookStageID", PrevStageID); // SKIP - - Name = "New stage 2"; + + Name = "New stage 2"; Color = "0026FF"; - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.AddKanbanStage(URL, Name, Color, PrevStageID, , True, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "AddKanbanStage", "Bitrix24"); - - Check_BitrixNumber(Result); - + + Check_BitrixNumber(Result); + StageID = Result["result"]; - OPI_TestDataRetrieval.WriteParameter("Bitrix24_StageID", StageID); - FunctionParameters.Insert("Bitrix24_StageID", StageID); - + OPI_TestDataRetrieval.WriteParameter("Bitrix24_StageID", StageID); + FunctionParameters.Insert("Bitrix24_StageID", StageID); + EndProcedure Procedure Bitrix24_DeleteKanbanStage(FunctionParameters) - + StageID = FunctionParameters["Bitrix24_HookStageID"]; - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.DeleteKanbanStage(URL, StageID, True); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteKanbanStage (wh)", "Bitrix24"); - - Check_BitrixTrue(Result); // SKIP - + + Check_BitrixTrue(Result); // SKIP + StageID = FunctionParameters["Bitrix24_StageID"]; - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.DeleteKanbanStage(URL, StageID, , Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteKanbanStage", "Bitrix24"); - - Check_BitrixTrue(Result); - + + Check_BitrixTrue(Result); + EndProcedure Procedure Bitrix24_GetKanbanStages(FunctionParameters) - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.GetKanbanStages(URL, , True); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetKanbanStages (wh)", "Bitrix24"); - - Check_BitrixMap(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + Check_BitrixMap(Result); // SKIP + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetKanbanStages(URL, , , Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetKanbanStages", "Bitrix24"); - - Check_BitrixMap(Result); - + + Check_BitrixMap(Result); + EndProcedure Procedure Bitrix24_MoveTaskToKanbanStage(FunctionParameters) - - TaskID = FunctionParameters["Bitrix24_KanbanTaskID"]; + + TaskID = FunctionParameters["Bitrix24_KanbanTaskID"]; StageID = FunctionParameters["Bitrix24_HookStageID"]; - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.MoveTaskToKanbanStage(URL, TaskID, StageID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "MoveTaskToKanbanStage (wh)", "Bitrix24"); - - Check_BitrixTrue(Result); // SKIP - + + Check_BitrixTrue(Result); // SKIP + StageID = FunctionParameters["Bitrix24_StageID"]; - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.MoveTaskToKanbanStage(URL, TaskID, StageID, , , Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "MoveTaskToKanbanStage", "Bitrix24"); - + Check_BitrixTrue(Result); - + OPI_Bitrix24.MoveTaskToKanbanStage(URL, TaskID, 2, , , Token); - + EndProcedure Procedure Bitrix24_UpdateKanbansStage(FunctionParameters) - - Name = "New stage name"; - Color = "000000"; + + Name = "New stage name"; + Color = "000000"; StageID = FunctionParameters["Bitrix24_HookStageID"]; - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.UpdateKanbansStage(URL, Name, StageID, Color); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UpdateKanbansStage (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - Name = "New stage name 2"; - Color = "000000"; + + Name = "New stage name 2"; + Color = "000000"; StageID = FunctionParameters["Bitrix24_StageID"]; - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.UpdateKanbansStage(URL, Name, StageID, Color, 6, True, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UpdateKanbansStage", "Bitrix24"); - - Check_BitrixTrue(Result); - + + Check_BitrixTrue(Result); + EndProcedure Procedure Bitrix24_AddTasksChecklistElement(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Text = "Checklist element"; - + Result = OPI_Bitrix24.AddTasksChecklistElement(URL, TaskID, Text, True); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "AddTasksChecklistElement (wh)", "Bitrix24"); - + Check_BitrixNumber(Result); // SKIP - + ElementID = Result["result"]; // SKIP - - OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookCheckElementID", ElementID); // SKIP + + OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookCheckElementID", ElementID); // SKIP FunctionParameters.Insert("Bitrix24_HookCheckElementID", ElementID); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.AddTasksChecklistElement(URL, TaskID, Text, , Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "AddTasksChecklistElement", "Bitrix24"); - + Check_BitrixNumber(Result); - - ElementID = Result["result"]; - - OPI_TestDataRetrieval.WriteParameter("Bitrix24_CheckElementID", ElementID); - FunctionParameters.Insert("Bitrix24_CheckElementID", ElementID); - + + ElementID = Result["result"]; + + OPI_TestDataRetrieval.WriteParameter("Bitrix24_CheckElementID", ElementID); + FunctionParameters.Insert("Bitrix24_CheckElementID", ElementID); + EndProcedure Procedure Bitrix24_UpdateTasksChecklistElement(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - TaskID = FunctionParameters["Bitrix24_HookTaskID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + TaskID = FunctionParameters["Bitrix24_HookTaskID"]; ElementID = FunctionParameters["Bitrix24_HookCheckElementID"]; - + Text = "New elements text"; - + Result = OPI_Bitrix24.UpdateTasksChecklistElement(URL, TaskID, ElementID, Text); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UpdateTasksChecklistElement (wh)", "Bitrix24"); - + Check_BitrixUndefined(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; - TaskID = FunctionParameters["Bitrix24_TaskID"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; + TaskID = FunctionParameters["Bitrix24_TaskID"]; ElementID = FunctionParameters["Bitrix24_CheckElementID"]; - + Result = OPI_Bitrix24.UpdateTasksChecklistElement(URL, TaskID, ElementID, Text, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UpdateTasksChecklistElement", "Bitrix24"); - + Check_BitrixUndefined(Result); - + EndProcedure Procedure Bitrix24_DeleteTasksChecklistElement(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - TaskID = FunctionParameters["Bitrix24_HookTaskID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + TaskID = FunctionParameters["Bitrix24_HookTaskID"]; ElementID = FunctionParameters["Bitrix24_HookCheckElementID"]; - + Result = OPI_Bitrix24.DeleteTasksChecklistElement(URL, TaskID, ElementID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteTasksChecklistElement (wh)", "Bitrix24"); - - Check_BitrixTrue(Result); // SKIP - - TaskID = FunctionParameters["Bitrix24_TaskID"]; + + Check_BitrixTrue(Result); // SKIP + + TaskID = FunctionParameters["Bitrix24_TaskID"]; ElementID = FunctionParameters["Bitrix24_CheckElementID"]; - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.DeleteTasksChecklistElement(URL, TaskID, ElementID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteTasksChecklistElement", "Bitrix24"); - - Check_BitrixTrue(Result); - + + Check_BitrixTrue(Result); + EndProcedure Procedure Bitrix24_GetTasksChecklist(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_HookTaskID"]; - + Result = OPI_Bitrix24.GetTasksChecklist(URL, TaskID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetTasksChecklist (wh)", "Bitrix24"); - + Check_BitrixArray(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; TaskID = FunctionParameters["Bitrix24_TaskID"]; - + Result = OPI_Bitrix24.GetTasksChecklist(URL, TaskID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetTasksChecklist", "Bitrix24"); - + Check_BitrixArray(Result); EndProcedure Procedure Bitrix24_GetTasksChecklistElement(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - TaskID = FunctionParameters["Bitrix24_HookTaskID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + TaskID = FunctionParameters["Bitrix24_HookTaskID"]; ElementID = FunctionParameters["Bitrix24_HookCheckElementID"]; - + Result = OPI_Bitrix24.GetTasksChecklistElement(URL, TaskID, ElementID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetTasksChecklistElement (wh)", "Bitrix24"); - - Check_BitrixObject(Result); // SKIP - - TaskID = FunctionParameters["Bitrix24_TaskID"]; + + Check_BitrixObject(Result); // SKIP + + TaskID = FunctionParameters["Bitrix24_TaskID"]; ElementID = FunctionParameters["Bitrix24_CheckElementID"]; - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetTasksChecklistElement(URL, TaskID, ElementID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetTasksChecklistElement", "Bitrix24"); - - Check_BitrixObject(Result); - + + Check_BitrixObject(Result); + EndProcedure Procedure Bitrix24_CompleteTasksChecklistElement(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - TaskID = FunctionParameters["Bitrix24_HookTaskID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + TaskID = FunctionParameters["Bitrix24_HookTaskID"]; ElementID = FunctionParameters["Bitrix24_HookCheckElementID"]; - + Result = OPI_Bitrix24.CompleteTasksChecklistElement(URL, TaskID, ElementID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CompleteTasksChecklistElement (wh)", "Bitrix24"); - - Check_BitrixTrue(Result); // SKIP - - TaskID = FunctionParameters["Bitrix24_TaskID"]; + + Check_BitrixTrue(Result); // SKIP + + TaskID = FunctionParameters["Bitrix24_TaskID"]; ElementID = FunctionParameters["Bitrix24_CheckElementID"]; - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.CompleteTasksChecklistElement(URL, TaskID, ElementID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CompleteTasksChecklistElement", "Bitrix24"); - - Check_BitrixTrue(Result); - + + Check_BitrixTrue(Result); + EndProcedure Procedure Bitrix24_RenewTasksChecklistElement(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - TaskID = FunctionParameters["Bitrix24_HookTaskID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + TaskID = FunctionParameters["Bitrix24_HookTaskID"]; ElementID = FunctionParameters["Bitrix24_HookCheckElementID"]; - + Result = OPI_Bitrix24.RenewTasksChecklistElement(URL, TaskID, ElementID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "RenewTasksChecklistElement (wh)", "Bitrix24"); - - Check_BitrixTrue(Result); // SKIP - - TaskID = FunctionParameters["Bitrix24_TaskID"]; + + Check_BitrixTrue(Result); // SKIP + + TaskID = FunctionParameters["Bitrix24_TaskID"]; ElementID = FunctionParameters["Bitrix24_CheckElementID"]; - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.RenewTasksChecklistElement(URL, TaskID, ElementID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "RenewTasksChecklistElement", "Bitrix24"); - - Check_BitrixTrue(Result); - + + Check_BitrixTrue(Result); + EndProcedure Procedure Bitrix24_AddTaskTimeAccounting(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_ElapsedTaskID"]; - + Time = 3600; - + Result = OPI_Bitrix24.AddTaskTimeAccounting(URL, TaskID, Time); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "AddTaskTimeAccounting (wh)", "Bitrix24"); - + Check_BitrixNumber(Result); // SKIP - + SpendingID = Result["result"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookTimeID", SpendingID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookTimeID", SpendingID); // SKIP FunctionParameters.Insert("Bitrix24_HookTimeID", SpendingID); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - - Text = "Time spent on work"; - UserID = 10; - Time = 7200; + + Text = "Time spent on work"; + UserID = 10; + Time = 7200; SetupDate = AddMonth(OPI_Tools.GetCurrentDate(), -1); - + Result = OPI_Bitrix24.AddTaskTimeAccounting(URL , TaskID , Time @@ -8501,42 +8501,42 @@ Procedure Bitrix24_AddTaskTimeAccounting(FunctionParameters) , Text , SetupDate , Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "AddTaskTimeAccounting", "Bitrix24"); - + Check_BitrixNumber(Result); - - SpendingID = Result["result"]; - OPI_TestDataRetrieval.WriteParameter("Bitrix24_TimeID", SpendingID); - FunctionParameters.Insert("Bitrix24_TimeID", SpendingID); - + + SpendingID = Result["result"]; + OPI_TestDataRetrieval.WriteParameter("Bitrix24_TimeID", SpendingID); + FunctionParameters.Insert("Bitrix24_TimeID", SpendingID); + EndProcedure Procedure Bitrix24_UpdateTaskTimeAccounting(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - TaskID = FunctionParameters["Bitrix24_ElapsedTaskID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + TaskID = FunctionParameters["Bitrix24_ElapsedTaskID"]; RecordID = FunctionParameters["Bitrix24_HookTimeID"]; - + Text = "The text I forgot last time"; Time = 4800; - + Result = OPI_Bitrix24.UpdateTaskTimeAccounting(URL, TaskID, RecordID, Time, Text); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UpdateTaskTimeAccounting (wh)", "Bitrix24"); - + Check_BitrixUndefined(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; RecordID = FunctionParameters["Bitrix24_TimeID"]; - - Text = "New time record"; - Time = 4800; + + Text = "New time record"; + Time = 4800; SetupDate = AddMonth(OPI_Tools.GetCurrentDate(), -1); - + Result = OPI_Bitrix24.UpdateTaskTimeAccounting(URL , TaskID , RecordID @@ -8544,994 +8544,994 @@ Procedure Bitrix24_UpdateTaskTimeAccounting(FunctionParameters) , Text , SetupDate , Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "UpdateTaskTimeAccounting", "Bitrix24"); - - Check_BitrixUndefined(Result); - + + Check_BitrixUndefined(Result); + EndProcedure Procedure Bitrix24_DeleteTaskTimeAccounting(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - TaskID = FunctionParameters["Bitrix24_ElapsedTaskID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + TaskID = FunctionParameters["Bitrix24_ElapsedTaskID"]; RecordID = FunctionParameters["Bitrix24_HookTimeID"]; - + Result = OPI_Bitrix24.DeleteTaskTimeAccounting(URL, TaskID, RecordID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteTaskTimeAccounting (wh)", "Bitrix24"); - + Check_BitrixUndefined(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; RecordID = FunctionParameters["Bitrix24_TimeID"]; - + Result = OPI_Bitrix24.DeleteTaskTimeAccounting(URL, TaskID, RecordID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteTaskTimeAccounting", "Bitrix24"); - + Check_BitrixUndefined(Result); - + EndProcedure Procedure Bitrix24_GetTaskTimeAccounting(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - TaskID = FunctionParameters["Bitrix24_ElapsedTaskID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + TaskID = FunctionParameters["Bitrix24_ElapsedTaskID"]; RecordID = FunctionParameters["Bitrix24_HookTimeID"]; - + Result = OPI_Bitrix24.GetTaskTimeAccounting(URL, TaskID, RecordID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetTaskTimeAccounting (wh)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; RecordID = FunctionParameters["Bitrix24_TimeID"]; - + Result = OPI_Bitrix24.GetTaskTimeAccounting(URL, TaskID, RecordID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetTaskTimeAccounting", "Bitrix24"); - + Check_BitrixObject(Result); - + EndProcedure Procedure Bitrix24_GetTaskTimeAccountingList(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; TaskID = FunctionParameters["Bitrix24_ElapsedTaskID"]; - + Result = OPI_Bitrix24.GetTaskTimeAccountingList(URL, TaskID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetTaskTimeAccountingList (wh)", "Bitrix24"); - + Check_BitrixObjectsArray(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetTaskTimeAccountingList(URL, TaskID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetTaskTimeAccountingList", "Bitrix24"); - + Check_BitrixObjectsArray(Result); - + EndProcedure Procedure Bitrix24_GetDailyPlan(FunctionParameters) - + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.GetDailyPlan(URL); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetDailyPlan (wh)", "Bitrix24"); - + Check_BitrixArray(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetDailyPlan(URL, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetDailyPlan", "Bitrix24"); - + Check_BitrixArray(Result); - + EndProcedure Procedure Bitrix24_CreateChat(FunctionParameters) - + Image = FunctionParameters["Picture"]; OPI_TypeConversion.GetBinaryData(Image); - + B64Image = GetBase64StringFromBinaryData(Image); - + MembersArray = New Array; MembersArray.Add(10); MembersArray.Add(1); - + ChatStructure = New Structure; - ChatStructure.Insert("TYPE" , "OPEN"); - ChatStructure.Insert("TITLE" , "New chat"); + ChatStructure.Insert("TYPE" , "OPEN"); + ChatStructure.Insert("TITLE" , "New chat"); ChatStructure.Insert("DESCRIPTION", "This is a new chat"); - ChatStructure.Insert("COLOR" , "GREEN"); - ChatStructure.Insert("MESSAGE" , "Welcome to new chat"); - ChatStructure.Insert("USERS" , MembersArray); - ChatStructure.Insert("AVATAR" , B64Image); - ChatStructure.Insert("OWNER_ID" , 1); - + ChatStructure.Insert("COLOR" , "GREEN"); + ChatStructure.Insert("MESSAGE" , "Welcome to new chat"); + ChatStructure.Insert("USERS" , MembersArray); + ChatStructure.Insert("AVATAR" , B64Image); + ChatStructure.Insert("OWNER_ID" , 1); + URL = FunctionParameters["Bitrix24_URL"]; - + Result = OPI_Bitrix24.CreateChat(URL, ChatStructure); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateChat (wh)", "Bitrix24"); - + Check_BitrixNumber(Result); // SKIP - + ChatID = Result["result"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookChatID", ChatID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_HookChatID", ChatID); // SKIP FunctionParameters.Insert("Bitrix24_HookChatID", ChatID); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + ChatStructure = New Structure; - ChatStructure.Insert("TYPE" , "CHAT"); + ChatStructure.Insert("TYPE" , "CHAT"); ChatStructure.Insert("TITLE" , "Private chat"); ChatStructure.Insert("USERS" , MembersArray); - + Result = OPI_Bitrix24.CreateChat(URL, ChatStructure, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateChat", "Bitrix24"); - + Check_BitrixNumber(Result); - + ChatID = Result["result"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_ChatID", ChatID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_ChatID", ChatID); // SKIP FunctionParameters.Insert("Bitrix24_ChatID", ChatID); // SKIP - + EndProcedure Procedure Bitrix24_GetChatUsers(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; ChatID = FunctionParameters["Bitrix24_HookChatID"]; - + Result = OPI_Bitrix24.GetChatUsers(URL, ChatID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetUserListChatа (хуto)", "Bitrix24"); - + Check_BitrixArray(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; ChatID = FunctionParameters["Bitrix24_ChatID"]; - + Result = OPI_Bitrix24.GetChatUsers(URL, ChatID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetUserListChatа", "Bitrix24"); - + Check_BitrixArray(Result); - + EndProcedure Procedure Bitrix24_LeaveChat(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; ChatID = FunctionParameters["Bitrix24_HookChatID"]; - + Result = OPI_Bitrix24.LeaveChat(URL, ChatID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "LeaveChat (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; ChatID = FunctionParameters["Bitrix24_ChatID"]; - + Result = OPI_Bitrix24.LeaveChat(URL, ChatID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "LeaveChat", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_DeleteUserFromChat(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; ChatID = FunctionParameters["Bitrix24_HookChatID"]; - + UserID = 10; - + Result = OPI_Bitrix24.DeleteUserFromChat(URL, ChatID, UserID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteUserFromChat (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; ChatID = FunctionParameters["Bitrix24_ChatID"]; - + Result = OPI_Bitrix24.DeleteUserFromChat(URL, ChatID, UserID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteUserFromChat", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_AddUsersToChat(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; ChatID = FunctionParameters["Bitrix24_HookChatID"]; - + UserIDs = New Array; UserIDs.Add(10); UserIDs.Add(12); - + Result = OPI_Bitrix24.AddUsersToChat(URL, ChatID, UserIDs); // !OInt OPI_TestDataRetrieval.WriteLog(Result, "AddUsersToChat (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; ChatID = FunctionParameters["Bitrix24_ChatID"]; UserID = 10; - + Result = OPI_Bitrix24.AddUsersToChat(URL, ChatID, UserID, True, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "AddUsersToChat", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_ChangeChatTitle(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; ChatID = FunctionParameters["Bitrix24_HookChatID"]; - + Title = "New chat title"; - + Result = OPI_Bitrix24.ChangeChatTitle(URL, ChatID, Title); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ChangeChatTitle (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; ChatID = FunctionParameters["Bitrix24_ChatID"]; - + Title = "Another title"; - + Result = OPI_Bitrix24.ChangeChatTitle(URL, ChatID, Title, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ChangeChatTitle", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_ChangeChatColor(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; ChatID = FunctionParameters["Bitrix24_HookChatID"]; - + Color = "AZURE"; - + Result = OPI_Bitrix24.ChangeChatColor(URL, ChatID, Color); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ChangeChatColor (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; ChatID = FunctionParameters["Bitrix24_ChatID"]; - + Color = "PURPLE"; - + Result = OPI_Bitrix24.ChangeChatColor(URL, ChatID, Color, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ChangeChatColor", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_ChangeChatPicture(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; ChatID = FunctionParameters["Bitrix24_HookChatID"]; Image = FunctionParameters["Picture2"]; - + Result = OPI_Bitrix24.ChangeChatPicture(URL, ChatID, Image); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ChangeChatPicture (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; ChatID = FunctionParameters["Bitrix24_ChatID"]; Result = OPI_Bitrix24.ChangeChatPicture(URL, ChatID, Image, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ChangeChatPicture", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_DisableChatNotifications(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; ChatID = FunctionParameters["Bitrix24_HookChatID"]; - + Result = OPI_Bitrix24.DisableChatNotifications(URL, ChatID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DisableChatNotifications (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; ChatID = FunctionParameters["Bitrix24_ChatID"]; - + Result = OPI_Bitrix24.DisableChatNotifications(URL, ChatID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DisableChatNotifications", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_EnableChatNotifications(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; ChatID = FunctionParameters["Bitrix24_HookChatID"]; - + Result = OPI_Bitrix24.EnableChatNotifications(URL, ChatID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "EnableChatNotifications (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; ChatID = FunctionParameters["Bitrix24_ChatID"]; - + Result = OPI_Bitrix24.EnableChatNotifications(URL, ChatID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "EnableChatNotifications", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_ChangeChatOwner(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; ChatID = FunctionParameters["Bitrix24_HookChatID"]; - + UserID = 10; - + Result = OPI_Bitrix24.ChangeChatOwner(URL, ChatID, UserID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ChangeChatOwner (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; ChatID = FunctionParameters["Bitrix24_ChatID"]; - + Result = OPI_Bitrix24.ChangeChatOwner(URL, ChatID, UserID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ChangeChatOwner", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_GetChatMessagesList(FunctionParameters) - URL = FunctionParameters["Bitrix24_URL"]; - ChatID = "chat4"; - + URL = FunctionParameters["Bitrix24_URL"]; + ChatID = "chat4"; + Result = OPI_Bitrix24.GetChatMessagesList(URL, ChatID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetChatMessagesList (wh)", "Bitrix24"); - + Check_BitrixMessages(Result); // SKIP - + MessageID = Result["result"]["messages"][0]["id"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_ChatMessageID", MessageID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_ChatMessageID", MessageID); // SKIP FunctionParameters.Insert("Bitrix24_ChatMessageID", MessageID); // SKIP - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; UserID = 10; - + Result = OPI_Bitrix24.GetChatMessagesList(URL, UserID, , 0, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetChatMessagesList", "Bitrix24"); - + Check_BitrixMessages(Result); - - MessageID = Result["result"]["messages"][0]["id"]; - OPI_TestDataRetrieval.WriteParameter("Bitrix24_UserMessageID", MessageID); - FunctionParameters.Insert("Bitrix24_UserMessageID", MessageID); - + + MessageID = Result["result"]["messages"][0]["id"]; + OPI_TestDataRetrieval.WriteParameter("Bitrix24_UserMessageID", MessageID); + FunctionParameters.Insert("Bitrix24_UserMessageID", MessageID); + EndProcedure Procedure Bitrix24_MarkMessageAsReaded(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - ChatID = "chat" + FunctionParameters["Bitrix24_HookChatID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + ChatID = "chat" + FunctionParameters["Bitrix24_HookChatID"]; MessageID = FunctionParameters["Bitrix24_ChatMessageID"]; - + Result = OPI_Bitrix24.MarkMessageAsReaded(URL, ChatID, MessageID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "MarkMessageAsReaded (wh)", "Bitrix24"); - + Check_BitrixDialog(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; - UserID = 10; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; + UserID = 10; MessageID = FunctionParameters["Bitrix24_UserMessageID"]; - + Result = OPI_Bitrix24.MarkMessageAsReaded(URL, UserID, MessageID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "MarkMessageAsReaded", "Bitrix24"); - + Check_BitrixDialog(Result); - + EndProcedure Procedure Bitrix24_MarkMessageAsUnreaded(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - ChatID = "chat" + FunctionParameters["Bitrix24_HookChatID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + ChatID = "chat" + FunctionParameters["Bitrix24_HookChatID"]; MessageID = FunctionParameters["Bitrix24_ChatMessageID"]; - + Result = OPI_Bitrix24.MarkMessageAsUnreaded(URL, ChatID, MessageID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "MarkMessageAsUnreaded)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; - UserID = 10; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; + UserID = 10; MessageID = FunctionParameters["Bitrix24_UserMessageID"]; - + Result = OPI_Bitrix24.MarkMessageAsUnreaded(URL, UserID, MessageID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "MarkMessageAsUnreaded", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_GetDialog(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - ChatID = "chat" + FunctionParameters["Bitrix24_HookChatID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + ChatID = "chat" + FunctionParameters["Bitrix24_HookChatID"]; Result = OPI_Bitrix24.GetDialog(URL, ChatID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetDialog (wh)", "Bitrix24"); - + Check_BitrixMessage(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; UserID = 10; - + Result = OPI_Bitrix24.GetDialog(URL, UserID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetDialog", "Bitrix24"); - + Check_BitrixMessage(Result); - + EndProcedure Procedure Bitrix24_GetChatMembersList(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - ChatID = "chat" + FunctionParameters["Bitrix24_HookChatID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + ChatID = "chat" + FunctionParameters["Bitrix24_HookChatID"]; Result = OPI_Bitrix24.GetChatMembersList(URL, ChatID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetUserListDialogа (хуto)", "Bitrix24"); - + Check_BitrixArray(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; UserID = 10; - + Result = OPI_Bitrix24.GetChatMembersList(URL, UserID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetUserListDialogа", "Bitrix24"); - + Check_BitrixArray(Result); - + EndProcedure Procedure Bitrix24_SendWritingNotification(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - ChatID = "chat" + FunctionParameters["Bitrix24_HookChatID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + ChatID = "chat" + FunctionParameters["Bitrix24_HookChatID"]; Result = OPI_Bitrix24.SendWritingNotification(URL, ChatID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendWritingNotification (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; UserID = 10; - + Result = OPI_Bitrix24.SendWritingNotification(URL, UserID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendWritingNotification", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_ReadAll(FunctionParameters) - + URL = FunctionParameters["Bitrix24_URL"]; Result = OPI_Bitrix24.ReadAll(URL); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ReadAll (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.ReadAll(URL, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "ReadAll", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_SendMessage(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - ChatID = "chat" + FunctionParameters["Bitrix24_HookChatID"]; - Text = "Message text"; - Image = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/service/test_data/picture.jpg"; - File = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; - + + URL = FunctionParameters["Bitrix24_URL"]; + ChatID = "chat" + FunctionParameters["Bitrix24_HookChatID"]; + Text = "Message text"; + Image = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/service/test_data/picture.jpg"; + File = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; + Attachments = New Array; - Attachments.Add(OPI_Bitrix24.GetPictureBlock("Image1", Image)); + Attachments.Add(OPI_Bitrix24.GetPictureBlock("Image1" , Image)); Attachments.Add(OPI_Bitrix24.GetFileBlock("File1.docx", File)); Result = OPI_Bitrix24.SendMessage(URL, ChatID, Text, Attachments); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendMessage (хуto)", "Bitrix24"); - + Check_BitrixNumber(Result); // SKIP - + MessageID = Result["result"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_ChatMessageID", MessageID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_ChatMessageID", MessageID); // SKIP FunctionParameters.Insert("Bitrix24_ChatMessageID", MessageID); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; UserID = 10; - + Result = OPI_Bitrix24.SendMessage(URL, UserID, Text, , Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendMessage", "Bitrix24"); - + Check_BitrixNumber(Result); - - MessageID = Result["result"]; - OPI_TestDataRetrieval.WriteParameter("Bitrix24_UserMessageID", MessageID); - FunctionParameters.Insert("Bitrix24_UserMessageID", MessageID); - + + MessageID = Result["result"]; + OPI_TestDataRetrieval.WriteParameter("Bitrix24_UserMessageID", MessageID); + FunctionParameters.Insert("Bitrix24_UserMessageID", MessageID); + EndProcedure Procedure Bitrix24_EditMessage(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; MessageID = FunctionParameters["Bitrix24_ChatMessageID"]; - + Text = "New message text"; Result = OPI_Bitrix24.EditMessage(URL, MessageID, Text); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "EditMessage (хуto)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; MessageID = FunctionParameters["Bitrix24_UserMessageID"]; - + Image = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/service/test_data/picture.jpg"; - File = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; - + File = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; + Attachments = New Array; - Attachments.Add(OPI_Bitrix24.GetPictureBlock("Image1", Image)); + Attachments.Add(OPI_Bitrix24.GetPictureBlock("Image1" , Image)); Attachments.Add(OPI_Bitrix24.GetFileBlock("File1.docx", File)); - + Result = OPI_Bitrix24.EditMessage(URL, MessageID, Text, Attachments, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "EditMessage", "Bitrix24"); - - Check_BitrixTrue(Result); - + + Check_BitrixTrue(Result); + EndProcedure Procedure Bitrix24_DeleteMessage(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; MessageID = FunctionParameters["Bitrix24_ChatMessageID"]; Result = OPI_Bitrix24.DeleteMessage(URL, MessageID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteMessage (хуto)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; MessageID = FunctionParameters["Bitrix24_UserMessageID"]; - + Result = OPI_Bitrix24.DeleteMessage(URL, MessageID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteMessage", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_SetMessageReaction(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; MessageID = FunctionParameters["Bitrix24_ChatMessageID"]; Result = OPI_Bitrix24.SetMessageReaction(URL, MessageID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SetMessageReaction (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; MessageID = FunctionParameters["Bitrix24_UserMessageID"]; - + Result = OPI_Bitrix24.SetMessageReaction(URL, MessageID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SetMessageReaction", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_GetChatFilesFolder(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - ChatID = FunctionParameters["Bitrix24_HookChatID"]; + + URL = FunctionParameters["Bitrix24_URL"]; + ChatID = FunctionParameters["Bitrix24_HookChatID"]; Result = OPI_Bitrix24.GetChatFilesFolder(URL, ChatID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetChatFilesFolder)", "Bitrix24"); - + Check_BitrixObject(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; ChatID = FunctionParameters["Bitrix24_ChatID"]; - + Result = OPI_Bitrix24.GetChatFilesFolder(URL, ChatID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetChatFilesFolder", "Bitrix24"); - + Check_BitrixObject(Result); - + EndProcedure Procedure Bitrix24_SendFile(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; - ChatID = FunctionParameters["Bitrix24_HookChatID"]; - File = FunctionParameters["Document"]; // Binary Data, URL or path to file + + URL = FunctionParameters["Bitrix24_URL"]; + ChatID = FunctionParameters["Bitrix24_HookChatID"]; + File = FunctionParameters["Document"]; // Binary Data, URL or path to file Description = "Very important file"; - + Directory = OPI_Bitrix24.GetChatFilesFolder(URL, ChatID); - FolderID = Directory["result"]["ID"]; - + FolderID = Directory["result"]["ID"]; + UploadedFile = OPI_Bitrix24.UploadFileToFolder(URL, "Imortant doc.docx", File, FolderID); - FileID = UploadedFile["result"]["ID"]; + FileID = UploadedFile["result"]["ID"]; Result = OPI_Bitrix24.SendFile(URL, ChatID, FileID, Description); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendFile (хуto)", "Bitrix24"); - + Check_BitrixFileMessage(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; ChatID = FunctionParameters["Bitrix24_ChatID"]; - + Directory = OPI_Bitrix24.GetChatFilesFolder(URL, ChatID, Token); - FolderID = Directory["result"]["ID"]; - + FolderID = Directory["result"]["ID"]; + UploadedFile = OPI_Bitrix24.UploadFileToFolder(URL, "Imortant doc.docx", File, FolderID, Token); - FileID = UploadedFile["result"]["ID"]; + FileID = UploadedFile["result"]["ID"]; Result = OPI_Bitrix24.SendFile(URL, ChatID, FileID, Description, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SendFile", "Bitrix24"); - + Check_BitrixFileMessage(Result); EndProcedure Procedure Bitrix24_GetUsers(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; ArrayOfUsers = New Array; - + ArrayOfUsers.Add(1); ArrayOfUsers.Add(10); Result = OPI_Bitrix24.GetUsers(URL, ArrayOfUsers); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetUsers (wh)", "Bitrix24"); - + Check_BitrixMap(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; UserIDs = 10; - + Result = OPI_Bitrix24.GetUsers(URL, UserIDs, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetUsers", "Bitrix24"); - + Check_BitrixMap(Result); - + EndProcedure Procedure Bitrix24_GetUserStatus(FunctionParameters) - + URL = FunctionParameters["Bitrix24_URL"]; Result = OPI_Bitrix24.GetUserStatus(URL); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetUserStatus (wh)", "Bitrix24"); - + Check_BitrixString(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; + + URL = FunctionParameters["Bitrix24_Domain"]; Token = FunctionParameters["Bitrix24_Token"]; - + Result = OPI_Bitrix24.GetUserStatus(URL, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetUserStatus", "Bitrix24"); - + Check_BitrixString(Result); - + EndProcedure Procedure Bitrix24_SetUserStatus(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; Status = "dnd"; Result = OPI_Bitrix24.SetUserStatus(URL, Status); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SetUserStatus (wh)", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; Status = "away"; - + Result = OPI_Bitrix24.SetUserStatus(URL, Status, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "SetUserStatus", "Bitrix24"); - + Check_BitrixTrue(Result); - + EndProcedure Procedure Bitrix24_CreatePersonalNotification(FunctionParameters) - + UserID = 1; - - URL = FunctionParameters["Bitrix24_URL"]; - Text = "Message text"; + + URL = FunctionParameters["Bitrix24_URL"]; + Text = "Message text"; Image = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/service/test_data/picture.jpg"; - File = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; - + File = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; + Attachments = New Array; - Attachments.Add(OPI_Bitrix24.GetPictureBlock("Image1", Image)); + Attachments.Add(OPI_Bitrix24.GetPictureBlock("Image1" , Image)); Attachments.Add(OPI_Bitrix24.GetFileBlock("File1.docx", File)); Result = OPI_Bitrix24.CreatePersonalNotification(URL, UserID, Text, ,Attachments); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreatePersonalNotification)", "Bitrix24"); - + Check_BitrixNumber(Result); // SKIP - + MessageID = Result["result"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_PersoalHookNotifyID", MessageID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_PersoalHookNotifyID", MessageID); // SKIP FunctionParameters.Insert("Bitrix24_PersoalHookNotifyID", MessageID); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; - Tag = "New"; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; + Tag = "New"; UserID = 10; - + Result = OPI_Bitrix24.CreatePersonalNotification(URL, UserID, Text, Tag, , Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreatePersonalNotification", "Bitrix24"); - + Check_BitrixNumber(Result); - - MessageID = Result["result"]; - OPI_TestDataRetrieval.WriteParameter("Bitrix24_PersoalNotifyID", MessageID); - FunctionParameters.Insert("Bitrix24_PersoalNotifyID", MessageID); - + + MessageID = Result["result"]; + OPI_TestDataRetrieval.WriteParameter("Bitrix24_PersoalNotifyID", MessageID); + FunctionParameters.Insert("Bitrix24_PersoalNotifyID", MessageID); + EndProcedure Procedure Bitrix24_CreateSystemNotification(FunctionParameters) - + UserID = 1; - - URL = FunctionParameters["Bitrix24_URL"]; - Text = "Message text"; + + URL = FunctionParameters["Bitrix24_URL"]; + Text = "Message text"; Image = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/service/test_data/picture.jpg"; - File = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; - + File = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; + Attachments = New Array; - Attachments.Add(OPI_Bitrix24.GetPictureBlock("Image1", Image)); + Attachments.Add(OPI_Bitrix24.GetPictureBlock("Image1" , Image)); Attachments.Add(OPI_Bitrix24.GetFileBlock("File1.docx", File)); Result = OPI_Bitrix24.CreateSystemNotification(URL, UserID, Text, ,Attachments); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateSystemNotification (wh)", "Bitrix24"); - + Check_BitrixNumber(Result); // SKIP - + MessageID = Result["result"]; // SKIP - OPI_TestDataRetrieval.WriteParameter("Bitrix24_SystemHookNotifyID", MessageID); // SKIP + OPI_TestDataRetrieval.WriteParameter("Bitrix24_SystemHookNotifyID", MessageID); // SKIP FunctionParameters.Insert("Bitrix24_SystemHookNotifyID", MessageID); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; - Tag = "New"; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; + Tag = "New"; UserID = 10; - + Result = OPI_Bitrix24.CreateSystemNotification(URL, UserID, Text, Tag, , Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateSystemNotification", "Bitrix24"); - + Check_BitrixNumber(Result); - - MessageID = Result["result"]; - OPI_TestDataRetrieval.WriteParameter("Bitrix24_SystemNotifyID", MessageID); - FunctionParameters.Insert("Bitrix24_SystemNotifyID", MessageID); - + + MessageID = Result["result"]; + OPI_TestDataRetrieval.WriteParameter("Bitrix24_SystemNotifyID", MessageID); + FunctionParameters.Insert("Bitrix24_SystemNotifyID", MessageID); + EndProcedure Procedure Bitrix24_DeleteNotification(FunctionParameters) - - URL = FunctionParameters["Bitrix24_URL"]; + + URL = FunctionParameters["Bitrix24_URL"]; NotificationID = FunctionParameters["Bitrix24_PersoalHookNotifyID"]; - + Result = OPI_Bitrix24.DeleteNotification(URL, NotificationID); - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteNotification", "Bitrix24"); - + Check_BitrixTrue(Result); // SKIP - - URL = FunctionParameters["Bitrix24_Domain"]; - Token = FunctionParameters["Bitrix24_Token"]; + + URL = FunctionParameters["Bitrix24_Domain"]; + Token = FunctionParameters["Bitrix24_Token"]; NotificationID = FunctionParameters["Bitrix24_PersoalNotifyID"]; - + Result = OPI_Bitrix24.DeleteNotification(URL, NotificationID, Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "DeleteNotification (app)", "Bitrix24"); - + Check_BitrixBool(Result); - + EndProcedure #EndRegion @@ -9540,36 +9540,36 @@ EndProcedure Procedure YandexDisk_GetDiskInfo(FunctionParameters) - Token = FunctionParameters["YandexDisk_Token"]; + Token = FunctionParameters["YandexDisk_Token"]; Result = OPI_YandexDisk.GetDiskInformation(Token); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "GetDiskInfo", "YandexDisk"); - + Check_YaDiskDrive(Result); - + OPI_Tools.Pause(5); - + EndProcedure Procedure YandexDisk_CreateFolder(FunctionParameters) Token = FunctionParameters["YandexDisk_Token"]; - Path = "/" + String(New UUID); - + Path = "/" + String(New UUID); + Result = OPI_YandexDisk.CreateFolder(Token, Path); - + // END - + // !OInt OPI_TestDataRetrieval.WriteLog(Result, "CreateFolder", "YandexDisk"); - + Check_YaDiskFolder(Result, Path); - + OPI_YandexDisk.DeleteObject(Token, Path, False); - + OPI_Tools.Pause(5); - + EndProcedure #EndRegion diff --git a/src/en/OPI/src/CommonModules/OPI_Tools/Module.bsl b/src/en/OPI/src/CommonModules/OPI_Tools/Module.bsl index d032252267..5f0829cd9e 100644 --- a/src/en/OPI/src/CommonModules/OPI_Tools/Module.bsl +++ b/src/en/OPI/src/CommonModules/OPI_Tools/Module.bsl @@ -56,69 +56,69 @@ EndFunction #Region RequestsWithBody Function Post(Val URL - , Val Parameters = "" + , Val Parameters = "" , Val AdditionalHeaders = "" , Val JSON = True - , Val FullResponse = False - , Val ResponseFile = Undefined) Export - + , Val FullResponse = False + , Val ResponseFile = Undefined) Export + Return ExecuteRequestWithBody(URL, "POST", Parameters, AdditionalHeaders, JSON, FullResponse, ResponseFile); - + EndFunction Function Patch(Val URL - , Val Parameters = "" + , Val Parameters = "" , Val AdditionalHeaders = "" , Val JSON = True - , Val FullResponse = False - , Val ResponseFile = Undefined) Export - + , Val FullResponse = False + , Val ResponseFile = Undefined) Export + Return ExecuteRequestWithBody(URL, "PATCH", Parameters, AdditionalHeaders, JSON, FullResponse, ResponseFile); - + EndFunction Function Put(Val URL - , Val Parameters = "" + , Val Parameters = "" , Val AdditionalHeaders = "" , Val JSON = True - , Val FullResponse = False - , Val ResponseFile = Undefined) Export - + , Val FullResponse = False + , Val ResponseFile = Undefined) Export + Return ExecuteRequestWithBody(URL, "PUT", Parameters, AdditionalHeaders, JSON, FullResponse, ResponseFile); - + EndFunction Function PostBinary(Val URL , Val Body , Val AdditionalHeaders , Val FullResponse = False - , Val DataType = "application/octet-stream") Export - + , Val DataType = "application/octet-stream") Export + Return ExecuteRequestWithBinaryData(URL, "POST", Body, AdditionalHeaders, FullResponse, DataType); - + EndFunction -#EndRegion +#EndRegion #Region MultipartRequests Function PostMultipart(Val URL - , Val Parameters = "" - , Val Files = "" - , Val ContentType = "image/jpeg" + , Val Parameters = "" + , Val Files = "" + , Val ContentType = "image/jpeg" , Val AdditionalHeaders = "" - , Val ResponseFile = Undefined) Export + , Val ResponseFile = Undefined) Export Return ExecuteMultipartRequest(URL, "POST", Parameters, Files, ContentType, AdditionalHeaders, ResponseFile); EndFunction Function PutMultipart(Val URL - , Val Parameters = "" - , Val Files = "" - , Val ContentType = "image/jpeg" + , Val Parameters = "" + , Val Files = "" + , Val ContentType = "image/jpeg" , Val AdditionalHeaders = "" - , Val ResponseFile = Undefined) Export + , Val ResponseFile = Undefined) Export Return ExecuteMultipartRequest(URL, "PUT", Parameters, Files, ContentType, AdditionalHeaders, ResponseFile); @@ -126,99 +126,99 @@ EndFunction Function PostMultipartRelated(Val URL , Val JSON = "" - , Val Files = "" + , Val Files = "" , Val AdditionalHeaders = "" - , Val ResponseFile = Undefined) Export - + , Val ResponseFile = Undefined) Export + Return ExecuteMultipartRelatedRequest(URL, "POST", JSON, Files, AdditionalHeaders, ResponseFile); - + EndFunction Function PatchMultipartRelated(Val URL , Val JSON = "" - , Val Files = "" + , Val Files = "" , Val AdditionalHeaders = "" - , Val ResponseFile = Undefined) Export - + , Val ResponseFile = Undefined) Export + Return ExecuteMultipartRelatedRequest(URL, "PATCH", JSON, Files, AdditionalHeaders, ResponseFile); - + EndFunction #EndRegion #Region Miscellaneous -Procedure ProcessResponse(Response, Val FullResponse = False) Export - +Procedure ProcessResponse(Response, Val FullResponse = False) Export + If FullResponse Or TypeOf(Response) <> Type("HTTPResponse") Then Return; EndIf; - + BodyFile = Response.GetBodyFileName(); - + If Not BodyFile = Undefined Then - Response = BodyFile; + Response = BodyFile; Return; EndIf; - - GZip = "gzip"; - NeedsUnpacking = - Response.Headers.Get("Content-Encoding") = GZip + + GZip = "gzip"; + NeedsUnpacking = + Response.Headers.Get("Content-Encoding") = GZip Or Response.Headers.Get("content-encoding") = GZip; - + If NeedsUnpacking Then Response = UnpackResponse(Response); EndIf; - + Response = ?(TypeOf(Response) = Type("HTTPResponse"), Response.GetBodyAsBinaryData(), Response); - + If TypeOf(Response) = Type("BinaryData") Then - + Try Response = JsonToStructure(Response); Except Return; EndTry; - + EndIf; - + EndProcedure Function CreateRequest(Val Address, Val AdditionalHeaders = "", Val DataType = "") Export - + Headers = New Map; Headers.Insert("Accept-Encoding", "gzip"); - Headers.Insert("Accept" , "*/*"); - Headers.Insert("Connection" , "keep-alive"); + Headers.Insert("Accept" , "*/*"); + Headers.Insert("Connection" , "keep-alive"); Headers.Insert("Accept-Charset" , "utf-8"); - + If ValueIsFilled(DataType) Then Headers.Insert("Content-Type", DataType); EndIf; - + If TypeOf(AdditionalHeaders) = Type("Map") Then - + For Each Title In AdditionalHeaders Do Headers.Insert(Title.Key, Title.Value); EndDo; - + EndIf; - + NewRequest = New HTTPRequest(Address, Headers); - + Return NewRequest; - + EndFunction Function CreateConnection(Val Server, Val User = "", Val Password = "") Export - - Try + + Try SSL = New OpenSSLSecureConnection; Return New HTTPConnection(Server, 443, User, Password, , 3000, SSL); Except Return New HTTPConnection(Server, 443, User, Password, , 3000); EndTry; - + EndFunction #EndRegion @@ -236,12 +236,12 @@ Function RequestParametersToString(Val Parameters) Export ParameterString = "?"; For Each Parameter In Parameters Do - + ParameterValue = ConvertParameterToString(Parameter.Value); - - ParameterString = ParameterString - + Parameter.Key - + "=" + + ParameterString = ParameterString + + Parameter.Key + + " =" + ParameterValue + "&"; EndDo; @@ -255,20 +255,20 @@ EndFunction Function SplitURL(Val URL) Export URL = StrReplace(URL, "https://", ""); - URL = StrReplace(URL, "http://", ""); - URL = StrReplace(URL, ":443", ""); + URL = StrReplace(URL, "http://" , ""); + URL = StrReplace(URL, ":443" , ""); Address = Right(URL, StrLen(URL) - StrFind(URL, "/", SearchDirection.FromBegin) + 1); - Server = Left(URL, StrFind(URL, "/", SearchDirection.FromBegin) - 1); - - Try - SSL = New OpenSSLSecureConnection; + Server = Left(URL, StrFind(URL, "/", SearchDirection.FromBegin) - 1); + + Try + SSL = New OpenSSLSecureConnection; Except Server = "https://" + Server; EndTry; - + ReturnStructure = New Structure; - ReturnStructure.Insert("Server", Server); + ReturnStructure.Insert("Server" , Server); ReturnStructure.Insert("Address" , Address); Return ReturnStructure; @@ -280,7 +280,7 @@ Function JsonToStructure(Val Text) Export If Not ValueIsFilled(Text) Then Return ""; EndIf; - + Text = ?(TypeOf(Text) = Type("BinaryData"), GetStringFromBinaryData(Text), Text); JSONReader = New JSONReader; @@ -305,14 +305,14 @@ Function JSONString(Val Data, Val Escaping = "None") Export , False); Try - + JSONWriter = New JSONWriter; JSONWriter.SetString(JSONParameters); - + WriteJSON(JSONWriter, Data); Return JSONWriter.Close(); - - Except + + Except Return "NOT JSON: " + String(Data); EndTry; @@ -323,21 +323,21 @@ Function NumberToString(Val Number) Export EndFunction Function ReadJSONFile(Val Path) Export - + JSONReader = New JSONReader; - JSONReader.OpenFile(Path); - Values = ReadJSON(JSONReader); - + JSONReader.OpenFile(Path); + Values = ReadJSON(JSONReader); + JSONReader.Close(); - + Return Values; - + EndFunction Function RequestParametersToMap(Val ParameterString) Export - ReturnMapping = New Map; - NumberOfParts = 2; + ReturnMapping = New Map; + NumberOfParts = 2; ParameterArray = StrSplit(ParameterString, "&", False); For Each Parameter In ParameterArray Do @@ -355,104 +355,104 @@ Function RequestParametersToMap(Val ParameterString) Export EndFunction Function GetCurrentDate() Export - Return ToLocalTime(CurrentUniversalDate()); + Return ToLocalTime(CurrentUniversalDate()); EndFunction Function UNIXTime(Val Date) Export - - OTD = New TypeDescription("Date"); + + OTD = New TypeDescription("Date"); Date = OTD.AdjustValue(Date); - + UNIX = Format(Date - Date(1970, 1, 1, 1, 0, 0), "HC=10; HDC=0; HG=0"); - UNIX = StrReplace(UNIX, ",", ""); + UNIX = StrReplace(UNIX, "," , ""); UNIX = StrReplace(UNIX, Chars.NBSp, ""); - UNIX = StrReplace(UNIX, " ", ""); + UNIX = StrReplace(UNIX, " " , ""); UNIX = Left(UNIX, 10); - + Return UNIX; - + EndFunction Function ProgressInformation(Val Current, Val Total, Val Unit, Val Divider = 1) Export - - Whole = 100; + + Whole = 100; Current = Round(Current / Divider, 2); - Total = Round(Total / Divider, 2); + Total = Round(Total / Divider, 2); Percent = Int(Current / Total * Whole); - - StrCurrent = NumberToString(Current); - StrTotal = NumberToString(Total); + + StrCurrent = NumberToString(Current); + StrTotal = NumberToString(Total); StrPercentage = NumberToString(Percent); - + Information = StrCurrent + "/" + StrTotal + " " + Unit + " ( " + StrPercentage + "% )"; - + Return Information; - + EndFunction Function ConvertDataWithSizeRetrieval(Data, Val MinimumStreamSize = 0) Export - + Size = 0; - + If TypeOf(Data) = Type("String") Then - + FileOnDisk = New File(Data); - - If FileOnDisk.Exists() Then - Size = FileOnDisk.Size(); + + If FileOnDisk.Exists() Then + Size = FileOnDisk.Size(); Else OPI_TypeConversion.GetBinaryData(Data); Size = Data.Size(); EndIf; - + Else OPI_TypeConversion.GetBinaryData(Data); Size = Data.Size(); EndIf; - + If ValueIsFilled(MinimumStreamSize) Then If Size < MinimumStreamSize Then OPI_TypeConversion.GetBinaryData(Data); Else - OPI_TypeConversion.GetBinaryOrStream(Data); - EndIf; + OPI_TypeConversion.GetBinaryOrStream(Data); + EndIf; Else OPI_TypeConversion.GetBinaryOrStream(Data); EndIf; - + Return Size; - + EndFunction Procedure ValueToArray(Value) Export - + Value_ = New Array; Value_.Add(Value); - Value = Value_; + Value = Value_; EndProcedure Procedure ReplaceSpecialCharacters(Text, Markup = "Markdown") Export - + CharacterMapping = New Map; - + If Markup = "HTML" Then - + CharacterMapping.Insert("&", "&"); - + ElsIf Markup = "MarkdownV2" Then - + CharacterMapping.Insert("-", "\-"); CharacterMapping.Insert("+", "\+"); - CharacterMapping.Insert("#", "\#"); + CharacterMapping.Insert("#", "\#"); CharacterMapping.Insert("=", "\="); - CharacterMapping.Insert("{", "\{"); - CharacterMapping.Insert("}", "\}"); + CharacterMapping.Insert("{", "\{"); + CharacterMapping.Insert("}", "\}"); CharacterMapping.Insert(".", "\."); - + Else Return; - EndIf; + EndIf; For Each ArraySymbol In CharacterMapping Do Text = StrReplace(Text, ArraySymbol.Key, ArraySymbol.Value); @@ -461,80 +461,80 @@ Procedure ReplaceSpecialCharacters(Text, Markup = "Markdown") Export EndProcedure Procedure RemoveEmptyCollectionFields(Collection) Export - - CollectionType = TypeOf(Collection); + + CollectionType = TypeOf(Collection); OutputCollection = New(CollectionType); - + If CollectionType = Type("Map") Or CollectionType = Type("Structure") Then - + RemoveEmptyKeyValues(Collection, OutputCollection); - + ElsIf CollectionType = Type("Array") Then - + RemoveEmptyArrayItems(Collection, OutputCollection); - + Else - + OutputCollection = Collection; - + EndIf; - + Collection = OutputCollection; - + EndProcedure Procedure Pause(Val Seconds) Export - + Connection = New HTTPConnection("1C.ru", 11111, , , , Seconds); Try Connection.Get(New HTTPRequest("")); Except - Return; + Return; EndTry; - + EndProcedure Procedure AddField(Val Name, Val Value, Val Type, Collection) Export - + Filled = ValueIsFilled(Value); - + If Not Filled Then Return; EndIf; - - If Type = "Date" Then + + If Type = "Date" Then OPI_TypeConversion.GetDate(Value); Value = UNIXTime(Value); - + ElsIf Type = "DateISO" Then OPI_TypeConversion.GetDate(Value); - Value = XMLString(Value); - + Value = XMLString(Value); + ElsIf Type = "Collection" Then - OPI_TypeConversion.GetCollection(Value); - + OPI_TypeConversion.GetCollection(Value); + ElsIf Type = "Boolean" Then - OPI_TypeConversion.GetBoolean(Value); - + OPI_TypeConversion.GetBoolean(Value); + ElsIf Type = "FileString" Then OPI_TypeConversion.GetLine(Value, True); - + ElsIf Type = "Array" Then OPI_TypeConversion.GetArray(Value); - + ElsIf Type = "BinaryData" Then OPI_TypeConversion.GetBinaryData(Value); - + ElsIf Type = "Number" Then OPI_TypeConversion.GetNumber(Value); - + Else OPI_TypeConversion.GetLine(Value); - + EndIf; - + Collection.Insert(Name, Value); - + EndProcedure #EndRegion @@ -545,24 +545,24 @@ EndProcedure Function ExecuteRequestWithBody(Val URL , Val View - , Val Parameters = "" + , Val Parameters = "" , Val AdditionalHeaders = "" , Val JSON = True - , Val FullResponse = False - , Val ResponseFile = Undefined) - + , Val FullResponse = False + , Val ResponseFile = Undefined) + If Not ValueIsFilled(Parameters) Then Parameters = New Structure; EndIf; - - DataType = ?(JSON, "application/json; charset=utf-8", "application/x-www-form-urlencoded; charset=utf-8"); + + DataType = ?(JSON, "application/json; charset =utf-8", "application/x-www-form-urlencoded; charset =utf-8"); URLStructure = SplitURL(URL); - Server = URLStructure["Server"]; - Address = URLStructure["Address"]; - - Request = CreateRequest(Address, AdditionalHeaders, DataType); + Server = URLStructure["Server"]; + Address = URLStructure["Address"]; + + Request = CreateRequest(Address, AdditionalHeaders, DataType); Connection = CreateConnection(Server); - + SetRequestBody(Request, Parameters, JSON); If ValueIsFilled(ResponseFile) Then @@ -570,17 +570,17 @@ Function ExecuteRequestWithBody(Val URL Else Response = Connection.CallHTTPMethod(View, Request); EndIf; - - If ThisIsRedirection(Response) Then + + If ThisIsRedirection(Response) Then Response = ExecuteRequestWithBody(Response.Headers["Location"] , View , Parameters , AdditionalHeaders , JSON , FullResponse - , ResponseFile); - Else - ProcessResponse(Response, FullResponse); + , ResponseFile); + Else + ProcessResponse(Response, FullResponse); EndIf; Return Response; @@ -593,29 +593,29 @@ Function ExecuteRequestWithBinaryData(Val URL , Val AdditionalHeaders , Val FullResponse , Val DataType) - + URLStructure = SplitURL(URL); - Server = URLStructure["Server"]; - Address = URLStructure["Address"]; - - Request = CreateRequest(Address, AdditionalHeaders, DataType); + Server = URLStructure["Server"]; + Address = URLStructure["Address"]; + + Request = CreateRequest(Address, AdditionalHeaders, DataType); Connection = CreateConnection(Server); - + If Not Data.Size() = 0 Then Request.SetBodyFromBinaryData(Data); EndIf; - + Response = Connection.CallHTTPMethod(View, Request); - If ThisIsRedirection(Response) Then + If ThisIsRedirection(Response) Then Response = ExecuteRequestWithBinaryData(Response.Headers["Location"] , View , Data , AdditionalHeaders , FullResponse - , DataType); - Else - ProcessResponse(Response, FullResponse); + , DataType); + Else + ProcessResponse(Response, FullResponse); EndIf; Return Response; @@ -624,45 +624,45 @@ EndFunction Function ExecuteRequestWithoutBody(Val URL , Val View - , Val Parameters = "" + , Val Parameters = "" , Val AdditionalHeaders = "" - , Val ResponseFile = Undefined) - + , Val ResponseFile = Undefined) + If Not ValueIsFilled(Parameters) Then Parameters = New Structure; EndIf; URLStructure = SplitURL(URL); - Server = URLStructure["Server"]; - Address = URLStructure["Address"] + RequestParametersToString(Parameters); - - Request = CreateRequest(Address, AdditionalHeaders); - Connection = CreateConnection(Server); - + Server = URLStructure["Server"]; + Address = URLStructure["Address"] + RequestParametersToString(Parameters); + + Request = CreateRequest(Address, AdditionalHeaders); + Connection = CreateConnection(Server); + If ValueIsFilled(ResponseFile) Then Response = Connection.CallHTTPMethod(View, Request, ResponseFile); Else Response = Connection.CallHTTPMethod(View, Request); EndIf; - - If ThisIsRedirection(Response) Then - Response = ExecuteRequestWithoutBody(Response.Headers["Location"], View, Parameters, AdditionalHeaders, ResponseFile); - Else - ProcessResponse(Response); + + If ThisIsRedirection(Response) Then + Response = ExecuteRequestWithoutBody(Response.Headers["Location"], View, Parameters, AdditionalHeaders, ResponseFile); + Else + ProcessResponse(Response); EndIf; Return Response; - + EndFunction Function ExecuteMultipartRequest(Val URL , Val View - , Val Parameters = "" - , Val Files = "" - , Val ContentType = "image/jpeg" + , Val Parameters = "" + , Val Files = "" + , Val ContentType = "image/jpeg" , Val AdditionalHeaders = "" - , Val ResponseFile = Undefined) - + , Val ResponseFile = Undefined) + If Not ValueIsFilled(Parameters) Then Parameters = New Structure; EndIf; @@ -671,20 +671,20 @@ Function ExecuteMultipartRequest(Val URL Files = New Map; EndIf; - Redirection = 300; - Error = 400; - Boundary = StrReplace(String(New UUID), "-", ""); + Redirection = 300; + Error = 400; + Boundary = StrReplace(String(New UUID), "-", ""); LineSeparator = Chars.CR + Chars.LF; - DataType = "multipart/form-data; boundary=" + Boundary; - URLStructure = SplitURL(URL); - Server = URLStructure["Server"]; - Address = URLStructure["Address"]; - - Request = CreateRequest(Address, AdditionalHeaders, DataType); + DataType = "multipart/form-data; boundary =" + Boundary; + URLStructure = SplitURL(URL); + Server = URLStructure["Server"]; + Address = URLStructure["Address"]; + + Request = CreateRequest(Address, AdditionalHeaders, DataType); Connection = CreateConnection(Server); - + RequestBody = GetTempFileName(); - TextRecord = New DataWriter(RequestBody + TextRecord = New DataWriter(RequestBody , TextEncoding.UTF8 , ByteOrder.LittleEndian , "" @@ -694,98 +694,98 @@ Function ExecuteMultipartRequest(Val URL WriteMultipartParameters(TextRecord, Boundary, Parameters); WriteMultipartFiles(TextRecord, Boundary, ContentType, Files); - + TextRecord.WriteLine("--" + boundary + "--" + LineSeparator); TextRecord.Close(); Request.SetBodyFileName(RequestBody); - + If ValueIsFilled(ResponseFile) Then Response = Connection.CallHTTPMethod(View, Request, ResponseFile); Else Response = Connection.CallHTTPMethod(View, Request); EndIf; - + ThisIsRedirection = Response.StatusCode >= Redirection And Response.StatusCode < Error; - - If ThisIsRedirection Then + + If ThisIsRedirection Then Response = ExecuteMultipartRequest(Response.Headers["Location"] , View , Parameters , Files , ContentType , AdditionalHeaders - , ResponseFile); - Else - ProcessResponse(Response); + , ResponseFile); + Else + ProcessResponse(Response); EndIf; - - Request = Undefined; + + Request = Undefined; TextRecord = Undefined; - + DeleteFiles(RequestBody); Return Response; - + EndFunction Function ExecuteMultipartRelatedRequest(Val URL , Val View , Val JSON = "" - , Val Files = "" + , Val Files = "" , Val AdditionalHeaders = "" - , Val ResponseFile = Undefined) - - Redirection = 300; - Error = 400; - Boundary = StrReplace(String(New UUID), "-", ""); + , Val ResponseFile = Undefined) + + Redirection = 300; + Error = 400; + Boundary = StrReplace(String(New UUID), "-", ""); LineSeparator = Chars.CR + Chars.LF; - DataType = "multipart/related; boundary=" + Boundary; - URLStructure = SplitURL(URL); - Server = URLStructure["Server"]; - Address = URLStructure["Address"]; - - Request = CreateRequest(Address, AdditionalHeaders, DataType); + DataType = "multipart/related; boundary =" + Boundary; + URLStructure = SplitURL(URL); + Server = URLStructure["Server"]; + Address = URLStructure["Address"]; + + Request = CreateRequest(Address, AdditionalHeaders, DataType); Connection = CreateConnection(Server); - + RequestBody = GetTempFileName(); - TextRecord = New DataWriter(RequestBody + TextRecord = New DataWriter(RequestBody , TextEncoding.UTF8 , ByteOrder.LittleEndian , "" , False , "" , False); - + WriteJSONMultipart(TextRecord, Boundary, JSON); - WriteRelatedFiles(TextRecord, Boundary, Files); - + WriteRelatedFiles(TextRecord, Boundary, Files); + TextRecord.WriteLine("--" + boundary + "--" + LineSeparator); TextRecord.Close(); - + AddContentLength(Request); - + Request.SetBodyFileName(RequestBody); - + If ValueIsFilled(ResponseFile) Then Response = Connection.CallHTTPMethod(View, Request, ResponseFile); Else Response = Connection.CallHTTPMethod(View, Request); EndIf; - + ThisIsRedirection = Response.StatusCode >= Redirection And Response.StatusCode < Error; - - If ThisIsRedirection Then + + If ThisIsRedirection Then Response = ExecuteMultipartRelatedRequest(Response.Headers["Location"] , View , JSON , Files , AdditionalHeaders - , ResponseFile); - Else - ProcessResponse(Response); + , ResponseFile); + Else + ProcessResponse(Response); EndIf; - - Request = Undefined; + + Request = Undefined; TextRecord = Undefined; DeleteFiles(RequestBody); @@ -794,167 +794,167 @@ Function ExecuteMultipartRelatedRequest(Val URL EndFunction Function ThisIsRedirection(Val Response) - - Redirection = 300; - Error = 400; - ThisIsRedirection = Response.StatusCode >= Redirection + Redirection = 300; + Error = 400; + + ThisIsRedirection = Response.StatusCode >= Redirection And Response.StatusCode < Error And ValueIsFilled(Response.Headers["Location"]); - + Return ThisIsRedirection; - + EndFunction Function ConvertParameterToString(Val Value) If TypeOf(Value) = Type("Array") Then - Value = StrConcat(Value, ","); - Value = EncodeString(Value, StringEncodingMethod.URLInURLEncoding); - Value = "[" + Value + "]"; + Value = StrConcat(Value, ","); + Value = EncodeString(Value, StringEncodingMethod.URLInURLEncoding); + Value = "[" + Value + "]"; Else - Value = NumberToString(Value); - Value = EncodeString(Value, StringEncodingMethod.URLInURLEncoding); + Value = NumberToString(Value); + Value = EncodeString(Value, StringEncodingMethod.URLInURLEncoding); EndIf; - + Return Value; - + EndFunction Function SplitFileKey(Val FileData, Val ContentType) DotReplacement = "___"; - FileName = StrReplace(FileData, DotReplacement, "."); - NameParts = StrSplit(FileName, "|", False); - NeedParts = 2; - + FileName = StrReplace(FileData, DotReplacement, "."); + NameParts = StrSplit(FileName, "|", False); + NeedParts = 2; + If NameParts.Count() = NeedParts Then - FieldName = NameParts[0]; - FileName = NameParts[1]; + FieldName = NameParts[0]; + FileName = NameParts[1]; Else - + If ContentType = "image/jpeg" Then - FieldName = "photo"; + FieldName = "photo"; Else - FieldName = Left(FileName, StrFind(FileName, ".") - 1); - FieldName = ?(ValueIsFilled(FieldName), FieldName, StrReplace(FileData, + FieldName = Left(FileName, StrFind(FileName, ".") - 1); + FieldName = ?(ValueIsFilled(FieldName), FieldName, StrReplace(FileData, DotReplacement, ".")); EndIf; - + EndIf; - + ReturnStructure = New Structure("FieldName,FileName", FieldName, FileName); - + Return ReturnStructure; - + EndFunction Procedure SetRequestBody(Request, Val Parameters, Val JSON) - - Collection = TypeOf(Parameters) = Type("Structure") + + Collection = TypeOf(Parameters) = Type("Structure") Or TypeOf(Parameters) = Type("Map") Or TypeOf(Parameters) = Type("Array"); - + If JSON Then - Data = JSONString(Parameters); + Data = JSONString(Parameters); ElsIf Not Collection Then - Data = Parameters; + Data = Parameters; Else ParameterString = RequestParametersToString(Parameters); - Data = Right(ParameterString, StrLen(ParameterString) - 1); + Data = Right(ParameterString, StrLen(ParameterString) - 1); EndIf; - + If TypeOf(Data) = Type("String") Then Request.SetBodyFromString(Data); Else //@skip-check wrong-type-expression Request.SetBodyFromBinaryData(Data); EndIf; - + EndProcedure Procedure WriteMultipartParameters(TextRecord, Val Boundary, Val Parameters) - + LineSeparator = Chars.CR + Chars.LF; - + For Each Parameter In Parameters Do - - If Parameter.Value = Undefined + + If Parameter.Value = Undefined Or Parameter.Value = NULL Then Continue; EndIf; - + TextRecord.WriteLine("--" + boundary + LineSeparator); TextRecord.WriteLine("Content-Disposition: form-data; name=""" + Parameter.Key + """"); TextRecord.WriteLine(LineSeparator); TextRecord.WriteLine(LineSeparator); - - If TypeOf(Parameter.Value) = Type("String") + + If TypeOf(Parameter.Value) = Type("String") Or TypeOf(Parameter.Value) = Type("Number") Then - + ValueAsString = NumberToString(Parameter.Value); TextRecord.WriteLine(ValueAsString); - + ElsIf TypeOf(Parameter.Value) = Type("Boolean") Then - + TextRecord.WriteLine(?(Parameter.Value, "true", "false")); - + Else - + TextRecord.Write(Parameter.Value); - + EndIf; - + TextRecord.WriteLine(LineSeparator); - + EndDo; - + EndProcedure Procedure WriteMultipartFiles(TextRecord, Val Boundary, Val ContentType, Val Files) - - ContentType = TrimAll(ContentType); + + ContentType = TrimAll(ContentType); LineSeparator = Chars.CR + Chars.LF; - + For Each File In Files Do - + DataStructure = SplitFileKey(File.Key, ContentType); - + FieldName = DataStructure["FieldName"]; - FileName = DataStructure["FileName"]; - + FileName = DataStructure["FileName"]; + TextRecord.WriteLine("--" + boundary + LineSeparator); - TextRecord.WriteLine("Content-Disposition: form-data; name=""" - + FieldName - + """; filename=""" + TextRecord.WriteLine("Content-Disposition: form-data; name=""" + + FieldName + + """; filename=""" + FileName + """"); - TextRecord.WriteLine(LineSeparator); - + TextRecord.WriteLine(LineSeparator); + If ValueIsFilled(ContentType) Then TextRecord.WriteLine("Content-Type: " + ContentType); EndIf; - + TextRecord.WriteLine(LineSeparator); TextRecord.WriteLine(LineSeparator); WriteBinaryData(TextRecord, File.Value); TextRecord.WriteLine(LineSeparator); - + EndDo; EndProcedure Procedure WriteRelatedFiles(TextRecord, Val Boundary, Val Files) - + If Not ValueIsFilled(Files) Then Return; EndIf; - + LineSeparator = Chars.CR + Chars.LF; - + If TypeOf(Files) = Type("Map") Then For Each File In Files Do - + TextRecord.WriteLine("--" + boundary + LineSeparator); TextRecord.WriteLine("Content-Type: " + File.Value); TextRecord.WriteLine(LineSeparator); @@ -962,51 +962,51 @@ Procedure WriteRelatedFiles(TextRecord, Val Boundary, Val Files) WriteBinaryData(TextRecord, File.Key); TextRecord.WriteLine(LineSeparator); TextRecord.WriteLine(LineSeparator); - + EndDo; - + EndIf; EndProcedure Procedure WriteBinaryData(DataWriter, Val BinaryData) - - ChunkSize = 268435456; - BytesRead = 0; + + ChunkSize = 268435456; + BytesRead = 0; CurrentPosition = 0; - TotalSize = BinaryData.Size(); + TotalSize = BinaryData.Size(); WHile BytesRead < TotalSize Do - - DataReader = New DataReader(BinaryData); - BytesRead = DataReader.Skip(CurrentPosition); - Result = DataReader.Read(ChunkSize); + + DataReader = New DataReader(BinaryData); + BytesRead = DataReader.Skip(CurrentPosition); + Result = DataReader.Read(ChunkSize); CurrentData = Result.GetBinaryData(); CurrentSize = CurrentData.Size(); - + If Not ValueIsFilled(CurrentData) Then Break; EndIf; DataWriter.Write(CurrentData); - + // !OInt FreeObject(CurrentData); // !OInt RunGarbageCollection(); CurrentPosition = CurrentPosition + CurrentSize; - + EndDo; EndProcedure Procedure WriteJSONMultipart(TextRecord, Val Boundary, Val JSON) - + If Not ValueIsFilled(JSON) Then Return; EndIf; - + LineSeparator = Chars.CR + Chars.LF; - + TextRecord.WriteLine("--" + boundary + LineSeparator); TextRecord.WriteLine("Content-Type: application/json; charset=UTF-8"); TextRecord.WriteLine(LineSeparator); @@ -1018,46 +1018,46 @@ Procedure WriteJSONMultipart(TextRecord, Val Boundary, Val JSON) EndProcedure Procedure AddContentLength(Request) - + RequestBody = Request.GetBodyAsBinaryData(); - + If ValueIsFilled(RequestBody) Then - + Size = RequestBody.Size(); Request.Headers.Insert("Content-Length", NumberToString(Size)); - + EndIf; EndProcedure Procedure RemoveEmptyKeyValues(Val Collection, OutputCollection) - + For Each CollectionItem In Collection Do - + If Not CollectionItem.Value = Undefined And Not CollectionItem.Value = NULL Then OutputCollection.Insert(CollectionItem.Key, CollectionItem.Value); EndIf; - + EndDo; - + EndProcedure Procedure RemoveEmptyArrayItems(Val Collection, OutputCollection) - + For Each CollectionItem In Collection Do - + If Not CollectionItem = Undefined And Not CollectionItem = NULL Then OutputCollection.Add(CollectionItem); EndIf; - + EndDo; - + EndProcedure #Region GZip // Structure description at https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT -// Source: https://github.com/vbondarevsky/Connector +// Source: https://github.com/vbondarevsky/Connector // Connector: convenient HTTP client for 1C:Enterprise 8 // @@ -1094,24 +1094,24 @@ EndFunction Function ReadGZip(CompressedData) Export - GZipPrefixSize = 10; + GZipPrefixSize = 10; GZipPostfixSize = 8; - - SizeDD = ZipSizeDD(); + + SizeDD = ZipSizeDD(); SizeCDH = ZipSizeCDH(); SizeESD = ZipSizeEOCD(); SizeLFH = ZipSizeLFH(); - DataReader = New DataReader(CompressedData); + DataReader = New DataReader(CompressedData); DataReader.Skip(GZipPrefixSize); CompressedDataSize = DataReader.SourceStream().Size() - GZipPrefixSize - GZipPostfixSize; - ZipStream = New MemoryStream(SizeLFH - + CompressedDataSize - + SizeDD - + SizeCDH + ZipStream = New MemoryStream(SizeLFH + + CompressedDataSize + + SizeDD + + SizeCDH + SizeESD); - + DataWriter = New DataWriter(ZipStream); DataWriter.WriteBinaryDataBuffer(ZipLFH()); DataReader.CopyTo(DataWriter, CompressedDataSize); @@ -1123,7 +1123,7 @@ Function ReadGZip(CompressedData) Export UncompressedDataSize = DataReader.ReadInt32(); DataReader.Close(); - DataWriter.WriteBinaryDataBuffer(ZipDD(CRC32, CompressedDataSize, UncompressedDataSize)); + DataWriter.WriteBinaryDataBuffer(ZipDD(CRC32 , CompressedDataSize, UncompressedDataSize)); DataWriter.WriteBinaryDataBuffer(ZipCDH(CRC32, CompressedDataSize, UncompressedDataSize)); DataWriter.WriteBinaryDataBuffer(ZipEOCD(CompressedDataSize)); DataWriter.Close(); @@ -1134,9 +1134,9 @@ EndFunction Function ReadZip(CompressedData, ErrorText = Undefined) - Directory = GetTempFileName(); - ReadingZip = New ZipFileReader(CompressedData); - FileName = ReadingZip.Items[0].Name; + Directory = GetTempFileName(); + ReadingZip = New ZipFileReader(CompressedData); + FileName = ReadingZip.Items[0].Name; Try ReadingZip.Extract(ReadingZip.Items[0], Directory, ZIPRestoreFilePathsMode.DontRestore); Except @@ -1177,12 +1177,12 @@ Function ZipSizeEOCD() EndFunction Function ZipLFH() - + // Local file header Buffer = New BinaryDataBuffer(ZipSizeLFH()); Buffer.WriteInt32(0, 67324752); // signature 0x04034b50 Buffer.WriteInt16(4, 20); // version - Buffer.WriteInt16(6, 10); // bit flags + Buffer.WriteInt16(6, 10); // bit flags Buffer.WriteInt16(8, 8); // compression method Buffer.WriteInt16(10, 0); // time Buffer.WriteInt16(12, 0); // date @@ -1198,7 +1198,7 @@ Function ZipLFH() EndFunction Function ZipDD(CRC32, CompressedDataSize, UncompressedDataSize) - + // Data descriptor Buffer = New BinaryDataBuffer(ZipSizeDD()); Buffer.WriteInt32(0, 134695760); @@ -1211,7 +1211,7 @@ Function ZipDD(CRC32, CompressedDataSize, UncompressedDataSize) EndFunction Function ZipCDH(CRC32, CompressedDataSize, UncompressedDataSize) - + // Central directory header Buffer = New BinaryDataBuffer(ZipSizeCDH()); Buffer.WriteInt32(0, 33639248); // signature 0x02014b50 @@ -1238,7 +1238,7 @@ Function ZipCDH(CRC32, CompressedDataSize, UncompressedDataSize) EndFunction Function ZipEOCD(CompressedDataSize) - + // End of central directory SizeCDH = 50; Buffer = New BinaryDataBuffer(ZipSizeEOCD()); @@ -1247,7 +1247,7 @@ Function ZipEOCD(CompressedDataSize) Buffer.WriteInt16(6, 0); // number of the disk with the start of the central directory Buffer.WriteInt16(8, 1); // total number of entries in the central directory on this disk Buffer.WriteInt16(10, 1); // total number of entries in the central directory - Buffer.WriteInt32(12, SizeCDH); // size of the central directory + Buffer.WriteInt32(12, SizeCDH); // size of the central directory // offset of start of central directory with respect to the starting disk number Buffer.WriteInt32(16, ZipSizeLFH() + CompressedDataSize + ZipSizeDD()); Buffer.WriteInt16(20, 0); // the starting disk number diff --git a/src/en/OPI/src/CommonModules/OPI_Twitter/Module.bsl b/src/en/OPI/src/CommonModules/OPI_Twitter/Module.bsl index 13f73b0ba6..5019dea18c 100644 --- a/src/en/OPI/src/CommonModules/OPI_Twitter/Module.bsl +++ b/src/en/OPI/src/CommonModules/OPI_Twitter/Module.bsl @@ -48,83 +48,83 @@ // Get authorization link // Forms a link for authorization via the browser -// +// // Parameters: // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // String - URL for browser transition Function GetAuthorizationLink(Parameters = "") Export - + Parameters_ = GetStandardParameters(Parameters); - + URLParameters = New Structure; - - URLParameters.Insert("response_type" , "code"); - URLParameters.Insert("client_id" , Parameters_["client_id"]); - URLParameters.Insert("redirect_uri" , Parameters_["redirect_uri"]); - URLParameters.Insert("scope" , Parameters_["scope"]); - URLParameters.Insert("state" , "state"); - URLParameters.Insert("code_challenge" , "challenge"); + + URLParameters.Insert("response_type" , "code"); + URLParameters.Insert("client_id" , Parameters_["client_id"]); + URLParameters.Insert("redirect_uri" , Parameters_["redirect_uri"]); + URLParameters.Insert("scope" , Parameters_["scope"]); + URLParameters.Insert("state" , "state"); + URLParameters.Insert("code_challenge" , "challenge"); URLParameters.Insert("code_challenge_method", "plain"); - + URLParameters = OPI_Tools.RequestParametersToString(URLParameters); - Link = "https://twitter.com/i/oauth2/authorize" + URLParameters; - + Link = "https://twitter.com/i/oauth2/authorize" + URLParameters; + Return Link; - + EndFunction // Get token // Gets the token by the code received when authorizing using the link from GetAuthorizationLink -// +// // Parameters: // Code - String - Code obtained from authorization See GetAuthorizationLink - code // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Twitter Function GetToken(Val Code, Val Parameters = "") Export OPI_TypeConversion.GetLine(Code); - + Parameters_ = GetStandardParameters(Parameters); RequestParameters = New Structure; - RequestParameters.Insert("code" , Code); - RequestParameters.Insert("grant_type" , "authorization_code"); - RequestParameters.Insert("client_id" , Parameters_["client_id"]); + RequestParameters.Insert("code" , Code); + RequestParameters.Insert("grant_type" , "authorization_code"); + RequestParameters.Insert("client_id" , Parameters_["client_id"]); RequestParameters.Insert("redirect_uri" , Parameters_["redirect_uri"]); RequestParameters.Insert("code_verifier", "challenge"); - + Response = OPI_Tools.Post("https://api.twitter.com/2/oauth2/token" , RequestParameters, , False); - + Return Response; - + EndFunction -// Refresh token +// Refresh token // Updates the v2 token using the refresh_token -// +// // Parameters: // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Twitter Function RefreshToken(Val Parameters = "") Export - + Parameters_ = GetStandardParameters(Parameters); - Refresh = "refresh_token"; - + Refresh = "refresh_token"; + RequestParameters = New Structure; - RequestParameters.Insert(Refresh , Parameters_[Refresh]); + RequestParameters.Insert(Refresh , Parameters_[Refresh]); RequestParameters.Insert("grant_type" , Refresh); - RequestParameters.Insert("client_id" , Parameters_["client_id"]); - + RequestParameters.Insert("client_id" , Parameters_["client_id"]); + Response = OPI_Tools.Post("https://api.twitter.com/2/oauth2/token" , RequestParameters, , False); - + Return Response; EndFunction @@ -133,23 +133,23 @@ EndFunction // Method for insertion into an http service, the address of which is specified in redirect_uri // Calls the token acquisition method, as for obtaining a token from the code received // on redirect_uri after authorization via the browser is only 30 seconds -// +// // Parameters: // Request - HTTPServiceRequest - Request coming to the http service -// +// // Returns: // HTTPResponse, Arbitrary, BinaryData - Result of reading the JSON response from the server Function HandleIncomingRequestAfterAuthorization(Request) Export - - Code = Request.RequestParameters["code"]; + + Code = Request.RequestParameters["code"]; TokenResponse = GetToken(Code); - + // BSLLS:CommentedCode-off // Preferred token storage // Constants.TwitterRefresh.Set(ResponseToken["refresh_token"]); // Constants.TwitterToken.Set(ResponseToken["access_token"]); // BSLLS:CommentedCode-on - + Return TokenResponse; EndFunction @@ -160,189 +160,189 @@ EndFunction // !NOCLI // Create custom tweet -// +// // Parameters: // Text - String - Tweet text // MediaArray - Array of String, BinaryData - Array of binary data or file paths // PollOptionsArray - Array of String - Array of poll options, if necessary // PollDuration - String, Number - Poll duration if necessary (poll without duration is not created) // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Twitter Function CreateCustomTweet(Val Text = "" , Val MediaArray = "" , Val PollOptionsArray = "" , Val PollDuration = "" - , Val Parameters = "") Export - + , Val Parameters = "") Export + OPI_TypeConversion.GetLine(Text); OPI_TypeConversion.GetLine(PollDuration); - + If ValueIsFilled(MediaArray) Then OPI_TypeConversion.GetCollection(MediaArray); EndIf; - + If ValueIsFilled(PollOptionsArray) Then OPI_TypeConversion.GetCollection(PollOptionsArray); EndIf; - + Parameters_ = GetStandardParameters(Parameters); - URL = "https://api.twitter.com/2/tweets"; - Array = "Array"; - Fields = New Map; - + URL = "https://api.twitter.com/2/tweets"; + Array = "Array"; + Fields = New Map; + If ValueIsFilled(Text) Then Fields.Insert("text", Text); EndIf; - + If TypeOf(PollOptionsArray) = Type(Array) And ValueIsFilled(PollDuration) Then - + PollDuration = Number(PollDuration); - + If PollOptionsArray.Count() > 0 Then - + OptionStructure = New Structure("options,duration_minutes", PollOptionsArray, PollDuration); Fields.Insert("poll", OptionStructure); - + EndIf; - + EndIf; - + If TypeOf(MediaArray) = Type(Array) Then If MediaArray.Count() > 0 Then Fields.Insert("media", New Structure("media_ids", MediaArray)); EndIf; EndIf; - + Authorization = CreateAuthorizationHeaderV2(Parameters_); - Response = OPI_Tools.Post(URL, Fields, Authorization); + Response = OPI_Tools.Post(URL, Fields, Authorization); Return Response; - + EndFunction // Create text tweet // Creates a tweet without attachments -// +// // Parameters: // Text - String - Tweet text - text // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Twitter Function CreateTextTweet(Val Text, Val Parameters = "") Export - Return CreateCustomTweet(Text, , , , Parameters); + Return CreateCustomTweet(Text, , , , Parameters); EndFunction // Create image tweet // Creates a tweet with an image attachment -// +// // Parameters: // Text - String - Tweet text - text // ImageArray - Array of String, BinaryData - Image files array - pictures // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Twitter Function CreateImageTweet(Val Text, Val ImageArray, Val Parameters = "") Export - + MediaArray = UploadAttachmentsArray(ImageArray, "photo", Parameters); - Return CreateCustomTweet(Text, MediaArray, , , Parameters); - + Return CreateCustomTweet(Text, MediaArray, , , Parameters); + EndFunction // Create gif tweet // Creates a tweet with a gif attachment -// +// // Parameters: // Text - String - Tweet text - text // GifsArray - Array of String, BinaryData - Gif files array - gifs // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Twitter Function CreateGifTweet(Val Text, Val GifsArray, Val Parameters = "") Export - + MediaArray = UploadAttachmentsArray(GifsArray, "animated_gif", Parameters); - Return CreateCustomTweet(Text, MediaArray, , , Parameters); - + Return CreateCustomTweet(Text, MediaArray, , , Parameters); + EndFunction // Create video tweet // Creates a tweet with a video attachment -// +// // Parameters: // Text - String - Tweet text - text // VideosArray - Array of String, BinaryData - Video files array - videos // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Twitter Function CreateVideoTweet(Val Text, Val VideosArray, Val Parameters = "") Export - + MediaArray = UploadAttachmentsArray(VideosArray, "video", Parameters); Return CreateCustomTweet(Text, MediaArray, , , Parameters); - + EndFunction // Create poll tweet // Creates a tweet with a poll -// +// // Parameters: // Text - String - Tweet text - text // OptionArray - Array of String - Poll options array - options // Duration - String, Number - Poll duration - duration // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Twitter Function CreatePollTweet(Val Text, Val OptionArray, Val Duration, Val Parameters = "") Export - - Return CreateCustomTweet(Text, , OptionArray, Duration, Parameters); - + + Return CreateCustomTweet(Text, , OptionArray, Duration, Parameters); + EndFunction // Upload attachments array !NOCLI // Uploads files to the server and returns their IDs -// +// // Parameters: // ArrayOfFiles - Array of String, BinaryData - Files array // AttachmentsType - String - Attachments type // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Array Of String - Media ID array Function UploadAttachmentsArray(Val ArrayOfFiles, Val AttachmentsType, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(AttachmentsType); OPI_TypeConversion.GetCollection(ArrayOfFiles); - - MediaArray = New Array; + + MediaArray = New Array; Parameters_ = GetStandardParameters(Parameters); - MIS = "media_id_string"; - + MIS = "media_id_string"; + If ValueIsFilled(ArrayOfFiles) Then - + For Each SendingFile In ArrayOfFiles Do - + OPI_TypeConversion.GetBinaryData(SendingFile); - + Response = UploadMediaFile(SendingFile, AttachmentsType, Parameters_); - MediaID = Response[MIS]; - + MediaID = Response[MIS]; + If Not ValueIsFilled(MediaID) Then Return Response; EndIf; - + MediaArray.Add(MediaID); - + EndDo; - + EndIf; - + Return MediaArray; - + EndFunction #EndRegion @@ -351,195 +351,195 @@ EndFunction #Region Private -Function UploadMediaFile(Val File, Val Type, Val Parameters) - +Function UploadMediaFile(Val File, Val Type, Val Parameters) + OPI_TypeConversion.GetBinaryData(File); - - RequestType = "POST"; + + RequestType = "POST"; Parameters_ = GetStandardParameters(Parameters); - URL = "https://upload.twitter.com/1.1/media/upload.json"; - - If Type = "photo" Then - + URL = "https://upload.twitter.com/1.1/media/upload.json"; + + If Type = "photo" Then + Fields = New Structure; - Fields.Insert("media_data" , Base64String(File)); + Fields.Insert("media_data" , Base64String(File)); Fields.Insert("media_category", Type); - - Authorization = CreateAuthorizationHeaderV1(Parameters_, Fields, RequestType, URL); - Response = OPI_Tools.Post(URL, Fields, Authorization, False); - + + Authorization = CreateAuthorizationHeaderV1(Parameters_, Fields, RequestType, URL); + Response = OPI_Tools.Post(URL, Fields, Authorization, False); + Else - + Response = UploadMediaInParts(File, Type, RequestType, URL, Parameters_); - + EndIf; - + Return Response; - + EndFunction Function UploadMediaInParts(Val File, Val Type, Val RequestType, Val URL, Parameters) - - Unit = 1024; - Count = 4; + + Unit = 1024; + Count = 4; MediaKey = "media_key"; - MIS = "media_id_string"; - Command = "command"; - Size = File.Size(); - + MIS = "media_id_string"; + Command = "command"; + Size = File.Size(); + MIMETypeMapping = New Map; - MIMETypeMapping.Insert("photo" , "image/jpeg"); - MIMETypeMapping.Insert("video" , "video/mp4"); + MIMETypeMapping.Insert("photo" , "image/jpeg"); + MIMETypeMapping.Insert("video" , "video/mp4"); MIMETypeMapping.Insert("animated_gif", "image/gif"); - - ChunkSize = Count * Unit * Unit; + + ChunkSize = Count * Unit * Unit; ArrayReading = SplitBinaryData(File, ChunkSize); - + Fields = New Structure; - Fields.Insert(Command , "INIT"); - Fields.Insert("total_bytes" , OPI_Tools.NumberToString(Size)); - Fields.Insert("media_type" , MIMETypeMapping.Get(Type)); + Fields.Insert(Command , "INIT"); + Fields.Insert("total_bytes" , OPI_Tools.NumberToString(Size)); + Fields.Insert("media_type" , MIMETypeMapping.Get(Type)); Fields.Insert("media_category" , Type); - + Authorization = CreateAuthorizationHeaderV1(Parameters, Fields, RequestType, URL); InitializationResponse = OPI_Tools.Post(URL, Fields, Authorization, False); - InitializationKey = InitializationResponse[MediaKey]; - InitializationID = InitializationResponse[MIS]; - + InitializationKey = InitializationResponse[MediaKey]; + InitializationID = InitializationResponse[MIS]; + If Not ValueIsFilled(InitializationKey) Or Not ValueIsFilled(InitializationID) Then - Return InitializationResponse; + Return InitializationResponse; EndIf; - + Counter = 0; - + For Each Part In ArrayReading Do - + Fields = New Structure; - Fields.Insert(Command , "APPEND"); - Fields.Insert("media_key" , InitializationKey); + Fields.Insert(Command , "APPEND"); + Fields.Insert("media_key" , InitializationKey); Fields.Insert("segment_index" , OPI_Tools.NumberToString(Counter)); - Fields.Insert("media" , Part); + Fields.Insert("media" , Part); Authorization = CreateAuthorizationHeaderV1(Parameters, New Structure, RequestType, URL); - + OPI_Tools.PostMultipart(URL, Fields, , , Authorization); - + Counter = Counter + 1; - + EndDo; - + Fields = New Structure; - Fields.Insert(Command , "FINALIZE"); + Fields.Insert(Command , "FINALIZE"); Fields.Insert("media_id", InitializationID); - + ProcessingStatus = GetProcessingStatus(Parameters, Fields, URL); - + If Not TypeOf(ProcessingStatus) = Type("String") Then Return ProcessingStatus; EndIf; - + Response = WaitForProcessingCompletion(ProcessingStatus, InitializationID, URL, Parameters); - + Return Response; - + EndFunction Function WaitForProcessingCompletion(Val ProcessingStatus, Val InitializationID, Val URL, Val Parameters) - + ProcessingInfo = "processing_info"; - Command = "command"; - Fields = New Structure; - - Fields.Insert(Command , "STATUS"); + Command = "command"; + Fields = New Structure; + + Fields.Insert(Command , "STATUS"); Fields.Insert("media_id", InitializationID); WHile String(ProcessingStatus) = "pending" Or String(ProcessingStatus) = "in_progress" Do - - Authorization = CreateAuthorizationHeaderV1(Parameters, Fields, "GET", URL); - Response = OPI_Tools.Get(URL, Fields, Authorization); - Information = Response[ProcessingInfo]; + + Authorization = CreateAuthorizationHeaderV1(Parameters, Fields, "GET", URL); + Response = OPI_Tools.Get(URL, Fields, Authorization); + Information = Response[ProcessingInfo]; If Not ValueIsFilled(Information) Then Return Response; EndIf; - + ProcessingStatus = Information["state"]; - + If Not ValueIsFilled(ProcessingStatus) Then Return Response; EndIf; - + EndDo; - + If ProcessingStatus = "failed" Then Raise "Twitter could not process the video you uploaded"; EndIf; - + Return Response; - + EndFunction Function GetStandardParameters(Val Parameters = "") - + // The definition of the data required for the work is collected here. // For Twitter, this is quite a significant set, which is due to the presence of 2 APIs at once, // which, at the same time, are not created for different tasks, but are simply versions of each other. // The current version of the API is v2 and it requires obtaining temporary tokens. Despite the fact, // that Twitter insists on using this latest version, they somehow managed not to transfer - // file upload mechanism and some others from the old version - v1.1. Therefore, something needs to be done + // file upload mechanism and some others from the old version - v1.1. Therefore, something needs to be done // on version 1.1, and something on 2: up to the point that they removed the ability to post tweets from v1.1, // but only through it you can add a picture to the tweet. At the same time, their authentication methods and tokens are different - + // The world gigacorporation of Elon Musk, by the way, a reminder ;) - - // P.S The following is often referred to as the "Twitter Developer settings page" - this + + // P.S The following is often referred to as the "Twitter Developer settings page" - this // https://developer.twitter.com/en/portal/dashboard and chosing of project from list (key icon) - - Parameters_ = New Map; + + Parameters_ = New Map; Permissions = "tweet.read tweet.write tweet.moderate.write users.read " + "follows.read follows.write offline.access space.read mute.read " + "mute.write like.read like.write list.read list.write block.read " - + "block.write bookmark.read bookmark.write"; - + + "block.write bookmark.read bookmark.write"; + // Data for API v2 - + // redirect_uri - URL of your http service (or other request handler) for authorization // scope - a set of permissions for the received key. Can be any, but offline.access is mandatory // client_id - From OAuth 2.0 Client ID and Client Secret settings page of Twitter Developer // client_secret - From OAuth 2.0 Client ID and Client Secret settings page of Twitter Developer // access_token - GetAuthorizationLink() -> Browser -> code will come to redirect_uri -> GetToken(code) // refresh_token - Comes together with access_token and is used to refresh it (access_token lifetime - 2 hr) - // The update is done using the UpdateToken method with new access_token and refresh_token. - // For the next update, you need to use a new refresh_token, so hardcode - // won't work (access_token won't work either) - + // The update is done using the UpdateToken method with new access_token and refresh_token. + // For the next update, you need to use a new refresh_token, so hardcode + // won't work (access_token won't work either) + // |--> RefreshToken() ->|access_token --> 2 hrs. lifetime // | |refresh_token --| // |--------[after 2 hrs.]-------------------| - + // Data for API v1.1 - - // oauth_token - From Authentication Tokens -> Access Token and Secret settings page of Twitter Developer + + // oauth_token - From Authentication Tokens -> Access Token and Secret settings page of Twitter Developer // oauth_token_secret - From Authentication Tokens -> Access Token and Secret settings page of Twitter Developer // oauth_consumer_key - From Consumer Keys -> Access Token and Secret settings page of Twitter Developer // oauth_consumer_secret - From Consumer Keys -> Access Token and Secret settings page of Twitter Developer - + // These tokens do not need to be updated - - Parameters_.Insert("redirect_uri" , ""); - Parameters_.Insert("scope" , Permissions); - Parameters_.Insert("client_id" , ""); - Parameters_.Insert("client_secret" , ""); - Parameters_.Insert("access_token" , ""); // Should be something like Constants.TwitterToken.Get() - Parameters_.Insert("refresh_token" , ""); // Should be something like Constants.TwitterRefresh.Get() - Parameters_.Insert("oauth_token" , ""); - Parameters_.Insert("oauth_token_secret" , ""); - Parameters_.Insert("oauth_consumer_key" , ""); + + Parameters_.Insert("redirect_uri" , ""); + Parameters_.Insert("scope" , Permissions); + Parameters_.Insert("client_id" , ""); + Parameters_.Insert("client_secret" , ""); + Parameters_.Insert("access_token" , ""); // Should be something like Constants.TwitterToken.Get() + Parameters_.Insert("refresh_token" , ""); // Should be something like Constants.TwitterRefresh.Get() + Parameters_.Insert("oauth_token" , ""); + Parameters_.Insert("oauth_token_secret" , ""); + Parameters_.Insert("oauth_consumer_key" , ""); Parameters_.Insert("oauth_consumer_secret", ""); - + OPI_TypeConversion.GetCollection(Parameters); - + If TypeOf(Parameters) = Type("Structure") Or TypeOf(Parameters) = Type("Map") Then For Each PassedParameter In Parameters Do Parameters_.Insert(PassedParameter.Key, OPI_Tools.NumberToString(PassedParameter.Value)); @@ -551,137 +551,137 @@ Function GetStandardParameters(Val Parameters = "") EndFunction Function CreateAuthorizationHeaderV1(Val Parameters, Val Fields, Val RequestType, Val URL) - - CurrentDate = OPI_Tools.GetCurrentDate(); + + CurrentDate = OPI_Tools.GetCurrentDate(); AuthorizationHeader = ""; - HashingMethod = "HMAC-SHA1"; - APIVersion = "1.0"; - SignatureString = ""; - Signature = ""; + HashingMethod = "HMAC-SHA1"; + APIVersion = "1.0"; + SignatureString = ""; + Signature = ""; OCK = "oauth_consumer_key"; OTK = "oauth_token"; - CurrentUNIXDate = OPI_Tools.UNIXTime(CurrentDate); - CurrentUNIXDate = OPI_Tools.NumberToString(CurrentUNIXDate); - ParametersTable = New ValueTable; + CurrentUNIXDate = OPI_Tools.UNIXTime(CurrentDate); + CurrentUNIXDate = OPI_Tools.NumberToString(CurrentUNIXDate); + ParametersTable = New ValueTable; ParametersTable.Columns.Add("Key"); ParametersTable.Columns.Add("Value"); - - For Each Field In Fields Do - - NewLine = ParametersTable.Add(); - NewLine.Key = Field.Key; + + For Each Field In Fields Do + + NewLine = ParametersTable.Add(); + NewLine.Key = Field.Key; NewLine.Value = Field.Value; - + EndDo; - - NewLine = ParametersTable.Add(); - NewLine.Key = OCK; + + NewLine = ParametersTable.Add(); + NewLine.Key = OCK; NewLine.Value = Parameters[OCK]; - - NewLine = ParametersTable.Add(); - NewLine.Key = OTK; + + NewLine = ParametersTable.Add(); + NewLine.Key = OTK; NewLine.Value = Parameters[OTK]; - - NewLine = ParametersTable.Add(); - NewLine.Key = "oauth_version"; + + NewLine = ParametersTable.Add(); + NewLine.Key = "oauth_version"; NewLine.Value = APIVersion; - - NewLine = ParametersTable.Add(); - NewLine.Key = "oauth_signature_method"; + + NewLine = ParametersTable.Add(); + NewLine.Key = "oauth_signature_method"; NewLine.Value = HashingMethod; - NewLine = ParametersTable.Add(); - NewLine.Key = "oauth_timestamp"; + NewLine = ParametersTable.Add(); + NewLine.Key = "oauth_timestamp"; NewLine.Value = CurrentUNIXDate; - NewLine = ParametersTable.Add(); - NewLine.Key = "oauth_nonce"; + NewLine = ParametersTable.Add(); + NewLine.Key = "oauth_nonce"; NewLine.Value = CurrentUNIXDate; For Each TableRow In ParametersTable Do - - TableRow.Key = EncodeString(TableRow.Key, StringEncodingMethod.URLencoding); + + TableRow.Key = EncodeString(TableRow.Key, StringEncodingMethod.URLencoding); TableRow.Value = EncodeString(TableRow.Value, StringEncodingMethod.URLencoding); - + EndDo; - + ParametersTable.Sort("Key"); - + For Each TableRow In ParametersTable Do - - SignatureString = SignatureString - + TableRow.Key - + "=" + + SignatureString = SignatureString + + TableRow.Key + + " =" + TableRow.Value + "&"; - + EndDo; - + SignatureString = Left(SignatureString, StrLen(SignatureString) - 1); - SignatureString = Upper(RequestType) - + "&" - + EncodeString(URL, StringEncodingMethod.URLencoding) + SignatureString = Upper(RequestType) + + "&" + + EncodeString(URL , StringEncodingMethod.URLencoding) + "&" + EncodeString(SignatureString, StringEncodingMethod.URLencoding); - + Signature = EncodeString(Parameters["oauth_consumer_secret"], StringEncodingMethod.URLencoding) - + "&" + + "&" + EncodeString(Parameters["oauth_token_secret"], StringEncodingMethod.URLencoding); - + Signature = OPI_Cryptography.HMAC(GetBinaryDataFromString(Signature) , GetBinaryDataFromString(SignatureString) , HashFunction.SHA1 , 64); - + Signature = EncodeString(Base64String(Signature), StringEncodingMethod.URLencoding); - + Delimiter = ""","; - AuthorizationHeader = AuthorizationHeader + AuthorizationHeader = AuthorizationHeader + "OAuth " - + "oauth_consumer_key=""" + Parameters[OCK] + Delimiter - + "oauth_token=""" + Parameters[OTK] + Delimiter + + "oauth_consumer_key =""" + Parameters[OCK] + Delimiter + + "oauth_token =""" + Parameters[OTK] + Delimiter + "oauth_signature_method=""" + HashingMethod + Delimiter - + "oauth_timestamp=""" + CurrentUNIXDate + Delimiter - + "oauth_nonce=""" + CurrentUNIXDate + Delimiter - + "oauth_version=""" + APIVersion + Delimiter - + "oauth_signature=""" + Signature; - + + "oauth_timestamp =""" + CurrentUNIXDate + Delimiter + + "oauth_nonce =""" + CurrentUNIXDate + Delimiter + + "oauth_version =""" + APIVersion + Delimiter + + "oauth_signature =""" + Signature; + HeaderMapping = New Map; HeaderMapping.Insert("authorization", AuthorizationHeader); - + Return HeaderMapping; - + EndFunction Function CreateAuthorizationHeaderV2(Val Parameters) - + ReturnMapping = New Map; ReturnMapping.Insert("Authorization", "Bearer " + Parameters["access_token"]); - + Return ReturnMapping; - + EndFunction Function GetProcessingStatus(Val Parameters, Val Fields, Val URL) - ProcessingInfo = "processing_info"; + ProcessingInfo = "processing_info"; Authorization = CreateAuthorizationHeaderV1(Parameters, Fields, "POST", URL); - - Response = OPI_Tools.Post(URL, Fields, Authorization, False); + + Response = OPI_Tools.Post(URL, Fields, Authorization, False); Information = Response[ProcessingInfo]; - + If Not ValueIsFilled(Information) Then Return Response; EndIf; - + ProcessingStatus = Information["state"]; - + If Not ValueIsFilled(ProcessingStatus) Then Return Response; Else Return ProcessingStatus; - EndIf; - + EndIf; + EndFunction #EndRegion diff --git a/src/en/OPI/src/CommonModules/OPI_TypeConversion/Module.bsl b/src/en/OPI/src/CommonModules/OPI_TypeConversion/Module.bsl index f1b78a57db..65c20a4dba 100644 --- a/src/en/OPI/src/CommonModules/OPI_TypeConversion/Module.bsl +++ b/src/en/OPI/src/CommonModules/OPI_TypeConversion/Module.bsl @@ -39,268 +39,268 @@ #Region Internal Procedure GetBinaryData(Value) Export - + If Value = Undefined Then Return; EndIf; - - Try - + + Try + If TypeOf(Value) = Type("BinaryData") Then Return; Else - + File = New File(Value); - + If File.Exists() Then Value = New BinaryData(Value); - + ElsIf StrFind(Value, "//") Then - + Value = OPI_Tools.Get(Value); - + Else - + Value = Base64Value(Value); - + EndIf; - + EndIf; - + Except Raise "Error getting binary data from parameter: " + ErrorDescription(); EndTry; - + EndProcedure Procedure GetBinaryOrStream(Value) Export - + If Value = Undefined Then Return; EndIf; - + If TypeOf(Value) <> Type("String") Then GetBinaryData(Value); Return; EndIf; - + File = New File(Value); - + If File.Exists() Then - Value = New FileStream(Value, FileOpenMode.Open); + Value = New FileStream(Value, FileOpenMode.Open); Else GetBinaryData(Value); EndIf; - + EndProcedure Procedure GetCollection(Value) Export - + If Value = Undefined Then Return; EndIf; - - Try - + + Try + InitialValue = Value; - + If ThisIsCollection(Value) Then Return; Else - + If TypeOf(Value) = Type("BinaryData") Then - Value = GetStringFromBinaryData(Value); + Value = GetStringFromBinaryData(Value); Else - Value = OPI_Tools.NumberToString(Value); + Value = OPI_Tools.NumberToString(Value); EndIf; - - File = New File(Value); + + File = New File(Value); JSONReader = New JSONReader; - + If File.Exists() Then - + JSONReader.OpenFile(Value); - + ElsIf StrStartsWith(Lower(Value), "http") Then - + TFN = GetTempFileName(); FileCopy(Value, TFN); JSONReader.OpenFile(TFN); JSONReader.Read(); - + DeleteFiles(TFN); - + Else - + JSONReader.SetString(TrimAll(Value)); - + EndIf; - + Value = ReadJSON(JSONReader, True, Undefined, JSONDateFormat.ISO); JSONReader.Close(); - + If (Not ThisIsCollection(Value)) Or Not ValueIsFilled(Value) Then - + Value = InitialValue; GetArray(Value); - + EndIf; - + EndIf; - + Except - + Value = InitialValue; - GetArray(Value); - + GetArray(Value); + EndTry; - + EndProcedure Procedure GetArray(Value) Export - + If TypeOf(Value) = Type("Array") Then Return; EndIf; - - If TypeOf(Value) = Type("String") + + If TypeOf(Value) = Type("String") And StrStartsWith(Value, "[") And StrEndsWith(Value, "]") Then - + CommaInQuotes = "','"; - - Value = StrReplace(Value, "['" , ""); - Value = StrReplace(Value, "']" , ""); + + Value = StrReplace(Value, "['" , ""); + Value = StrReplace(Value, "']" , ""); Value = StrReplace(Value, "', '" , CommaInQuotes); Value = StrReplace(Value, "' , '", CommaInQuotes); Value = StrReplace(Value, "' ,'" , CommaInQuotes); - + Value = StrSplit(Value, CommaInQuotes, False); - - For N = 0 To Value.UBound() Do + + For N = 0 To Value.UBound() Do Value[N] = TrimAll(Value[N]); EndDo; - + Else - + If TypeOf(Value) = Type("Number") Then - Value = OPI_Tools.NumberToString(Value); + Value = OPI_Tools.NumberToString(Value); EndIf; - + OPI_Tools.ValueToArray(Value); - + EndIf; - + EndProcedure Procedure GetBoolean(Value) Export - + If Value = Undefined Then Return; EndIf; - - Try - + + Try + If TypeOf(Value) = Type("Boolean") Then Return; Else - Value = Boolean(Value); + Value = Boolean(Value); EndIf; - + Except Raise "Error getting boolean data from parameter"; EndTry; - + EndProcedure Procedure GetLine(Value, Val FromSource = False) Export - + If Value = Undefined Then Return; EndIf; - - Try - + + Try + If ThisIsSymbolic(Value) Then - + If Not FromSource Then Value = OPI_Tools.NumberToString(Value); - Return; + Return; EndIf; - - Value = OPI_Tools.NumberToString(Value); - File = New File(Value); - + + Value = OPI_Tools.NumberToString(Value); + File = New File(Value); + If File.Exists() Then - + TextReader = New TextReader(Value); - Value = TextReader.Read(); + Value = TextReader.Read(); TextReader.Close(); - + ElsIf StrStartsWith(Lower(Value), "http") Then - + TFN = GetTempFileName(); FileCopy(Value, TFN); - + TextReader = New TextReader(TFN); - Value = TextReader.Read(); + Value = TextReader.Read(); TextReader.Close(); - + DeleteFiles(TFN); - + Else - + Return; - + EndIf; - + ElsIf TypeOf(Value) = Type("BinaryData") Then - + Value = GetStringFromBinaryData(Value); - + ElsIf ThisIsCollection(Value) Then - - Value = OPI_Tools.JSONString(Value); - + + Value = OPI_Tools.JSONString(Value); + Else Return; EndIf; - + Except Value = String(Value); Return; EndTry; - + EndProcedure Procedure GetDate(Value) Export - + If Value = Undefined Then Return; EndIf; - + Date = "Date"; - - Try - + + Try + If TypeOf(Value) = Type(Date) Then Return; - Else - Value = XMLValue(Type(Date), Value); + Else + Value = XMLValue(Type(Date), Value); EndIf; - + Except - OOD = New TypeDescription(Date); + OOD = New TypeDescription(Date); Value = OOD.AdjustValue(Value); EndTry; - + EndProcedure Procedure GetNumber(Value) Export - + TypeDescription = New TypeDescription("Number"); - Value = TypeDescription.AdjustValue(Value); - + Value = TypeDescription.AdjustValue(Value); + EndProcedure #EndRegion @@ -308,19 +308,19 @@ EndProcedure #Region Private Function ThisIsCollection(Val Value) - - Return TypeOf(Value) = Type("Array") + + Return TypeOf(Value) = Type("Array") Or TypeOf(Value) = Type("Structure") Or TypeOf(Value) = Type("Map"); - -EndFunction + +EndFunction Function ThisIsSymbolic(Val Value) - - Return TypeOf(Value) = Type("String") - Or TypeOf(Value) = Type("Number") + + Return TypeOf(Value) = Type("String") + Or TypeOf(Value) = Type("Number") Or TypeOf(Value) = Type("Date"); - -EndFunction + +EndFunction #EndRegion diff --git a/src/en/OPI/src/CommonModules/OPI_VK/Module.bsl b/src/en/OPI/src/CommonModules/OPI_VK/Module.bsl index dc801062bc..315d3bef04 100644 --- a/src/en/OPI/src/CommonModules/OPI_VK/Module.bsl +++ b/src/en/OPI/src/CommonModules/OPI_VK/Module.bsl @@ -22,7 +22,7 @@ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. +// SOFTWARE. // https://github.com/Bayselonarrend/OpenIntegrations // If you don't know where to start, you should find the GetStandardParameters method() @@ -51,37 +51,37 @@ // Create token retrieval link // Getting a link for interactive token retrieval (access_token), which is necessary // for further actions -// +// // Parameters: // app_id - String, Number - app_id from application settings - app -// +// // Returns: -// String - URL to go to in the browser +// String - URL to go to in the browser Function CreateTokenRetrievalLink(Val App_id) Export - + OPI_TypeConversion.GetLine(App_id); - + // access_token will need to be taken from the parameter in the browser address bar Return "https://oauth.vk.com/authorize?client_id=" + App_id + "&scope=offline,wall,groups,photos,stats,stories,ads,market,video" + "&v=5.131&response_type=token&redirect_uri=https://api.vk.com/blank.html"; - + EndFunction - + #EndRegion #Region CommunityManagment // Create post // Creates a post with images -// +// // Parameters: // Text - String - Post text - text -// ImageArray - Array of String, BinaryData - Array of images - pictures +// ImageArray - Array of String, BinaryData - Array of images - pictures // Advertisement - Boolean - Sign ""This is an ad"" - ad // LinkUnderPost - String - Link (URL) under the post - url // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function CreatePost(Val Text @@ -89,49 +89,49 @@ Function CreatePost(Val Text , Val Advertisement = False , Val LinkUnderPost = "" , Val Parameters = "") Export - + OPI_TypeConversion.GetCollection(ImageArray); - - Parameters_ = GetStandardParameters(Parameters); - AttachmentsArray = New Array; - + + Parameters_ = GetStandardParameters(Parameters); + AttachmentsArray = New Array; + For Each PostImage In ImageArray Do - + Parameters_ = GetStandardParameters(Parameters); ResponseMap = GetImageMap(PostImage, Parameters_, "Post"); - - OwnerId = ResponseMap.Get("owner_id"); + + OwnerId = ResponseMap.Get("owner_id"); ObjectId = ResponseMap.Get("id"); - + If Not ValueIsFilled(OwnerId) Or Not ValueIsFilled(ObjectId) Then Return ResponseMap; EndIf; - - OwnerId = OPI_Tools.NumberToString(OwnerId); + + OwnerId = OPI_Tools.NumberToString(OwnerId); ObjectId = OPI_Tools.NumberToString(ObjectId); - - PhotoID = "photo" + OwnerId + "_" + ObjectId; + + PhotoID = "photo" + OwnerId + "_" + ObjectId; AttachmentsArray.Add(PhotoID); - + EndDo; Response = CreateCompositePost(Text, AttachmentsArray, Advertisement, LinkUnderPost, Parameters); - + Return Response; - + EndFunction // Create composite post // Creates a post based on an array of object identifiers (images, videos, etc..) -// +// // Parameters: // Text - String - Post text - text -// Objects - Array of String - Array of identifiers like photo123_123 - objects +// Objects - Array of String - Array of identifiers like photo123_123 - objects // Advertisement - Boolean - Sign ""This is an ad"" - ad // LinkUnderPost - String - Link (URL) under the post - url // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function CreateCompositePost(Val Text @@ -139,24 +139,24 @@ Function CreateCompositePost(Val Text , Val Advertisement = False , Val LinkUnderPost = "" , Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Text); - OPI_TypeConversion.GetLine(LinkUnderPost); + OPI_TypeConversion.GetLine(LinkUnderPost); OPI_TypeConversion.GetBoolean(Advertisement); - - Parameters = GetStandardParameters(Parameters); - AttachmentsString = StrConcat(Objects, ","); + + Parameters = GetStandardParameters(Parameters); + AttachmentsString = StrConcat(Objects, ","); AttachmentsString = AttachmentsString + LinkUnderPost; - - Parameters.Insert("message" , Text); - Parameters.Insert("attachments" , AttachmentsString); - Parameters.Insert("mark_as_ads" , ?(Advertisement, 1, 0)); + + Parameters.Insert("message" , Text); + Parameters.Insert("attachments" , AttachmentsString); + Parameters.Insert("mark_as_ads" , ?(Advertisement, 1, 0)); Parameters.Insert("close_comments" , ?(Advertisement, 1, 0)); Response = OPI_Tools.Get("api.vk.com/method/wall.post", Parameters); - + Return Response; - + EndFunction // Delete post @@ -165,20 +165,20 @@ EndFunction // Parameters: // PostID - String, Number - Post ID - post // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function DeletePost(Val PostID, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(PostID); - - Parameters_ = GetStandardParameters(Parameters); + + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("post_id", PostID); - + Response = OPI_Tools.Get("api.vk.com/method/wall.delete", Parameters_); - + Return Response; - + EndFunction // Create poll @@ -189,72 +189,72 @@ EndFunction // AnswersArray - Array of String - Array of answer options - options // Image - String, BinaryData - Poll image - picture // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function CreatePoll(Val Question, Val AnswersArray, Val Image = "", Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Question); OPI_TypeConversion.GetCollection(AnswersArray); - + Parameters_ = GetStandardParameters(Parameters); - Response_ = "response"; + Response_ = "response"; If ValueIsFilled(Image) Then - + Response = UploadPhotoToServer(Image, Parameters_, "Poll"); - + Photo = Response.Get(Response_); - + If ValueIsFilled(Photo) Then - + PhotoID = Photo["id"]; - + If Not ValueIsFilled(PhotoID) Then Return Response; EndIf; - + Else Return Response; EndIf; - + EndIf; - + Parameters_.Insert("is_anonymous", 1); Parameters_.Insert("is_multiple" , 0); - + Answers = StrConcat(AnswersArray, ""","""); - Answers = "[""" + Answers + """]"; - + Answers = "[""" + Answers + """]"; + Parameters_.Insert("add_answers", Answers); - Parameters_.Insert("photo_id" , OPI_Tools.NumberToString(PhotoID)); - Parameters_.Insert("question" , Question); - - Poll = OPI_Tools.Get("api.vk.com/method/polls.create", Parameters_); + Parameters_.Insert("photo_id" , OPI_Tools.NumberToString(PhotoID)); + Parameters_.Insert("question" , Question); + + Poll = OPI_Tools.Get("api.vk.com/method/polls.create", Parameters_); PollMap = Poll.Get(Response_); - + If Not ValueIsFilled(PollMap) Then Return Poll; EndIf; - - OwnerId = PollMap.Get("owner_id"); + + OwnerId = PollMap.Get("owner_id"); ObjectId = PollMap.Get("id"); - + If Not ValueIsFilled(OwnerId) Or Not ValueIsFilled(ObjectId) Then Return Poll; EndIf; - + PollID = "poll" + OPI_Tools.NumberToString(OwnerId) - + "_" + + "_" + OPI_Tools.NumberToString(ObjectId); - + Parameters_.Insert("attachments", PollID); - + Response = OPI_Tools.Get("api.vk.com/method/wall.post", Parameters_); - + Return Response; - + EndFunction // Create album @@ -264,24 +264,24 @@ EndFunction // Name - String - Album name - title // Description - String - Album description - description // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function CreateAlbum(Val Name, Val Description = "", Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Name); OPI_TypeConversion.GetLine(Description); - + Parameters_ = GetStandardParameters(Parameters); - - Parameters_.Insert("title" , Name); - Parameters_.Insert("description" , Description); + + Parameters_.Insert("title" , Name); + Parameters_.Insert("description" , Description); Parameters_.Insert("upload_by_admins_only", 1); - + Response = OPI_Tools.Get("api.vk.com/method/photos.createAlbum", Parameters_); - + Return Response; - + EndFunction // Delete album @@ -290,20 +290,20 @@ EndFunction // Parameters: // AlbumID - String, Number - Album ID - album // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function DeleteAlbum(Val AlbumID, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(AlbumID); - - Parameters_ = GetStandardParameters(Parameters); + + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("album_id", OPI_Tools.NumberToString(AlbumID)); - + Response = OPI_Tools.Get("api.vk.com/method/photos.deleteAlbum", Parameters_); - + Return Response; - + EndFunction // Create story @@ -313,187 +313,187 @@ EndFunction // Image - String, BinaryData - Story background - picture // URL - String - URL for button under the story - url // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function CreateStory(Val Image, Val URL = "", Val Parameters = "") Export - + OPI_TypeConversion.GetLine(URL); - + Parameters_ = GetStandardParameters(Parameters); - Parameters_.Insert("link_text" , "more"); - Parameters_.Insert("link_url" , URL); + Parameters_.Insert("link_text" , "more"); + Parameters_.Insert("link_url" , URL); Parameters_.Insert("add_to_news", "1"); - - Response = UploadPhotoToServer(Image, Parameters_, "Story"); + + Response = UploadPhotoToServer(Image, Parameters_, "Story"); Return Response; - + EndFunction // Save image to album // Saves an image to the community album // // Parameters: -// AlbumID - String, Number - Album ID - album +// AlbumID - String, Number - Album ID - album // Image - BinaryData,String - Image file - picture // Description - String - Image description - description // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function SaveImageToAlbum(Val AlbumID, Val Image, Val Description = "", Val Parameters = "") Export - + OPI_TypeConversion.GetLine(AlbumID); OPI_TypeConversion.GetLine(Description); - + Parameters_ = GetStandardParameters(Parameters); - + Parameters_.Insert("album_id", AlbumID); Parameters_.Insert("caption" , Description); - + Return UploadPhotoToServer(Image, Parameters_, "Album"); - + EndFunction // Delete image // Deletes an image from the album // // Parameters: -// ImageID - String, Number - Image ID - pictureid +// ImageID - String, Number - Image ID - pictureid // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function DeleteImage(Val ImageID, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(ImageID); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("photo_id", ImageID); - + Response = OPI_Tools.Get("api.vk.com/method/photos.delete", Parameters_); - + Return Response; - + EndFunction // Upload video to server // Uploads video to the group for further use -// +// // Parameters: // Video - String, BinaryData - Video file - file // Name - String - Video name - title // Description - String - Video description - description // Album - String - Album ID, if necessary - album // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: -// Map Of KeyAndValue - Serialized JSON response from VK +// Map Of KeyAndValue - Serialized JSON response from VK Function UploadVideoToServer(Val Video , Val Name , Val Description = "" , Val Album = "" , Val Parameters = "") Export - - String_ = "String"; + + String_ = "String"; Parameters = GetStandardParameters(Parameters); - - OPI_Tools.AddField("name" , Name, String_, Parameters); + + OPI_Tools.AddField("name" , Name , String_, Parameters); OPI_Tools.AddField("description", Description , String_, Parameters); - OPI_Tools.AddField("album_id" , Album , String_, Parameters); - + OPI_Tools.AddField("album_id" , Album , String_, Parameters); + Response = OPI_Tools.Get("api.vk.com/method/video.save", Parameters); - + Result = Response["response"]; - + If Not ValueIsFilled(Result) Then Return Response; EndIf; - + URL = Result["upload_url"]; - + If Not ValueIsFilled(URL) Then Return Response; EndIf; - + FileMapping = New Map; OPI_Tools.AddField("video_file.mp4", Video, "BinaryData", FileMapping); - + DataSize = FileMapping["video_file.mp4"].Size(); DataSize = OPI_Tools.NumberToString(DataSize); - + Response = OPI_Tools.PostMultipart(URL, , FileMapping, "video/mp4"); - + Return Response; - + EndFunction // Upload photo to server // Uploads photo to server for further use -// +// // Parameters: // Image - String, BinaryData - Image file - file // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json // View - String - Upload type (Post, Product, Story, Poll, Other) - type -// +// // Returns: -// Map Of KeyAndValue - Serialized JSON response from VK +// Map Of KeyAndValue - Serialized JSON response from VK Function UploadPhotoToServer(Val Image, Val Parameters = "", Val View = "Post") Export - + Parameters = GetStandardParameters(Parameters); - Method = DetermineImageUploadMethod(View); - Files = New Map; - + Method = DetermineImageUploadMethod(View); + Files = New Map; + Response_ = "response"; - URL = "api.vk.com/method/"; - Upload = URL + Method["Upload"]; - Save = URL + Method["Save"]; - + URL = "api.vk.com/method/"; + Upload = URL + Method["Upload"]; + Save = URL + Method["Save"]; + If TypeOf(Image) = Type("String") Then - ImageKey = StrReplace(Image, ".", "___"); + ImageKey = StrReplace(Image, ".", "___"); OPI_TypeConversion.GetBinaryData(Image); Else - ImageKey = "image___jpeg"; + ImageKey = "image___jpeg"; EndIf; - + Files.Insert(ImageKey, Image); - + For N = 1 To 5 Do - - Response = OPI_Tools.Get(Upload, Parameters); - Result = Response[Response_]; - + + Response = OPI_Tools.Get(Upload, Parameters); + Result = Response[Response_]; + If ValueIsFilled(Result) Then - + URL = Result["upload_url"]; - + If Not ValueIsFilled(URL) Then Return Response; EndIf; - + Else Return Response; EndIf; - + Parameters.Insert("upload_url", URL); Response = OPI_Tools.PostMultipart(URL, Parameters, Files); - + If TypeOf(Response) = Type("Map") Then Break; EndIf; - + EndDo; - + If TypeOf(Response) <> Type("Map") Then Return GetStringFromBinaryData(Response); EndIf; FillPhotoUploadParameters(Method, Response, Parameters); - + Response = OPI_Tools.Get(Save, Parameters); - + Return Response; - + EndFunction #EndRegion @@ -507,22 +507,22 @@ EndFunction // Name - String - Discussion name - title // FirstMessageText - String - Text of the first message - text // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function CreateDiscussion(Val Name, Val FirstMessageText, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Name); OPI_TypeConversion.GetLine(FirstMessageText); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("title", Name); Parameters_.Insert("text" , FirstMessageText); - + Response = OPI_Tools.Get("api.vk.com/method/board.addTopic", Parameters_); - + Return Response; - + EndFunction // Close discussion @@ -532,20 +532,20 @@ EndFunction // DiscussionID - String, Number - Discussion ID - topic // DeleteCompletely - Boolean - Delete completely (True) or close - remove // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function CloseDiscussion(Val DiscussionID, Val DeleteCompletely = False, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(DiscussionID); OPI_TypeConversion.GetBoolean(DeleteCompletely); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("topic_id", DiscussionID); - - Method = ?(DeleteCompletely, "deleteTopic", "closeTopic"); + + Method = ?(DeleteCompletely, "deleteTopic", "closeTopic"); Response = OPI_Tools.Get("api.vk.com/method/board." + Method, Parameters_); - + Return Response; EndFunction @@ -556,18 +556,18 @@ EndFunction // Parameters: // DiscussionID - String, Number - Discussion ID - topic // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function OpenDiscussion(Val DiscussionID, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(DiscussionID); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("topic_id", DiscussionID); - + Response = OPI_Tools.Get("api.vk.com/method/board.openTopic", Parameters_); - + Return Response; EndFunction @@ -579,20 +579,20 @@ EndFunction // DiscussionID - String, Number - Discussion ID - topic // Text - String - Message text - text // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function WriteInDiscussion(Val DiscussionID, Val Text, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(DiscussionID); OPI_TypeConversion.GetLine(Text); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("topic_id", DiscussionID); Parameters_.Insert("message" , Text); - + Response = OPI_Tools.Get("api.vk.com/method/board.createComment", Parameters_); - + Return Response; EndFunction @@ -608,26 +608,26 @@ EndFunction // PostID - String, Number - Post ID - post // WallID - String, Number - ID of the wall where the post is located - wall // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function LikePost(Val PostID, Val WallID = "", Val Parameters = "") Export - + OPI_TypeConversion.GetLine(PostID); OPI_TypeConversion.GetLine(WallID); - + Parameters_ = GetStandardParameters(Parameters); - WallID = ?(ValueIsFilled(WallID), WallID, Parameters_["owner_id"]); - VKObject = "wall" + WallID + "_" + OPI_Tools.NumberToString(PostID); - - Parameters_.Insert("type" , "post"); - Parameters_.Insert("object" , VKObject); - Parameters_.Insert("item_id" , OPI_Tools.NumberToString(PostID)); - Parameters_.Insert("owner_id" , OPI_Tools.NumberToString(WallID)); + WallID = ?(ValueIsFilled(WallID), WallID, Parameters_["owner_id"]); + VKObject = "wall" + WallID + "_" + OPI_Tools.NumberToString(PostID); + + Parameters_.Insert("type" , "post"); + Parameters_.Insert("object" , VKObject); + Parameters_.Insert("item_id" , OPI_Tools.NumberToString(PostID)); + Parameters_.Insert("owner_id" , OPI_Tools.NumberToString(WallID)); Parameters_.Insert("from_group" , 0); - + Response = OPI_Tools.Get("api.vk.com/method/likes.add", Parameters_); - + Return Response; EndFunction @@ -641,7 +641,7 @@ EndFunction // TargetWall - String, Number - ID of the target wall or group - to // Advertising - Boolean - Sign of an advertising post - ad // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function MakeRepost(Val PostID @@ -649,25 +649,25 @@ Function MakeRepost(Val PostID , Val TargetWall = "" , Val Advertising = False , Val Parameters = "") Export - + Parameters_ = GetStandardParameters(Parameters); - GroupId = Parameters_["group_id"]; - + GroupId = Parameters_["group_id"]; + OPI_TypeConversion.GetLine(GroupId); OPI_TypeConversion.GetLine(PostID); OPI_TypeConversion.GetLine(WallID); OPI_TypeConversion.GetLine(TargetWall); OPI_TypeConversion.GetBoolean(Advertising); - - Source = ?(ValueIsFilled(WallID), WallID, GroupId); + + Source = ?(ValueIsFilled(WallID), WallID, GroupId); Receiver = ?(ValueIsFilled(TargetWall), TargetWall, GroupId); - Parameters_.Insert("object" , "wall" + Source + "_" + OPI_Tools.NumberToString(PostID)); - Parameters_.Insert("group_id" , StrReplace(Receiver, "-", "")); - Parameters_.Insert("mark_as_ads" , ?(Advertising, 1, 0)); - + Parameters_.Insert("object" , "wall" + Source + "_" + OPI_Tools.NumberToString(PostID)); + Parameters_.Insert("group_id" , StrReplace(Receiver, "-", "")); + Parameters_.Insert("mark_as_ads" , ?(Advertising , 1 , 0)); + Response = OPI_Tools.Get("api.vk.com/method/wall.repost", Parameters_); - + Return Response; EndFunction @@ -681,7 +681,7 @@ EndFunction // Communitytoken - String - Community chat bot token, which can be obtained in the settings - ct // Keyboard - String - JSON keyboard. See FormKeyboard - keyboard // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function WriteMessage(Val Text @@ -689,27 +689,27 @@ Function WriteMessage(Val Text , Val Communitytoken , Val Keyboard = "" , Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Text); OPI_TypeConversion.GetLine(UserID); OPI_TypeConversion.GetLine(Communitytoken); OPI_TypeConversion.GetLine(Keyboard); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("access_token", Communitytoken); - - Parameters_.Insert("user_id" , UserID); - Parameters_.Insert("peer_id" , UserID); - Parameters_.Insert("parse_mode" , "Markdown"); - Parameters_.Insert("random_id" , 0); - Parameters_.Insert("message" , Text); - + + Parameters_.Insert("user_id" , UserID); + Parameters_.Insert("peer_id" , UserID); + Parameters_.Insert("parse_mode" , "Markdown"); + Parameters_.Insert("random_id" , 0); + Parameters_.Insert("message" , Text); + If ValueIsFilled(Keyboard) Then Parameters_.Insert("keyboard", Keyboard); EndIf; - + Response = OPI_Tools.Get("api.vk.com/method/messages.send", Parameters_); - + Return Response; EndFunction @@ -722,28 +722,28 @@ EndFunction // WallID - String, Number - ID of the wall where the post is located - wall // Text - String - Comment text - text // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function WriteComment(Val PostID, Val WallID, Val Text, Val Parameters = "") Export Parameters_ = GetStandardParameters(Parameters); - GroupId = Parameters_["group_id"]; - + GroupId = Parameters_["group_id"]; + OPI_TypeConversion.GetLine(GroupId); OPI_TypeConversion.GetLine(PostID); OPI_TypeConversion.GetLine(WallID); OPI_TypeConversion.GetLine(Text); - - Parameters_.Insert("owner_id" , WallID); + + Parameters_.Insert("owner_id" , WallID); Parameters_.Insert("from_group" , GroupId); - Parameters_.Insert("post_id" , PostID); - Parameters_.Insert("message" , Text); - + Parameters_.Insert("post_id" , PostID); + Parameters_.Insert("message" , Text); + Parameters_.Delete("group_id"); - + Response = OPI_Tools.Get("api.vk.com/method/wall.createComment", Parameters_); - + Return Response; EndFunction @@ -754,35 +754,35 @@ EndFunction // Parameters: // URL - String - URL for shortening - url // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: -// String - Shortened URL +// String - Shortened URL Function ShortenLink(Val URL, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(URL); - - Response_ = "response"; + + Response_ = "response"; Parameters_ = New Structure; - Parameters_ = GetStandardParameters(Parameters); + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("url", URL); - + Response = OPI_Tools.Get("https://api.vk.com/method/utils.getShortLink", Parameters_); - Result = Response[Response_]; - + Result = Response[Response_]; + If ValueIsFilled(Result) Then - + URL = Result["short_url"]; - + If ValueIsFilled(URL) Then Return URL; Else Return Response; EndIf; - + Else Return Response; EndIf; - + EndFunction #EndRegion @@ -796,27 +796,27 @@ EndFunction // StartDate - Date - Start date of the period - datefrom // EndDate - Date - End date of the period - dateto // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function GetStatistics(Val StartDate, Val EndDate, Val Parameters = "") Export - + OPI_TypeConversion.GetDate(StartDate); OPI_TypeConversion.GetDate(EndDate); - + Parameters_ = GetStandardParameters(Parameters); - + StartDate = OPI_Tools.UNIXTime(StartDate); - EndDate = OPI_Tools.UNIXTime(EndDate); - + EndDate = OPI_Tools.UNIXTime(EndDate); + Parameters_.Insert("timestamp_from", StartDate); - Parameters_.Insert("timestamp_to" , EndDate); - Parameters_.Insert("stats_groups" , "visitors, reach, activity"); - + Parameters_.Insert("timestamp_to" , EndDate); + Parameters_.Insert("stats_groups" , "visitors, reach, activity"); + Response = OPI_Tools.Get("api.vk.com/method/stats.get", Parameters_); - + Return Response; - + EndFunction // Get post statistics @@ -825,47 +825,47 @@ EndFunction // Parameters: // PostIDsArray - Array of String,Number - Array of post IDs - posts // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Array of Arbitrary - Array of post statistics data Function GetPostStatistics(Val PostIDsArray, Val Parameters = "") Export - + OPI_TypeConversion.GetCollection(PostIDsArray); - - Parameters_ = GetStandardParameters(Parameters); + + Parameters_ = GetStandardParameters(Parameters); AnswersArray = New Array; - SetsArray = New Array; + SetsArray = New Array; MaximumPosts = 30; - Response_ = "response"; - + Response_ = "response"; + For Each Post In PostIDsArray Do - + SetsArray.Add(OPI_Tools.NumberToString(Post)); - + If SetsArray.Count() = MaximumPosts Then - + NumbersString = StrConcat(SetsArray, ","); Parameters_.Insert("post_ids", NumbersString); - - Statistics = OPI_Tools.Get("api.vk.com/method/stats.getPostReach", Parameters_); + + Statistics = OPI_Tools.Get("api.vk.com/method/stats.getPostReach", Parameters_); StatisticsArray = Statistics[Response_]; - + For Each StatisticsItem In StatisticsArray Do AnswersArray.Add(StatisticsItem); EndDo; - + SetsArray = New Array; - + EndIf; - + EndDo; - + NumbersString = StrConcat(SetsArray, ","); Parameters_.Insert("post_ids", NumbersString); - - Statistics = OPI_Tools.Get("api.vk.com/method/stats.getPostReach", Parameters_); + + Statistics = OPI_Tools.Get("api.vk.com/method/stats.getPostReach", Parameters_); StatisticsArray = Statistics[Response_]; - + If TypeOf(StatisticsArray) = Type("Array") Then For Each StatisticsItem In StatisticsArray Do AnswersArray.Add(StatisticsItem); @@ -873,9 +873,9 @@ Function GetPostStatistics(Val PostIDsArray, Val Parameters = "") Export EndIf; Return AnswersArray; - + EndFunction - + #EndRegion #Region AdAccountManagement @@ -887,43 +887,43 @@ EndFunction // AccountID - String, Number - Advertising account ID - cabinet // Name - String - Campaign name - title // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function CreateAdvertisingCampaign(Val AccountID, Val Name, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(AccountID); OPI_TypeConversion.GetLine(Name); - + CurrentDate = OPI_Tools.GetCurrentDate(); - EndDate = AddMonth(CurrentDate, 24); - - Parameters_ = GetStandardParameters(Parameters); + EndDate = AddMonth(CurrentDate, 24); + + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("account_id", AccountID); - + StructuresArray = New Array; - StartDate = OPI_Tools.UNIXTime(CurrentDate); - EndDate = OPI_Tools.UNIXTime(EndDate); - + StartDate = OPI_Tools.UNIXTime(CurrentDate); + EndDate = OPI_Tools.UNIXTime(EndDate); + CampaignStructure = New Structure; - CampaignStructure.Insert("type" , "promoted_posts"); - CampaignStructure.Insert("name" , Name); - CampaignStructure.Insert("day_limit" , 0); - CampaignStructure.Insert("all_limit" , 0); + CampaignStructure.Insert("type" , "promoted_posts"); + CampaignStructure.Insert("name" , Name); + CampaignStructure.Insert("day_limit" , 0); + CampaignStructure.Insert("all_limit" , 0); CampaignStructure.Insert("start_time" , StartDate); - CampaignStructure.Insert("stop_time" , EndDate); - CampaignStructure.Insert("status" , 1); - + CampaignStructure.Insert("stop_time" , EndDate); + CampaignStructure.Insert("status" , 1); + StructuresArray.Add(CampaignStructure); - + JSONDate = OPI_Tools.JSONString(StructuresArray); - + Parameters_.Insert("data", JSONDate); - + Response = OPI_Tools.Get("api.vk.com/method/ads.createCampaigns", Parameters_); - + Return Response; - + EndFunction // Create advertising post @@ -936,7 +936,7 @@ EndFunction // PostID - String, Number - ID of the post used for advertising - post // AccountID - String, Number - Advertising account ID - cabinet // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function CreateAd(Val CampaignNumber @@ -945,49 +945,49 @@ Function CreateAd(Val CampaignNumber , Val PostID , Val AccountID , Val Parameters = "") Export - - Parameters_ = GetStandardParameters(Parameters); - GroupId = Parameters_["group_id"]; - + + Parameters_ = GetStandardParameters(Parameters); + GroupId = Parameters_["group_id"]; + OPI_TypeConversion.GetLine(GroupId); OPI_TypeConversion.GetLine(CampaignNumber); OPI_TypeConversion.GetLine(DailyLimit); OPI_TypeConversion.GetLine(CategoryNumber); OPI_TypeConversion.GetLine(PostID); OPI_TypeConversion.GetLine(AccountID); - + Link = "https://vk.com/wall-" + GroupId + "_" + PostID; - - StructuresArray = New Array; + + StructuresArray = New Array; CampaignStructure = New Structure; - CampaignStructure.Insert("campaign_id" , CampaignNumber); - CampaignStructure.Insert("ad_format" , 9); - CampaignStructure.Insert("conversion_event_id" , 1); - CampaignStructure.Insert("autobidding" , 1); - CampaignStructure.Insert("cost_type" , 3); - CampaignStructure.Insert("goal_type" , 2); - CampaignStructure.Insert("ad_platform" , "all"); - CampaignStructure.Insert("publisher_platforms" , "vk"); + CampaignStructure.Insert("campaign_id" , CampaignNumber); + CampaignStructure.Insert("ad_format" , 9); + CampaignStructure.Insert("conversion_event_id" , 1); + CampaignStructure.Insert("autobidding" , 1); + CampaignStructure.Insert("cost_type" , 3); + CampaignStructure.Insert("goal_type" , 2); + CampaignStructure.Insert("ad_platform" , "all"); + CampaignStructure.Insert("publisher_platforms" , "vk"); CampaignStructure.Insert("publisher_platforms_auto" , "1"); - CampaignStructure.Insert("day_limit" , DailyLimit); - CampaignStructure.Insert("all_limit" , "0"); - CampaignStructure.Insert("category1_id" , CategoryNumber); - CampaignStructure.Insert("age_restriction" , 0); - CampaignStructure.Insert("status" , 1); - CampaignStructure.Insert("name" , "Ad"); - CampaignStructure.Insert("link_url" , Link); - + CampaignStructure.Insert("day_limit" , DailyLimit); + CampaignStructure.Insert("all_limit" , "0"); + CampaignStructure.Insert("category1_id" , CategoryNumber); + CampaignStructure.Insert("age_restriction" , 0); + CampaignStructure.Insert("status" , 1); + CampaignStructure.Insert("name" , "Ad"); + CampaignStructure.Insert("link_url" , Link); + StructuresArray.Add(CampaignStructure); - + OPI_TypeConversion.GetLine(StructuresArray, True); - - Parameters_.Insert("data" , StructuresArray); + + Parameters_.Insert("data" , StructuresArray); Parameters_.Insert("account_id" , AccountID); - + Response = OPI_Tools.Get("api.vk.com/method/ads.createAds", Parameters_); - + Return Response; - + EndFunction // Pause advertising post @@ -995,36 +995,36 @@ EndFunction // // Parameters: // AccountID - String, Number - Advertising account ID - cabinet -// AdID - String, Number - Ad ID - adv +// AdID - String, Number - Ad ID - adv // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function PauseAdvertising(Val AccountID, Val AdID, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(AccountID); OPI_TypeConversion.GetLine(AdID); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("account_id", AccountID); - - StructuresArray = New Array; + + StructuresArray = New Array; CampaignStructure = New Structure; - - CampaignStructure.Insert("ad_id" , AdID); + + CampaignStructure.Insert("ad_id" , AdID); CampaignStructure.Insert("status" , 0); - + StructuresArray.Add(CampaignStructure); - + OPI_TypeConversion.GetLine(StructuresArray, True); - + Parameters_.Insert("data", StructuresArray); - + Response = OPI_Tools.Get("api.vk.com/method/ads.updateAds", Parameters_); - + Return Response; - + EndFunction // Get a list of advertising categories @@ -1032,14 +1032,14 @@ EndFunction // // Parameters: // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function GetAdvertisingCategoryList(Val Parameters = "") Export - + Parameters_ = GetStandardParameters(Parameters); - Response = OPI_Tools.Get("api.vk.com/method/ads.getCategories", Parameters_); - + Response = OPI_Tools.Get("api.vk.com/method/ads.getCategories", Parameters_); + Return Response; EndFunction @@ -1053,52 +1053,52 @@ EndFunction // // Parameters: // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of String - Key - ID, Value - Name Function GetProductCategoryList(Val Parameters = "") Export - - Response_ = "response"; + + Response_ = "response"; Parameters_ = GetStandardParameters(Parameters); - Response = OPI_Tools.Get("api.vk.com/method/market.getCategories", Parameters_); - Result = Response[Response_]; - + Response = OPI_Tools.Get("api.vk.com/method/market.getCategories", Parameters_); + Result = Response[Response_]; + If ValueIsFilled(Result) Then - + Count = Result["count"]; - + If Not ValueIsFilled(Count) Then Return Response; EndIf; - + Else Return Response; EndIf; - + Parameters_.Insert("count", Count); - Response = OPI_Tools.Get("api.vk.com/method/market.getCategories", Parameters_); - Result = Response[Response_]; - + Response = OPI_Tools.Get("api.vk.com/method/market.getCategories", Parameters_); + Result = Response[Response_]; + If ValueIsFilled(Result) Then - + Categories = Result["items"]; - + If Not ValueIsFilled(Categories) Then Return Response; EndIf; - + Else Return Response; EndIf; - + CategoryMap = New Map; - - For Each Category In Categories Do + + For Each Category In Categories Do CategoryMap.Insert(Category["id"], Category["name"]); EndDo; - + Return CategoryMap; - + EndFunction // Get product list @@ -1107,60 +1107,60 @@ EndFunction // Parameters: // Selection - String, Number - Selection ID, if filtering is needed - sel // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Array of product maps Function GetProductList(Val Selection = "", Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Selection); - + Parameters_ = GetStandardParameters(Parameters); - Parameters_.Insert("count" , 200); - Parameters_.Insert("extended" , 1); + Parameters_.Insert("count" , 200); + Parameters_.Insert("extended" , 1); Parameters_.Insert("with_disabled", 1); - + If ValueIsFilled(Selection) Then - Parameters_.Insert("album_id", Selection); + Parameters_.Insert("album_id", Selection); EndIf; - + ProductsArray = New Array; GetProductListRecursively(ProductsArray, Parameters_); - + Return ProductsArray; - + EndFunction // Get products by ID // Gets information about products by array of IDs // // Parameters: -// Products - String, Array of String - Array of product IDs - items +// Products - String, Array of String - Array of product IDs - items // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function GetProductsByID(Val Products, Val Parameters = "") Export - + OPI_TypeConversion.GetCollection(Products); - - Parameters_ = GetStandardParameters(Parameters); + + Parameters_ = GetStandardParameters(Parameters); ProductsString = ""; - Owner = "owner_id"; - - For Each Product In Products Do + Owner = "owner_id"; + + For Each Product In Products Do CurrentProduct = Parameters_[Owner] + "_" + Product; CurrentProduct = OPI_Tools.NumberToString(CurrentProduct); ProductsString = ProductsString + CurrentProduct + ","; EndDo; - + ProductsString = Left(ProductsString, StrLen(ProductsString) - 1); Parameters_.Insert("item_ids", ProductsString); Parameters_.Insert("extended", 1); - + Response = OPI_Tools.Get("api.vk.com/method/market.getById", Parameters_); - + Return Response; - + EndFunction // Add product @@ -1170,13 +1170,13 @@ EndFunction // ProductDescription - Map Of KeyAndValue - See GetProductDescription - product - JSON description of the product or path // Selection - String - Selection ID for placing the product, if needed - sel // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK -Function AddProduct(Val ProductDescription, Val Selection = "", Val Parameters = "") Export - - Return ProductManagement(ProductDescription, , Selection, Parameters); - +Function AddProduct(Val ProductDescription, Val Selection = "", Val Parameters = "") Export + + Return ProductManagement(ProductDescription, , Selection, Parameters); + EndFunction // Edit product @@ -1185,15 +1185,15 @@ EndFunction // Parameters: // Product - Number, String - Identifier of the product being edited - item // ProductDescription - Map Of KeyAndValue - See GetProductDescription - product - JSON description of the product or path -// Selection - String - Identifier of the new selection, if needed - sel +// Selection - String - Identifier of the new selection, if needed - sel // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function EditProduct(Val Product, Val ProductDescription, Val Selection = "", Val Parameters = "") Export - - Return ProductManagement(ProductDescription, Product, Selection, Parameters); - + + Return ProductManagement(ProductDescription, Product, Selection, Parameters); + EndFunction // Delete product @@ -1202,20 +1202,20 @@ EndFunction // Parameters: // Product - String, Number - Product ID - item // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function DeleteProduct(Val Product, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Product); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("item_id", Product); - + Response = OPI_Tools.Get("api.vk.com/method/market.delete", Parameters_); - + Return Response; - + EndFunction // Group products @@ -1225,37 +1225,37 @@ EndFunction // ProductsArray - Array Of String - Array of product IDs - items // ExistingGroup - String - ID of the existing group, if needed - sellgroup // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function GroupProducts(Val ProductsArray, Val ExistingGroup = "", Val Parameters = "") Export - + OPI_TypeConversion.GetLine(ExistingGroup); OPI_TypeConversion.GetCollection(ProductsArray); - - Parameters_ = GetStandardParameters(Parameters); + + Parameters_ = GetStandardParameters(Parameters); ArrayOfProducts_ = New Array; - + For Each Product In ProductsArray Do ArrayOfProducts_.Add(OPI_Tools.NumberToString(Product)); EndDo; - + Products = StrConcat(ArrayOfProducts_, ","); - + Parameters_.Insert("item_ids", Products); - + If ValueIsFilled(ExistingGroup) Then Parameters_.Insert("item_group_id", ExistingGroup); EndIf; - + Response = OPI_Tools.Get("api.vk.com/method/market.groupItems", Parameters_); - + Return Response; EndFunction // Get product description. !NOCLI -// +// // Returns: // Map Of KeyAndValue - Empty product description: // *Name - String - Product name @@ -1275,27 +1275,27 @@ EndFunction // *SKU - String - SKU // *AvailableBalance - Number - Balance. -1 - unlimited Function GetProductDescription() Export - + Product = New Map(); - Product.Insert("Name" , "New product"); // Product name - Product.Insert("Description" , "Product description"); // Product description - Product.Insert("Category" , "20173"); // See GetProductCategoryList() - Product.Insert("Price" , 1); // Price. - Product.Insert("OldPrice" , Undefined); // For reflection change price - Product.Insert("MainPhoto" , Undefined); // BD or path to main. photo - Product.Insert("URL" , Undefined); // Link to page store + Product.Insert("Name" , "New product"); // Product name + Product.Insert("Description" , "Product description"); // Product description + Product.Insert("Category" , "20173"); // See GetProductCategoryList() + Product.Insert("Price" , 1); // Price. + Product.Insert("OldPrice" , Undefined); // For reflection change price + Product.Insert("MainPhoto" , Undefined); // BD or path to main. photo + Product.Insert("URL" , Undefined); // Link to page store Product.Insert("AdditionalPhotos" , New Array); // Array paths or BD for add. photo - Product.Insert("PropertyValues" , New Array); // Values properties (variants). Maximum 2 - Product.Insert("MainInGroup" , False); // Make main in of its group - Product.Insert("Width" , Undefined); // In millimeters - Product.Insert("Height" , Undefined); // In millimeters - Product.Insert("Depth" , Undefined); // In millimeters - Product.Insert("Weight" , Undefined); // In grams - Product.Insert("SKU" , Undefined); // SKU + Product.Insert("PropertyValues" , New Array); // Values properties (variants). Maximum 2 + Product.Insert("MainInGroup" , False); // Make main in of its group + Product.Insert("Width" , Undefined); // In millimeters + Product.Insert("Height" , Undefined); // In millimeters + Product.Insert("Depth" , Undefined); // In millimeters + Product.Insert("Weight" , Undefined); // In grams + Product.Insert("SKU" , Undefined); // SKU Product.Insert("AvailableBalance" , 1); - + Return Product; - + EndFunction #EndRegion @@ -1307,19 +1307,19 @@ EndFunction // // Parameters: // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Array of selection maps Function GetSelectionList(Val Parameters = "") Export - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("count", 100); - + ArrayOfAlbums = New Array; GetAlbumListRecursively(ArrayOfAlbums, Parameters_); - + Return ArrayOfAlbums; - + EndFunction // Get selections by ID @@ -1328,29 +1328,29 @@ EndFunction // Parameters: // Selections - String, Array of String - Selection IDs - sels // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function GetSelectionsByID(Val Selections, Val Parameters = "") Export - + OPI_TypeConversion.GetCollection(Selections); - - Parameters_ = GetStandardParameters(Parameters); - Selections_ = New Array; + + Parameters_ = GetStandardParameters(Parameters); + Selections_ = New Array; SelectionsString = ""; - + For Each Selection In Selections Do - Selections_.Add(OPI_Tools.NumberToString(Selection)); - EndDo; - + Selections_.Add(OPI_Tools.NumberToString(Selection)); + EndDo; + SelectionsString = StrConcat(Selections_, ","); - + Parameters_.Insert("album_ids", SelectionsString); - + Response = OPI_Tools.Get("api.vk.com/method/market.getAlbumById", Parameters_); - + Return Response; - + EndFunction // Create product selection @@ -1362,7 +1362,7 @@ EndFunction // Main - Boolean - Main - main // Hidden - Boolean - Hidden - hidden // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function CreateProductCollection(Val Name @@ -1370,9 +1370,9 @@ Function CreateProductCollection(Val Name , Val Main = False , Val Hidden = False , Val Parameters = "") Export - + Return SelectionManagement(Name, Image, , Main, Hidden, Parameters); - + EndFunction // Edit product selection @@ -1385,7 +1385,7 @@ EndFunction // Main - Boolean - Main - main // Hidden - Boolean - Hidden - hidden // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function EditProductCollection(Val Name @@ -1394,9 +1394,9 @@ Function EditProductCollection(Val Name , Val Main = False , Val Hidden = False , Val Parameters = "") Export - + Return SelectionManagement(Name, Image, Selection, Main, Hidden, Parameters); - + EndFunction // Add product to selection @@ -1406,56 +1406,56 @@ EndFunction // ProductsArray - Array of string, number - Array of products or product - items // Selection - String - Selection ID - sel // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function AddProductToCollection(Val ProductsArray, Val Selection, Val Parameters = "") Export - + OPI_TypeConversion.GetCollection(ProductsArray); OPI_TypeConversion.GetLine(Selection); - - Parameters_ = GetStandardParameters(Parameters); + + Parameters_ = GetStandardParameters(Parameters); ArrayOfProducts_ = New Array; - + For Each Product In ProductsArray Do - ArrayOfProducts_.Add(OPI_Tools.NumberToString(Product)); - EndDo; - + ArrayOfProducts_.Add(OPI_Tools.NumberToString(Product)); + EndDo; + ProductList = StrConcat(ArrayOfProducts_, ","); - + Parameters_.Insert("item_ids" , ProductList); Parameters_.Insert("album_ids", Selection); - + Response = OPI_Tools.Get("api.vk.com/method/market.addToAlbum", Parameters_); - + Return Response; - + EndFunction // Remove product from selection // Removes a previously added product from the selection -// +// // Parameters: // Product - String - Product ID - item // Selection - String - Selection ID - sel // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function RemoveProductFromSelection(Val Product, Val Selection, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Product); OPI_TypeConversion.GetLine(Selection); Parameters_ = GetStandardParameters(Parameters); - - Parameters_.Insert("item_id" , Product); + + Parameters_.Insert("item_id" , Product); Parameters_.Insert("album_ids", Selection); - + Response = OPI_Tools.Get("api.vk.com/method/market.removeFromAlbum", Parameters_); - + Return Response; - + EndFunction // Delete selection @@ -1464,20 +1464,20 @@ EndFunction // Parameters: // Selection - String - Selection ID - sel // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: // Map Of KeyAndValue - Serialized JSON response from VK Function DeleteSelection(Val Selection, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Selection); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("album_id", Selection); - + Response = OPI_Tools.Get("api.vk.com/method/market.deleteAlbum", Parameters_); - + Return Response; - + EndFunction #EndRegion @@ -1486,167 +1486,167 @@ EndFunction // Get property list // Gets the list of properties of group products -// +// // Parameters: // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: -// Map Of KeyAndValue - Serialized JSON response from VK +// Map Of KeyAndValue - Serialized JSON response from VK Function GetPropertyList(Val Parameters = "") Export - - Response_ = "response"; + + Response_ = "response"; Parameters_ = GetStandardParameters(Parameters); - - Response = OPI_Tools.Get("api.vk.com/method/market.getProperties", Parameters_); + + Response = OPI_Tools.Get("api.vk.com/method/market.getProperties", Parameters_); Properties = Response[Response_]["items"]; - + Return Properties; - + EndFunction // Create product property // Creates a new property for use in products -// +// // Parameters: // Name - String - Property name - title // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: -// Map Of KeyAndValue - Serialized JSON response from VK +// Map Of KeyAndValue - Serialized JSON response from VK Function CreateProductProperty(Val Name, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Name); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("title", Name); - - Response = OPI_Tools.Get("api.vk.com/method/market.addProperty", Parameters_); - + + Response = OPI_Tools.Get("api.vk.com/method/market.addProperty", Parameters_); + Return Response; EndFunction // Edit product property // Edits the existing product property -// +// // Parameters: // Name - String - New name - title // Property - String, Number - Property ID - prop // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: -// Map Of KeyAndValue - Serialized JSON response from VK +// Map Of KeyAndValue - Serialized JSON response from VK Function EditProductProperty(Val Name, Val Property, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Name); OPI_TypeConversion.GetLine(Property); - + Parameters_ = GetStandardParameters(Parameters); - Parameters_.Insert("title" , Name); + Parameters_.Insert("title" , Name); Parameters_.Insert("property_id", Property); - Parameters_.Insert("type" , "text"); - - Response = OPI_Tools.Get("api.vk.com/method/market.editProperty", Parameters_); - + Parameters_.Insert("type" , "text"); + + Response = OPI_Tools.Get("api.vk.com/method/market.editProperty", Parameters_); + Return Response; EndFunction // Delete product property // Deletes the existing product property -// +// // Parameters: // Property - String, Number - Property ID - prop // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: -// Map Of KeyAndValue - Serialized JSON response from VK +// Map Of KeyAndValue - Serialized JSON response from VK Function DeleteProductProperty(Val Property, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Property); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("property_id", Property); - + Response = OPI_Tools.Get("api.vk.com/method/market.deleteProperty", Parameters_); - + Return Response; - + EndFunction // Add product property variant // Adds a variant for an existing property -// +// // Parameters: // Value - String - Property value - value // Property - String, Number - Property ID where the variant is added - prop // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: -// Map Of KeyAndValue - Serialized JSON response from VK +// Map Of KeyAndValue - Serialized JSON response from VK Function AddProductPropertyVariant(Val Value, Val Property, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Property); OPI_TypeConversion.GetLine(Value); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("property_id", Property); - Parameters_.Insert("title" , Value); - + Parameters_.Insert("title" , Value); + Response = OPI_Tools.Get("api.vk.com/method/market.addPropertyVariant", Parameters_); - + Return Response; - + EndFunction // Edit product property variant // Edits the value of an existing product property variant -// +// // Parameters: // Value - String - New property value - value // Property - String, Number - Property ID - prop // Option - String, Number - Variant ID - option // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: -// Map Of KeyAndValue - Serialized JSON response from VK +// Map Of KeyAndValue - Serialized JSON response from VK Function EditProductPropertyVariant(Val Value, Val Property, Val Option, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Value); OPI_TypeConversion.GetLine(Property); OPI_TypeConversion.GetLine(Option); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("property_id", Property); Parameters_.Insert("variant_id" , Option); - Parameters_.Insert("title" , Value); - + Parameters_.Insert("title" , Value); + Response = OPI_Tools.Get("api.vk.com/method/market.editPropertyVariant", Parameters_); - + Return Response; - + EndFunction // Delete product property variant // Deletes the previously created product property variant -// +// // Parameters: // Option - String, Number - Variant ID - option // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: -// Map Of KeyAndValue - Serialized JSON response from VK +// Map Of KeyAndValue - Serialized JSON response from VK Function DeleteProductPropertyVariant(Val Option, Val Parameters = "") Export - + OPI_TypeConversion.GetLine(Option); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("variant_id", Option); - + Response = OPI_Tools.Get("api.vk.com/method/market.deletePropertyVariant", Parameters_); - + Return Response; - + EndFunction #EndRegion @@ -1655,22 +1655,22 @@ EndFunction // Get order list // Returns the community's order list -// +// // Parameters: // Parameters - Structure Of String - See GetStandardParameters - auth - Authorization JSON or path to .json -// +// // Returns: -// Map Of KeyAndValue - Serialized JSON response from VK +// Map Of KeyAndValue - Serialized JSON response from VK Function GetOrderList(Val Parameters = "") Export - + Parameters = GetStandardParameters(Parameters); Parameters.Insert("count", 50); - + ArrayOfOrders = New Array; GetOrderListRecursively(ArrayOfOrders, Parameters); - + Return ArrayOfOrders; - + EndFunction #EndRegion @@ -1679,40 +1679,40 @@ EndFunction // Create keyboard // Forms a keyboard from an array of buttons -// +// // Parameters: // ButtonArray - Array of String - Array of button titles - buttons -// +// // Returns: // String - Keyboard JSON Function FormKeyboard(Val ButtonArray) Export - - OPI_TypeConversion.GetCollection(ButtonArray); - - Keyboard = New Structure; + + OPI_TypeConversion.GetCollection(ButtonArray); + + Keyboard = New Structure; KeyboardArray = New Array; - ArrayBlock = New Array; - + ArrayBlock = New Array; + For Each Action In ButtonArray Do - - Button = New Structure; - Expression = New Structure; - + + Button = New Structure; + Expression = New Structure; + Expression.Insert("type" , "text"); Expression.Insert("label", Action); - + Button.Insert("action", Expression); ArrayBlock.Add(Button); - + EndDo; - + KeyboardArray.Add(ArrayBlock); - - Keyboard.Insert("buttons" , KeyboardArray); + + Keyboard.Insert("buttons" , KeyboardArray); Keyboard.Insert("one_time", False); - + Return OPI_Tools.JSONString(Keyboard); - + EndFunction #EndRegion @@ -1722,29 +1722,29 @@ EndFunction #Region Private Function GetStandardParameters(Val Parameters = "") - + // Here is a collection of data definitions for working with the VK API // You can override them by passing them as a parameter // Matching fields will be overwritten with the parameter of the function - + Parameters_ = New Structure; - + // access_token - can be obtained in the browser via the URL from the CreateTokenRetrievalLink function() // from_group - actions will be performed on behalf of the group // owner_id - group ID with "-" at the beginning. Can be found in the settings of the VK group or in its URL if not set // set your // app_id - application ID that needs to be created in the profile on the developer page // group_id - owner_id, but without "-" - + Parameters_.Insert("access_token" , ""); - Parameters_.Insert("from_group" , "1"); - Parameters_.Insert("owner_id" , ""); - Parameters_.Insert("v" , "5.131"); - Parameters_.Insert("app_id" , ""); - Parameters_.Insert("group_id" , ""); - + Parameters_.Insert("from_group" , "1"); + Parameters_.Insert("owner_id" , ""); + Parameters_.Insert("v" , "5.131"); + Parameters_.Insert("app_id" , ""); + Parameters_.Insert("group_id" , ""); + OPI_TypeConversion.GetCollection(Parameters); - + If TypeOf(Parameters) = Type("Structure") Or TypeOf(Parameters) = Type("Map") Then For Each PassedParameter In Parameters Do Parameters_.Insert(PassedParameter.Key, OPI_Tools.NumberToString(PassedParameter.Value)); @@ -1756,32 +1756,32 @@ Function GetStandardParameters(Val Parameters = "") EndFunction Function GetImageID(Val Image, Val Parameters, Val View) - - Response_ = "response"; + + Response_ = "response"; Response = UploadPhotoToServer(Image, Parameters, View); - Result = Response[Response_]; + Result = Response[Response_]; If ValueIsFilled(Result) Then PhotoID = Result["photo_id"]; - + If Not ValueIsFilled(PhotoID) Then - Return Response; + Return Response; EndIf; - + Else Return Response; EndIf; - + PhotoID = OPI_Tools.NumberToString(PhotoID); Return PhotoID; - + EndFunction Function GetImageMap(Val Image, Val Parameters, Val View) - - Response = UploadPhotoToServer(Image, Parameters, View); + + Response = UploadPhotoToServer(Image, Parameters, View); ResponseArray = Response.Get("response"); - + If Not ValueIsFilled(ResponseArray) Or Not TypeOf(ResponseArray) = Type("Array") Then Return Response; Else @@ -1791,407 +1791,407 @@ Function GetImageMap(Val Image, Val Parameters, Val View) ResponseMap = ResponseArray[0]; EndIf; EndIf; - + Return ResponseMap; - + EndFunction Function GetSelectionArray(Val Selections, Val Parameters = "") - - Response_ = "response"; + + Response_ = "response"; Selections = GetSelectionsByID(Selections, Parameters); - Result = Selections[Response_]; - + Result = Selections[Response_]; + If ValueIsFilled(Result) Then - + SelectionArray = Result["items"]; - + If Not ValueIsFilled(SelectionArray) Then - Return Selections; + Return Selections; EndIf; - + Else Return Selections; EndIf; - + Return SelectionArray; - + EndFunction Function DetermineImageUploadMethod(Val View) - + MethodMap = New Map; - Upload = "Upload"; - Save = "Save"; - Way = "Way"; - Photo = "Photo"; - + Upload = "Upload"; + Save = "Save"; + Way = "Way"; + Photo = "Photo"; + If View = "Post" Then - + MethodMap.Insert(Upload , "photos.getWallUploadServer"); - MethodMap.Insert(Save, "photos.saveWallPhoto"); - MethodMap.Insert(Photo , "photo"); - MethodMap.Insert(Way , 1); - + MethodMap.Insert(Save , "photos.saveWallPhoto"); + MethodMap.Insert(Photo , "photo"); + MethodMap.Insert(Way , 1); + ElsIf View = "Product" Then - + MethodMap.Insert(Upload , "market.getProductPhotoUploadServer"); - MethodMap.Insert(Save, "market.saveProductPhoto"); - MethodMap.Insert(Way , 2); - + MethodMap.Insert(Save , "market.saveProductPhoto"); + MethodMap.Insert(Way , 2); + ElsIf View = "Story" Then - + MethodMap.Insert(Upload , "stories.getPhotoUploadServer"); - MethodMap.Insert(Save, "stories.save"); - MethodMap.Insert(Way , 3); - + MethodMap.Insert(Save , "stories.save"); + MethodMap.Insert(Way , 3); + ElsIf View = "Poll" Then - + MethodMap.Insert(Upload , "polls.getPhotoUploadServer"); - MethodMap.Insert(Save, "polls.savePhoto"); - MethodMap.Insert(Photo , "photo"); - MethodMap.Insert(Way , 1); - + MethodMap.Insert(Save , "polls.savePhoto"); + MethodMap.Insert(Photo , "photo"); + MethodMap.Insert(Way , 1); + Else - + MethodMap.Insert(Upload , "photos.getUploadServer"); - MethodMap.Insert(Save, "photos.save"); - MethodMap.Insert(Photo , "photos_list"); - MethodMap.Insert(Way , 1); - + MethodMap.Insert(Save , "photos.save"); + MethodMap.Insert(Photo , "photos_list"); + MethodMap.Insert(Way , 1); + EndIf; - + Return MethodMap; - + EndFunction Function GetProductParameterMapping() - + Fields = New Map(); - Fields.Insert("Name" , "name"); - Fields.Insert("Description" , "description"); - Fields.Insert("Category" , "category_id"); - Fields.Insert("Price" , "price"); - Fields.Insert("OldPrice" , "old_price"); - Fields.Insert("URL" , "url"); - Fields.Insert("MainInGroup" , "is_main_variant"); - Fields.Insert("Width" , "dimension_width"); - Fields.Insert("Height" , "dimension_height"); - Fields.Insert("Depth" , "dimension_length"); - Fields.Insert("Weight" , "weight"); - Fields.Insert("SKU" , "sku"); + Fields.Insert("Name" , "name"); + Fields.Insert("Description" , "description"); + Fields.Insert("Category" , "category_id"); + Fields.Insert("Price" , "price"); + Fields.Insert("OldPrice" , "old_price"); + Fields.Insert("URL" , "url"); + Fields.Insert("MainInGroup" , "is_main_variant"); + Fields.Insert("Width" , "dimension_width"); + Fields.Insert("Height" , "dimension_height"); + Fields.Insert("Depth" , "dimension_length"); + Fields.Insert("Weight" , "weight"); + Fields.Insert("SKU" , "sku"); Fields.Insert("AvailableBalance" , "stock_amount"); - + Return Fields; EndFunction Function ProductManagement(Val ProductDescription, Val ProductID = "", Val Selection = "", Val Parameters = "") - + OPI_TypeConversion.GetLine(ProductID); OPI_TypeConversion.GetLine(Selection); OPI_TypeConversion.GetCollection(ProductDescription); - + Parameters_ = GetStandardParameters(Parameters); Parameters_.Insert("v", "5.199"); - + Response_ = "response"; - + FillProductRequestFields(ProductDescription, Parameters_); - - If ValueIsFilled(ProductID) Then + + If ValueIsFilled(ProductID) Then Parameters_.Insert("item_id", ProductID); - Method = "edit"; - Else + Method = "edit"; + Else Method = "add"; EndIf; - + Response = OPI_Tools.Get("api.vk.com/method/market." + Method, Parameters_); - Result = Response[Response_]; - - If Not ValueIsFilled(ProductID) And ValueIsFilled(Result) Then - + Result = Response[Response_]; + + If Not ValueIsFilled(ProductID) And ValueIsFilled(Result) Then + ProductID = Result["market_item_id"]; - + If Not ValueIsFilled(ProductID) Then - Return Response; + Return Response; EndIf; - + Else Return Response; EndIf; - + If ValueIsFilled(Selection) And ValueIsFilled(ProductID) Then AddProductToCollection(ProductID, Selection, Parameters_); EndIf; - + Return Response; EndFunction Function SelectionManagement(Val Name - , Val Image = "" + , Val Image = "" , Val SelectionID = "" - , Val Main = False - , Val Hidden = False - , Val Parameters = "") - + , Val Main = False + , Val Hidden = False + , Val Parameters = "") + OPI_TypeConversion.GetLine(Name); OPI_TypeConversion.GetLine(SelectionID); OPI_TypeConversion.GetBoolean(Main); OPI_TypeConversion.GetBoolean(Hidden); - - Parameters_ = GetStandardParameters(Parameters); - Response = AddImageParameter(Image, SelectionID, Parameters_); - + + Parameters_ = GetStandardParameters(Parameters); + Response = AddImageParameter(Image, SelectionID, Parameters_); + If ValueIsFilled(Response) Then Return Response; EndIf; - - Parameters_.Insert("title" , Name); - Parameters_.Insert("main_album" , ?(Main, 1, 0)); - Parameters_.Insert("is_hidden" , ?(Hidden, 1, 0)); - - If ValueIsFilled(SelectionID) Then + + Parameters_.Insert("title" , Name); + Parameters_.Insert("main_album" , ?(Main , 1, 0)); + Parameters_.Insert("is_hidden" , ?(Hidden, 1, 0)); + + If ValueIsFilled(SelectionID) Then Parameters_.Insert("album_id", SelectionID); - Method = "editAlbum"; - Else + Method = "editAlbum"; + Else Method = "addAlbum"; EndIf; - + Response = OPI_Tools.Get("api.vk.com/method/market." + Method, Parameters_); - + Return Response; EndFunction Function AddImageParameter(Val Image, Val SelectionID, Parameters) - + PhotoID_ = "photo_id"; - + If ValueIsFilled(Image) Then - + PhotoID = GetImageID(Image, Parameters, "Product"); - + If Not TypeOf(PhotoID) = Type("String") Then - Return PhotoID; + Return PhotoID; EndIf; - + Parameters.Insert(PhotoID_, PhotoID); - + Else - + If ValueIsFilled(SelectionID) Then - + Selections = GetSelectionArray(SelectionID, Parameters); - + If Not TypeOf(Selections) = Type("Array") Then - Return Selections; + Return Selections; EndIf; - - If Not Selections.Count() = 0 Then + + If Not Selections.Count() = 0 Then PhotoID = Selections[0]["photo"]["id"]; OPI_TypeConversion.GetLine(PhotoID); Parameters.Insert(PhotoID_, PhotoID); EndIf; - + EndIf; - + EndIf; - + Return ""; - + EndFunction Procedure FillPhotoUploadParameters(Val Method, Val Response, Parameters) - - Response_ = "response"; - Way = Method["Way"]; + + Response_ = "response"; + Way = Method["Way"]; StandardMethod = 1; - NewMethod = 2; + NewMethod = 2; If Way = StandardMethod Then - - Hash = "hash"; - Serv = "server"; - Aid = "aid"; + + Hash = "hash"; + Serv = "server"; + Aid = "aid"; Photo = Method["Photo"]; - - Parameters.Insert(Hash, Response[Hash]); + + Parameters.Insert(Hash , Response[Hash]); Parameters.Insert(Photo, Response[Photo]); - + PhotoServer = Response.Get(Serv); - + If ValueIsFilled(PhotoServer) Then PhotoServer = OPI_Tools.NumberToString(PhotoServer); - Parameters.Insert(Serv, PhotoServer); + Parameters.Insert(Serv, PhotoServer); EndIf; - + Identifier = Response.Get(Aid); - + If ValueIsFilled(Identifier) Then Identifier = OPI_Tools.NumberToString(Identifier); - Parameters.Insert(Aid , Identifier); + Parameters.Insert(Aid , Identifier); EndIf; - + ElsIf Way = NewMethod Then - + ResponseString = OPI_Tools.JSONString(Response); Parameters.Insert("upload_response", ResponseString); - + Else - + Parameters.Insert("upload_results", Response[Response_]["upload_result"]); - + EndIf; EndProcedure Procedure FillProductRequestFields(Val ProductDescription, Parameters) - - Response_ = "response"; - MainPhoto = ProductDescription["MainPhoto"]; + + Response_ = "response"; + MainPhoto = ProductDescription["MainPhoto"]; AdditionalPhoto = ProductDescription["AdditionalPhotos"]; - Properties = ProductDescription["PropertyValues"]; - + Properties = ProductDescription["PropertyValues"]; + If ValueIsFilled(MainPhoto) Then - + Response = UploadPhotoToServer(MainPhoto, Parameters, "Product"); - Result = Response[Response_]; - + Result = Response[Response_]; + If ValueIsFilled(Result) Then PhotoID = Result["photo_id"]; - + If Not ValueIsFilled(PhotoID) Then - Return; + Return; EndIf; - + Else Return; EndIf; - + PhotoID = OPI_Tools.NumberToString(PhotoID); - Parameters.Insert("main_photo_id", PhotoID); - + Parameters.Insert("main_photo_id", PhotoID); + EndIf; - - If TypeOf(Properties) = Type("Array") Then - + + If TypeOf(Properties) = Type("Array") Then + Properties_ = New Array; - + For Each Property In Properties Do - Properties_.Add(OPI_Tools.NumberToString(Property)); + Properties_.Add(OPI_Tools.NumberToString(Property)); EndDo; - - Properties = StrConcat(Properties_, ","); - + + Properties = StrConcat(Properties_, ","); + EndIf; - + If ValueIsFilled(Properties) Then - Parameters.Insert("variant_ids", OPI_Tools.NumberToString(Properties)); + Parameters.Insert("variant_ids", OPI_Tools.NumberToString(Properties)); EndIf; - + AddAdditionalProductPhotos(AdditionalPhoto, Parameters); - + For Each Field In GetProductParameterMapping() Do - + Value = ProductDescription[Field.Key]; - + If Value <> Undefined Then Parameters.Insert(Field.Value, ProductDescription[Field.Key]); EndIf; - + EndDo; EndProcedure Procedure AddAdditionalProductPhotos(Val PhotoArray, Parameters) - + If TypeOf(PhotoArray) = Type("Array") Then If PhotoArray.Count() > 0 Then - + PhotoString = ""; - + For Each Photo In PhotoArray Do - + PhotoID = GetImageID(Photo, Parameters, "Product"); - + If Not TypeOf(PhotoID) = Type("String") Then - Return; + Return; EndIf; - PhotoString = PhotoString + PhotoID + ","; - + PhotoString = PhotoString + PhotoID + ","; + EndDo; - + PhotoString = Left(PhotoString, StrLen(PhotoString) - 1); Parameters.Insert("photo_ids", PhotoString); EndIf; EndIf; - + EndProcedure Procedure GetProductListRecursively(ProductsArray, Parameters, Shift = 0) - - Response_ = "response"; + + Response_ = "response"; MaxInRequest = 200; - Response = OPI_Tools.Get("api.vk.com/method/market.get", Parameters); - Products = Response[Response_]["items"]; - + Response = OPI_Tools.Get("api.vk.com/method/market.get", Parameters); + Products = Response[Response_]["items"]; + If Products.Count() = 0 Then Return; - EndIf; - + EndIf; + For Each Product In Products Do ProductsArray.Add(Product); EndDo; - + Shift = Shift + MaxInRequest; Parameters.Insert("offset", Shift); GetProductListRecursively(ProductsArray, Parameters, Shift); - + EndProcedure Procedure GetAlbumListRecursively(ArrayOfAlbums, Parameters, Shift = 0) - - Response_ = "response"; + + Response_ = "response"; MaxInRequest = 100; - Response = OPI_Tools.Get("api.vk.com/method/market.getAlbums", Parameters); - Albums = Response[Response_]["items"]; - + Response = OPI_Tools.Get("api.vk.com/method/market.getAlbums", Parameters); + Albums = Response[Response_]["items"]; + If Albums.Count() = 0 Then Return; - EndIf; - + EndIf; + For Each Album In Albums Do ArrayOfAlbums.Add(Album); EndDo; - + Shift = Shift + MaxInRequest; Parameters.Insert("offset", Shift); GetAlbumListRecursively(ArrayOfAlbums, Parameters, Shift); - + EndProcedure Procedure GetOrderListRecursively(ArrayOfOrders, Parameters, Shift = 0) - - Response_ = "response"; + + Response_ = "response"; MaxInRequest = 50; - Response = OPI_Tools.Get("api.vk.com/method/market.getGroupOrders", Parameters); - Orders = Response[Response_]["items"]; - + Response = OPI_Tools.Get("api.vk.com/method/market.getGroupOrders", Parameters); + Orders = Response[Response_]["items"]; + If Orders.Count() = 0 Then Return; - EndIf; - + EndIf; + For Each Order In Orders Do ArrayOfOrders.Add(Order); EndDo; - + Shift = Shift + MaxInRequest; Parameters.Insert("offset", Shift); GetOrderListRecursively(ArrayOfOrders, Parameters, Shift); - + EndProcedure #EndRegion diff --git a/src/en/OPI/src/CommonModules/OPI_Viber/Module.bsl b/src/en/OPI/src/CommonModules/OPI_Viber/Module.bsl index bf9a23ca13..180f90315b 100644 --- a/src/en/OPI/src/CommonModules/OPI_Viber/Module.bsl +++ b/src/en/OPI/src/CommonModules/OPI_Viber/Module.bsl @@ -23,7 +23,7 @@ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. - + // https://github.com/Bayselonarrend/OpenIntegrations // BSLLS:LatinAndCyrillicSymbolInWord-off @@ -46,55 +46,55 @@ // which will return 200 and a genuine SSL certificate. If there is a certificate and the database is published // on the server - you can use an HTTP service. Information about new messages will also be sent there // Viber periodically knocks on the Webhook address, so if it is inactive, everything will stop working -// +// // Parameters: // Token - String - Viber Token - token // URL - String - URL for setting up Webhook - url -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Viber Function SetWebhook(Val Token, Val URL) Export - + Parameters = New Structure; - OPI_Tools.AddField("url" , URL , "String", Parameters); + OPI_Tools.AddField("url" , URL , "String", Parameters); OPI_Tools.AddField("auth_token" , Token, "String", Parameters); - + Return OPI_Tools.Post("https://chatapi.viber.com/pa/set_webhook", Parameters); - + EndFunction // Get channel information // Here you can get the channel's user IDs. Bot IDs need to be obtained from the Webhook arrivals // The user ID from channel information is not suitable for sending messages through the bot - they are different -// +// // Parameters: // Token - String - Token - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Viber Function GetChannelInformation(Val Token) Export - - URL = "https://chatapi.viber.com/pa/get_account_info"; + + URL = "https://chatapi.viber.com/pa/get_account_info"; Return OPI_Tools.Get(URL, , TokenInHeaders(Token)); - + EndFunction // Get user data // Gets user information by ID -// +// // Parameters: // Token - String - Token - token // UserID - String, Number - Viber User ID - user -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Viber Function GetUserData(Val Token, Val UserID) Export - + URL = "https://chatapi.viber.com/pa/get_user_details"; - + Parameters = New Structure; OPI_Tools.AddField("id", UserID, "String", Parameters); - + Response = OPI_Tools.Post(URL, Parameters, TokenInHeaders(Token)); Return Response; @@ -103,22 +103,22 @@ EndFunction // Get online users // Gets the status of a user or multiple users by ID -// +// // Parameters: // Token - String - Viber Token - token // UserIDs - String,Number,Array of String,Number - Viber User(s) ID - users -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Viber Function GetOnlineUsers(Val Token, Val UserIDs) Export - + URL = "https://chatapi.viber.com/pa/get_online"; - + Parameters = New Structure; OPI_Tools.AddField("ids", UserIDs, "Collection", Parameters); - + Response = OPI_Tools.Post(URL, Parameters, TokenInHeaders(Token)); - + Return Response; EndFunction @@ -129,14 +129,14 @@ EndFunction // Send text message // Sends a text message to a chat or channel -// +// // Parameters: // Token - String - Token - token // Text - String - Message text - text // UserID - String, Number - User ID. For channel > administrator, for bot > recipient - user // SendingToChannel - Boolean - Sending to channel or bot chat - ischannel // Keyboard - Structure Of String - See CreateKeyboardFromArrayButton - keyboard -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Viber Function SendTextMessage(Val Token @@ -144,40 +144,40 @@ Function SendTextMessage(Val Token , Val UserID , Val SendingToChannel , Val Keyboard = "") Export - - Return SendMessage(Token, "text", UserID, SendingToChannel, , Text, Keyboard); - + + Return SendMessage(Token, "text", UserID, SendingToChannel, , Text, Keyboard); + EndFunction // Send image // Sends an image to a chat or channel -// +// // Parameters: // Token - String - Token - token // URL - String - Image URL - picture // UserID - String, Number - User ID. For channel > administrator, for bot > recipient - user // SendingToChannel - boolean - Sending to channel or bot chat - ischannel // Description - String - Image annotation - description -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Viber Function SendImage(Val Token, Val URL, Val UserID, Val SendingToChannel, Val Description = "") Export - + Return SendMessage(Token, "picture", UserID, SendingToChannel, URL, Description); - + EndFunction // SendFile // Sends a file (document) to a chat or channel -// +// // Parameters: // Token - String - Token - token -// URL - String - File URL - file -// UserID - String, Number - User ID. For channel > administrator, for bot > recipient - user +// URL - String - File URL - file +// UserID - String, Number - User ID. For channel > administrator, for bot > recipient - user // SendingToChannel - Boolean - Sending to channel or bot chat - ischannel // Extension - String - File extension - ext // Size - Number - File size. If not filled in > determined automatically by downloading the file - size -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Viber Function SendFile(Val Token @@ -186,36 +186,36 @@ Function SendFile(Val Token , Val SendingToChannel , Val Extension , Val Size = "") Export - + If Not ValueIsFilled(Size) Then - + Response = OPI_Tools.Get(URL); - Size = Response.Size(); - + Size = Response.Size(); + EndIf; - - String_ = "String"; + + String_ = "String"; Extension = StrReplace(Extension, ".", ""); - + Parameters = New Structure; - OPI_Tools.AddField("URL" , URL , String_, Parameters); - OPI_Tools.AddField("Size" , Size , String_, Parameters); + OPI_Tools.AddField("URL" , URL , String_, Parameters); + OPI_Tools.AddField("Size" , Size , String_, Parameters); OPI_Tools.AddField("Extension", Extension, String_, Parameters); - + Return SendMessage(Token, "file", UserID, SendingToChannel, Parameters); - + EndFunction // Send contact // Sends a contact with a phone number to a chat or channel -// +// // Parameters: // Token - String - Token - token // ContactName - String - Contact name - name // PhoneNumber - String - Phone number - phone -// UserID - String, Number - User ID. For channel > administrator, for bot > recipient - user +// UserID - String, Number - User ID. For channel > administrator, for bot > recipient - user // SendingToChannel - Boolean - Sending to channel or bot chat - ischannel -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Viber Function SendContact(Val Token @@ -223,91 +223,91 @@ Function SendContact(Val Token , Val PhoneNumber , Val UserID , Val SendingToChannel) Export - + Parameters = New Structure; - OPI_Tools.AddField("name" , ContactName , "String", Parameters); - OPI_Tools.AddField("phone_number", PhoneNumber, "String", Parameters); - - Return SendMessage(Token, "contact", UserID, SendingToChannel, Parameters); - + OPI_Tools.AddField("name" , ContactName , "String", Parameters); + OPI_Tools.AddField("phone_number", PhoneNumber , "String", Parameters); + + Return SendMessage(Token, "contact", UserID, SendingToChannel, Parameters); + EndFunction // Send location // Sends geographic coordinates to a chat or channel -// +// // Parameters: // Token - String - Token - token // Latitude - String, Number - Geographic latitude - lat // Longitude - String, Number - Geographic longitude - long -// UserID - String, Number - User ID. For channel > administrator, for bot > recipient - user +// UserID - String, Number - User ID. For channel > administrator, for bot > recipient - user // SendingToChannel - Boolean - Sending to channel or bot chat - ischannel -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Viber Function SendLocation(Val Token, Val Latitude, Val Longitude, Val UserID, Val SendingToChannel) Export - + Parameters = New Structure; OPI_Tools.AddField("lat", Latitude , "String", Parameters); OPI_Tools.AddField("lon", Longitude, "String", Parameters); - + Return SendMessage(Token, "location", UserID, SendingToChannel, Parameters); - + EndFunction // Send link // Sends a URL with a preview to a chat or channel -// +// // Parameters: // Token - String - Token - token // URL - String - SentLink - url -// UserID - String, Number - User ID. For channel > administrator, for bot > recipient - user +// UserID - String, Number - User ID. For channel > administrator, for bot > recipient - user // SendingToChannel - Boolean - Sending to channel or bot chat - ischannel -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Viber Function SendLink(Val Token, Val URL, Val UserID, Val SendingToChannel) Export - + Return SendMessage(Token, "url", UserID, SendingToChannel, URL); - + EndFunction // Create a keyboard from an array of buttons // Returns a keyboard structure for messages -// +// // Parameters: // ButtonArray - Array of String - Array of buttons - buttons // ButtonColor - String - HEX color of buttons with # at the beginning - color -// +// // Returns: // Structure - Create a keyboard from an array of buttons: -// * Buttons - Array of Structure - Array of formed buttons -// * Type - String - KeyboardType +// * Buttons - Array of Structure - Array of formed buttons +// * Type - String - KeyboardType Function CreateKeyboardFromArrayButton(Val ButtonArray, Val ButtonColor = "#2db9b9") Export - + OPI_TypeConversion.GetLine(ButtonColor); OPI_TypeConversion.GetCollection(ButtonArray); - + ArrayOfButtonStructures = New Array; - KeyboardStructure = New Structure; - + KeyboardStructure = New Structure; + For Each ButtonText In ButtonArray Do - + ButtonStructure = New Structure; ButtonStructure.Insert("ActionType", "reply"); ButtonStructure.Insert("ActionBody", ButtonText); - ButtonStructure.Insert("Text" , ButtonText); - ButtonStructure.Insert("BgColor" , ButtonColor); - ButtonStructure.Insert("Coloumns" , 3); - + ButtonStructure.Insert("Text" , ButtonText); + ButtonStructure.Insert("BgColor" , ButtonColor); + ButtonStructure.Insert("Coloumns" , 3); + ArrayOfButtonStructures.Add(ButtonStructure); - + EndDo; - + KeyboardStructure.Insert("Buttons", ArrayOfButtonStructures); - KeyboardStructure.Insert("Type" , "keyboard"); - + KeyboardStructure.Insert("Type" , "keyboard"); + Return KeyboardStructure; - + EndFunction #EndRegion @@ -317,7 +317,7 @@ EndFunction #Region Private // Send message. -// +// // Parameters: // Token - String - Token // Type - String - TypeOfSentMessage @@ -328,8 +328,8 @@ EndFunction // * Size - Number, String - File size in case of sending // * Extension - String - File extension in case of sending // Text - String - Message text -// Keyboard - Structure Of String - Keyboard, if needed, see CreateKeyboardFromArrayButton -// +// Keyboard - Structure Of String - Keyboard, if needed, see CreateKeyboardFromArrayButton +// // Returns: // Arbitrary, HTTPResponse - Send message Function SendMessage(Val Token @@ -339,81 +339,81 @@ Function SendMessage(Val Token , Val Value = "" , Val Text = "" , Val Keyboard = "") - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Type); OPI_TypeConversion.GetLine(UserID); OPI_TypeConversion.GetLine(Text); OPI_TypeConversion.GetBoolean(IsChannel); OPI_TypeConversion.GetCollection(Keyboard); - + ParametersStructure = ReturnStandardParameters(); - ParametersStructure.Insert("type", Type); - + ParametersStructure.Insert("type", Type); + If (Type = "text" Or Type = "picture") And ValueIsFilled(Text) Then ParametersStructure.Insert("text", Text); EndIf; - + If TypeOf(Keyboard) = Type("Structure") Then ParametersStructure.Insert("keyboard", Keyboard); EndIf; - + If ValueIsFilled(Value) Then - - If Type = "file" Then - ParametersStructure.Insert("media" , Value["URL"]); - ParametersStructure.Insert("size" , Value["Size"]); + + If Type = "file" Then + ParametersStructure.Insert("media" , Value["URL"]); + ParametersStructure.Insert("size" , Value["Size"]); ParametersStructure.Insert("file_name", "File." + Value["Extension"]); ElsIf Type = "contact" Then - ParametersStructure.Insert("contact" , Value); + ParametersStructure.Insert("contact" , Value); ElsIf Type = "location" Then ParametersStructure.Insert("location" , Value); Else - ParametersStructure.Insert("media" , Value); + ParametersStructure.Insert("media" , Value); EndIf; - + EndIf; - + If IsChannel Then - ParametersStructure.Insert("from", UserID); + ParametersStructure.Insert("from" , UserID); URL = "https://chatapi.viber.com/pa/post"; - Else + Else ParametersStructure.Insert("receiver", UserID); URL = "https://chatapi.viber.com/pa/send_message"; EndIf; - + Response = OPI_Tools.Post(URL, ParametersStructure, TokenInHeaders(Token)); - + Try Return OPI_Tools.JsonToStructure(Response.GetBodyAsBinaryData()); Except Return Response; EndTry; - + EndFunction -Function ReturnStandardParameters() - +Function ReturnStandardParameters() + SenderStructure = New Structure; - SenderStructure.Insert("name" , "Bot"); + SenderStructure.Insert("name" , "Bot"); SenderStructure.Insert("avatar", ""); - + ParametersStructure = New Structure; - ParametersStructure.Insert("sender", SenderStructure); + ParametersStructure.Insert("sender" , SenderStructure); ParametersStructure.Insert("min_api_version", 1); - + Return ParametersStructure; - + EndFunction Function TokenInHeaders(Val Token) - + OPI_TypeConversion.GetLine(Token); - + HeadersStructure = New Map; HeadersStructure.Insert("X-Viber-Auth-Token", Token); Return HeadersStructure; - + EndFunction #EndRegion diff --git a/src/en/OPI/src/CommonModules/OPI_YandexDisk/Module.bsl b/src/en/OPI/src/CommonModules/OPI_YandexDisk/Module.bsl index 19aaa4959a..c69e1d9b6f 100644 --- a/src/en/OPI/src/CommonModules/OPI_YandexDisk/Module.bsl +++ b/src/en/OPI/src/CommonModules/OPI_YandexDisk/Module.bsl @@ -37,7 +37,7 @@ //@skip-check wrong-string-literal-content // Uncomment if OneScript is executed -// #Use "../../tools" +// #Use "../../tools" #Region Public @@ -45,217 +45,217 @@ // Get disk information // Gets information about the current disk -// +// // Parameters: // Token - String - Token - token -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function GetDiskInformation(Val Token) Export - + OPI_TypeConversion.GetLine(Token); - - Headers = AuthorizationHeader(Token); + + Headers = AuthorizationHeader(Token); Response = OPI_Tools.Get("https://cloud-api.yandex.net/v1/disk", , Headers); - + Return Response; - + EndFunction // Create folder // Creates a directory on the disk -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the created folder - path -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function CreateFolder(Val Token, Val Path) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Path); - + Headers = AuthorizationHeader(Token); - URL = "https://cloud-api.yandex.net/v1/disk/resources"; - Href = "href"; - + URL = "https://cloud-api.yandex.net/v1/disk/resources"; + Href = "href"; + Parameters = New Structure; Parameters.Insert("path", Path); - - Parameters = OPI_Tools.RequestParametersToString(Parameters); - Response = OPI_Tools.Put(URL + Parameters, , Headers, False); - - ResponseURL = Response[Href]; - + + Parameters = OPI_Tools.RequestParametersToString(Parameters); + Response = OPI_Tools.Put(URL + Parameters, , Headers, False); + + ResponseURL = Response[Href]; + If Not ValueIsFilled(ResponseURL) Then - Return Response; + Return Response; EndIf; - + Response = OPI_Tools.Get(ResponseURL, , Headers); - + Return Response; EndFunction // Get object // Gets information about a disk object at the specified path -// +// // Parameters: // Token - String - Token - token // Path - String - Path to folder or file - path -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function GetObject(Val Token, Val Path) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Path); - - Headers = AuthorizationHeader(Token); + + Headers = AuthorizationHeader(Token); Parameters = New Structure; Parameters.Insert("path", Path); - + Response = OPI_Tools.Get("https://cloud-api.yandex.net/v1/disk/resources", Parameters, Headers); - + Return Response; EndFunction // Delete object // Deletes an object at the specified path -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the folder or file to be deleted - path // ToCart - Boolean - To cart - can -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function DeleteObject(Val Token, Val Path, Val ToCart = True) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Path); OPI_TypeConversion.GetBoolean(ToCart); - + Headers = AuthorizationHeader(Token); - + Parameters = New Structure; - Parameters.Insert("path" , Path); + Parameters.Insert("path" , Path); Parameters.Insert("permanently", Not ToCart); - + Response = OPI_Tools.Delete("https://cloud-api.yandex.net/v1/disk/resources", Parameters, Headers); - + Return Response; EndFunction // Create object copy // Creates a copy of the object at the specified path and path to the original -// +// // Parameters: // Token - String - Token - token // Original - String - Path to the original file or directory - from // Path - String - Destination path for the copy - to // Overwrite - Boolean - Overwrite if a file with the same name already exists - rewrite -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function CreateObjectCopy(Val Token, Val Original, Val Path, Val Overwrite = False) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Original); OPI_TypeConversion.GetLine(Path); OPI_TypeConversion.GetBoolean(Overwrite); - + Headers = AuthorizationHeader(Token); - URL = "https://cloud-api.yandex.net/v1/disk/resources/copy"; - Href = "href"; - + URL = "https://cloud-api.yandex.net/v1/disk/resources/copy"; + Href = "href"; + Parameters = New Structure; - Parameters.Insert("from" , Original); - Parameters.Insert("path" , Path); + Parameters.Insert("from" , Original); + Parameters.Insert("path" , Path); Parameters.Insert("overwrite" , Overwrite); - - Parameters = OPI_Tools.RequestParametersToString(Parameters); - Response = OPI_Tools.Post(URL + Parameters, , Headers, False); - - ResponseURL = Response[Href]; - + + Parameters = OPI_Tools.RequestParametersToString(Parameters); + Response = OPI_Tools.Post(URL + Parameters, , Headers, False); + + ResponseURL = Response[Href]; + If Not ValueIsFilled(ResponseURL) Then - Return Response; + Return Response; EndIf; - + Response = OPI_Tools.Get(ResponseURL, , Headers); - + Return Response; - + EndFunction // Get download link // Gets a download link for the file -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the file for downloading - path -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function GetDownloadLink(Val Token, Val Path) Export OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Path); - + Headers = AuthorizationHeader(Token); - + Parameters = New Structure; Parameters.Insert("path", Path); - + Response = OPI_Tools.Get("https://cloud-api.yandex.net/v1/disk/resources/download", Parameters, Headers); - + Return Response; - + EndFunction // Download file // Downloads a file at the specified path -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the file for downloading - path -// SavePath - String - File save path - out -// +// SavePath - String - File save path - out +// // Returns: // BinaryData,String - Binary data or file path when SavePath parameter is specified Function DownloadFile(Val Token, Val Path, Val SavePath = "") Export - + OPI_TypeConversion.GetLine(SavePath); Response = GetDownloadLink(Token, Path); - URL = Response["href"]; - + URL = Response["href"]; + If Not ValueIsFilled(URL) Then Return Response; EndIf; - + Response = OPI_Tools.Get(URL, , , SavePath); - + Return Response; - + EndFunction // Get list of files // Gets a list of files with or without filtering by type -// List of available types: audio, backup, book, compressed, data, development, -// diskimage, document, encoded, executable, flash, font, +// List of available types: audio, backup, book, compressed, data, development, +// diskimage, document, encoded, executable, flash, font, // mage, settings, spreadsheet, text, unknown, video, web -// +// // Parameters: // Token - String - Token - token // Count - Number, String - Number of returned objects - amount // OffsetFromStart - Number - Offset for getting objects not from the beginning of the list - offset // FilterByType - String - Filter by file type - type // SortByDate - Boolean - True > sort by date, False > alphabetically - datesort -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function GetFilesList(Val Token @@ -263,50 +263,50 @@ Function GetFilesList(Val Token , Val OffsetFromStart = 0 , Val FilterByType = "" , Val SortByDate = False) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Count); OPI_TypeConversion.GetLine(OffsetFromStart); OPI_TypeConversion.GetLine(FilterByType); OPI_TypeConversion.GetBoolean(SortByDate); - + Headers = AuthorizationHeader(Token); - + Parameters = New Structure; - + If ValueIsFilled(Count) Then Parameters.Insert("limit", OPI_Tools.NumberToString(Count)); EndIf; - + If ValueIsFilled(OffsetFromStart) Then Parameters.Insert("offset", OPI_Tools.NumberToString(OffsetFromStart)); EndIf; - + If ValueIsFilled(FilterByType) Then Parameters.Insert("media_type", FilterByType); EndIf; - + If SortByDate Then Destination = "last-uploaded"; Else Destination = "files"; EndIf; - + Response = OPI_Tools.Get("https://cloud-api.yandex.net/v1/disk/resources/" + Destination, Parameters, Headers); - + Return Response; - + EndFunction // Move object // Moves the object to the specified path and path to the original -// +// // Parameters: // Token - String - Token - token // Original - String - Path to the original file or folder - from // Path - String - Destination path for moving - to // Overwrite - Boolean - Overwrite if a file with the same name already exists - rewrite -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function MoveObject(Val Token, Val Original, Val Path, Val Overwrite = False) Export @@ -315,97 +315,97 @@ Function MoveObject(Val Token, Val Original, Val Path, Val Overwrite = False) Ex OPI_TypeConversion.GetLine(Original); OPI_TypeConversion.GetLine(Path); OPI_TypeConversion.GetBoolean(Overwrite); - + Headers = AuthorizationHeader(Token); - URL = "https://cloud-api.yandex.net/v1/disk/resources/move"; - Href = "href"; - + URL = "https://cloud-api.yandex.net/v1/disk/resources/move"; + Href = "href"; + Parameters = New Structure; - Parameters.Insert("from" , Original); - Parameters.Insert("path" , Path); + Parameters.Insert("from" , Original); + Parameters.Insert("path" , Path); Parameters.Insert("overwrite" , Overwrite); - - Parameters = OPI_Tools.RequestParametersToString(Parameters); - Response = OPI_Tools.Post(URL + Parameters, , Headers, False); - ResponseURL = Response[Href]; - + + Parameters = OPI_Tools.RequestParametersToString(Parameters); + Response = OPI_Tools.Post(URL + Parameters, , Headers, False); + ResponseURL = Response[Href]; + If Not ValueIsFilled(ResponseURL) Then - Return Response; + Return Response; EndIf; - + Response = OPI_Tools.Get(ResponseURL, , Headers); - + Return Response; - + EndFunction // Upload file // Uploads a file to disk at the specified path -// +// // Parameters: // Token - String - Token - token // Path - String - Path for saving the file to disk - path // File - String, BinaryData - File for upload - file // Overwrite - Boolean - Overwrite if a file with the same name already exists - rewrite -// +// // Returns: -// Map Of KeyAndValue - serialized JSON response from Yandex +// Map Of KeyAndValue - serialized JSON response from Yandex Function UploadFile(Val Token, Val Path, Val File, Val Overwrite = False) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Path); OPI_TypeConversion.GetBoolean(Overwrite); OPI_TypeConversion.GetBinaryData(File); - + Headers = AuthorizationHeader(Token); - Href = "href"; - File = New Structure("file", File); - + Href = "href"; + File = New Structure("file", File); + Parameters = New Structure; - Parameters.Insert("path" , Path); + Parameters.Insert("path" , Path); Parameters.Insert("overwrite" , Overwrite); - + Response = OPI_Tools.Get("https://cloud-api.yandex.net/v1/disk/resources/upload", Parameters, Headers); - URL = Response[Href]; - + URL = Response[Href]; + If Not ValueIsFilled(URL) Then - Return Response; + Return Response; EndIf; - + Response = OPI_Tools.PutMultipart(URL, New Structure(), File, "multipart", Headers); - + Return Response; - + EndFunction // Upload file by URL // Downloads a file to disk from the specified URL -// +// // Parameters: // Token - String - Token - token // Path - String - Path to place the downloaded file - path // Address - String - File URL - url -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function UploadFileByURL(Val Token, Val Path, Val Address) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Path); OPI_TypeConversion.GetLine(Address); - + Headers = AuthorizationHeader(Token); - URL = "https://cloud-api.yandex.net/v1/disk/resources/upload"; - + URL = "https://cloud-api.yandex.net/v1/disk/resources/upload"; + Parameters = New Structure; Parameters.Insert("url" , EncodeString(Address, StringEncodingMethod.URLencoding)); Parameters.Insert("path", Path); - - Parameters = OPI_Tools.RequestParametersToString(Parameters); - Response = OPI_Tools.Post(URL + Parameters, , Headers, False); - + + Parameters = OPI_Tools.RequestParametersToString(Parameters); + Response = OPI_Tools.Post(URL + Parameters, , Headers, False); + Return Response; - + EndFunction #EndRegion @@ -414,186 +414,186 @@ EndFunction // Publish object // Publishes the disk object for public access -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the object to be published - path -// +// // Returns: -// Map Of KeyAndValue - serialized JSON response from Yandex +// Map Of KeyAndValue - serialized JSON response from Yandex Function PublishObject(Val Token, Val Path) Export - - Return TogglePublicAccess(Token, Path, True); - + + Return TogglePublicAccess(Token, Path, True); + EndFunction // Unpublish object // Unpublishes a previously published object -// +// // Parameters: // Token - String - Token - token // Path - String - Path to the previously published object - path -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function CancelObjectPublication(Val Token, Val Path) Export - + Return TogglePublicAccess(Token, Path, False); - + EndFunction // Get list of published objects. // Gets a list of published objects -// +// // Parameters: -// Token - String - Token - token +// Token - String - Token - token // Count - Number - Number of returned objects - amount // OffsetFromStart - Number - Offset for getting objects not from the beginning of the list - offset -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function GetPublishedObjectsList(Val Token, Val Count = 0, Val OffsetFromStart = 0) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Count); OPI_TypeConversion.GetLine(OffsetFromStart); - + Headers = AuthorizationHeader(Token); - + Parameters = New Structure; - + If ValueIsFilled(Count) Then Parameters.Insert("limit", Count); EndIf; - + If ValueIsFilled(OffsetFromStart) Then Parameters.Insert("offset", OffsetFromStart); EndIf; - + Response = OPI_Tools.Get("https://cloud-api.yandex.net/v1/disk/resources/public", Parameters, Headers); - + Return Response; - + EndFunction // Get public object // Gets information about the published object by its URL -// +// // Parameters: // Token - String - Token - token -// URL - String - Object address - url +// URL - String - Object address - url // Count - Number - Number of returned nested objects (for catalog) - amount // OffsetFromStart - Number - Offset for getting nested objects not from the beginning of the list - offset -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function GetPublicObject(Val Token, Val URL, Val Count = 0, Val OffsetFromStart = 0) Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(URL); OPI_TypeConversion.GetLine(Count); OPI_TypeConversion.GetLine(OffsetFromStart); - + Headers = AuthorizationHeader(Token); - + Parameters = New Structure; - + If ValueIsFilled(Count) Then Parameters.Insert("limit", OPI_Tools.NumberToString(Count)); EndIf; - + If ValueIsFilled(OffsetFromStart) Then Parameters.Insert("offset", OPI_Tools.NumberToString(OffsetFromStart)); EndIf; - + Parameters.Insert("public_key", URL); - + Response = OPI_Tools.Get("https://cloud-api.yandex.net/v1/disk/public/resources", Parameters, Headers); - + Return Response; - + EndFunction // Get download link for public object // Gets a direct link to download the public object -// +// // Parameters: // Token - String - Token - token // URL - String - Object address - url // Path - String - Path inside the object - path -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function GetDownloadLinkForPublicObject(Val Token, Val URL, Val Path = "") Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(URL); OPI_TypeConversion.GetLine(Path); - + Headers = AuthorizationHeader(Token); - + Parameters = New Structure; - + If ValueIsFilled(Path) Then Parameters.Insert("path", Path); EndIf; - + Parameters.Insert("public_key", URL); - + Response = OPI_Tools.Get("https://cloud-api.yandex.net/v1/disk/public/resources/download", Parameters, Headers); - - Return Response; - + + Return Response; + EndFunction - + // Save public object to disk // Saves the public object to your disk -// +// // Parameters: // Token - String - Token - token // URL - String - Object address - url // From - String - Path within public catalog (folders only) - from // Target - String - File save path - to -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function SavePublicObjectToDisk(Val Token, Val URL, From = "", Target = "") Export - + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(URL); OPI_TypeConversion.GetLine(From); OPI_TypeConversion.GetLine(Target); - + Headers = AuthorizationHeader(Token); Address = "https://cloud-api.yandex.net/v1/disk/public/resources/save-to-disk"; - Href = "href"; - + Href = "href"; + Parameters = New Structure; Parameters.Insert("public_key", EncodeString(URL, StringEncodingMethod.URLencoding)); - + If ValueIsFilled(From) Then Parameters.Insert("path", From); EndIf; - + If ValueIsFilled(Target) Then Parameters.Insert("save_path", Target); EndIf; - - Parameters = OPI_Tools.RequestParametersToString(Parameters); - Response = OPI_Tools.Post(Address + Parameters, , Headers, False); - - ResponseURL = Response[Href]; - + + Parameters = OPI_Tools.RequestParametersToString(Parameters); + Response = OPI_Tools.Post(Address + Parameters, , Headers, False); + + ResponseURL = Response[Href]; + If Not ValueIsFilled(ResponseURL) Then - Return Response; + Return Response; EndIf; - + Response = OPI_Tools.Get(ResponseURL, , Headers); - + Return Response; - + EndFunction - + #EndRegion #EndRegion @@ -601,42 +601,42 @@ EndFunction #Region Private Function AuthorizationHeader(Val Token) - + Headers = New Map; Headers.Insert("Authorization", "OAuth " + Token); - + Return Headers; - + EndFunction -Function TogglePublicAccess(Val Token, Val Path, Val PublicAccess) - +Function TogglePublicAccess(Val Token, Val Path, Val PublicAccess) + OPI_TypeConversion.GetLine(Token); OPI_TypeConversion.GetLine(Path); OPI_TypeConversion.GetBoolean(PublicAccess); - - Headers = AuthorizationHeader(Token); + + Headers = AuthorizationHeader(Token); Destination = ?(PublicAccess, "publish", "unpublish"); - Href = "href"; - + Href = "href"; + URL = "https://cloud-api.yandex.net/v1/disk/resources/" + Destination; - + Parameters = New Structure; Parameters.Insert("path", Path); - - Parameters = OPI_Tools.RequestParametersToString(Parameters); - Response = OPI_Tools.Put(URL + Parameters, , Headers, False); - + + Parameters = OPI_Tools.RequestParametersToString(Parameters); + Response = OPI_Tools.Put(URL + Parameters, , Headers, False); + ResponseURL = Response[Href]; - + If Not ValueIsFilled(ResponseURL) Then - Return Response; - EndIf; - + Return Response; + EndIf; + Response = OPI_Tools.Get(ResponseURL, , Headers); - + Return Response; - + EndFunction #EndRegion diff --git a/src/en/OPI/src/CommonModules/OPI_YandexID/Module.bsl b/src/en/OPI/src/CommonModules/OPI_YandexID/Module.bsl index 0512827a58..fb4f06396d 100644 --- a/src/en/OPI/src/CommonModules/OPI_YandexID/Module.bsl +++ b/src/en/OPI/src/CommonModules/OPI_YandexID/Module.bsl @@ -41,77 +41,77 @@ // Get confirmation code // Gets the confirmation code and the address of the page where it needs to be entered -// +// // Parameters: // ClientId - String - Client id - id -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function GetConfirmationCode(Val ClientId) Export OPI_TypeConversion.GetLine(ClientId); - + Parameters = New Structure("client_id", ClientId); - Response = OPI_Tools.Post("https://oauth.yandex.ru/device/code", Parameters, , False); - + Response = OPI_Tools.Post("https://oauth.yandex.ru/device/code", Parameters, , False); + Return Response; - + EndFunction // Convert code to token // Converts the code to a token after entering the code when executing GetConfirmationCode -// +// // Parameters: // ClientId - String - Client id - id // ClientSecret - String - Client secret - secret // DeviceCode - String - device_code from GetConfirmationCode() - device -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function ConvertCodeToToken(Val ClientId, Val ClientSecret, Val DeviceCode) Export - + OPI_TypeConversion.GetLine(ClientId); OPI_TypeConversion.GetLine(ClientSecret); OPI_TypeConversion.GetLine(DeviceCode); - + Parameters = New Structure; - Parameters.Insert("grant_type" , "device_code"); - Parameters.Insert("code" , DeviceCode); - Parameters.Insert("client_id" , ClientId); + Parameters.Insert("grant_type" , "device_code"); + Parameters.Insert("code" , DeviceCode); + Parameters.Insert("client_id" , ClientId); Parameters.Insert("client_secret" , ClientSecret); - + Response = OPI_Tools.Post("https://oauth.yandex.ru/token", Parameters, , False); - + Return Response; - + EndFunction // Refresh token // Updates token by Refresh token -// +// // Parameters: // ClientId - String - Client id - id // ClientSecret - String - Client secret - secret // RefreshToken - String - Refresh token - refresh -// +// // Returns: // Map Of KeyAndValue - serialized JSON response from Yandex Function RefreshToken(Val ClientId, Val ClientSecret, Val RefreshToken) Export - + OPI_TypeConversion.GetLine(ClientId); OPI_TypeConversion.GetLine(ClientSecret); OPI_TypeConversion.GetLine(RefreshToken); - + Parameters = New Structure; - Parameters.Insert("grant_type" , "refresh_token"); + Parameters.Insert("grant_type" , "refresh_token"); Parameters.Insert("refresh_token" , RefreshToken); - Parameters.Insert("client_id" , ClientId); + Parameters.Insert("client_id" , ClientId); Parameters.Insert("client_secret" , ClientSecret); - + Response = OPI_Tools.Post("https://oauth.yandex.ru/token", Parameters, , False); - + Return Response; - + EndFunction #EndRegion diff --git a/src/ru/OInt/core/Modules/OPI_Airtable.os b/src/ru/OInt/core/Modules/OPI_Airtable.os index a1b8e9335a..db28ffca3e 100644 --- a/src/ru/OInt/core/Modules/OPI_Airtable.os +++ b/src/ru/OInt/core/Modules/OPI_Airtable.os @@ -42,91 +42,91 @@ // Получить список баз // Получает список доступных баз -// +// // Параметры: // Токен - Строка - Токен - token // Отступ - Строка - Идентификатор следующей страницы списка баз из перыдудщего запроса - offset -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция ПолучитьСписокБаз(Знач Токен, Знач Отступ = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Отступ); - + URL = "https://api.airtable.com/v0/meta/bases"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); Параметры = Новый Структура; - + OPI_Инструменты.ДобавитьПоле("offset", Отступ, "Строка", Параметры); - + Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить таблицы базы // Получает схему таблиц базы -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - Идентификатор базы - base -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция ПолучитьТаблицыБазы(Знач Токен, Знач База) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(База); - + URL = "https://api.airtable.com/v0/meta/bases/" + База + "/tables"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Ответ = OPI_Инструменты.Get(URL, , Заголовки); - + Возврат Ответ; - + КонецФункции // Создать базу // Создает новую базу данных -// +// // Параметры: // Токен - Строка - Токен - token // РабочееПространство - Строка - Идентификатор рабочего пространства - ws // Наименование - Строка - Наименование новой базы - title // КоллекцияТаблиц - Соответствие Из КлючИЗначение - Описание таблиц: Ключ > имя, Значение > массив полей - tablesdata -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция СоздатьБазу(Знач Токен, Знач РабочееПространство, Знач Наименование, Знач КоллекцияТаблиц) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(КоллекцияТаблиц); - - Если Не ТипЗнч(КоллекцияТаблиц) = Тип("Структура") + + Если Не ТипЗнч(КоллекцияТаблиц) = Тип("Структура") И Не ТипЗнч(КоллекцияТаблиц) = Тип("Соответствие") Тогда - + ВызватьИсключение "Ошибка в данных коллекции таблиц"; - + КонецЕсли; - + URL = "https://api.airtable.com/v0/meta/bases"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); МассивТаблиц = Новый Массив; - + Для Каждого Таблица Из КоллекцияТаблиц Цикл - + Описание = СформироватьОписаниеТаблицы(Таблица.Ключ, Таблица.Значение); МассивТаблиц.Добавить(Описание); - + КонецЦикла; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("name" , Наименование , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("tables" , МассивТаблиц , "Массив", Параметры); OPI_Инструменты.ДобавитьПоле("workspaceId", РабочееПространство, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции @@ -137,56 +137,56 @@ // Создать таблицу // Создает новую таблицу в базе -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - Идентификатор базы - base // Наименование - Строка - Наименование новой таблицы - title // МассивПолей - Массив Из Структура - Массив описаний полей - fieldsdata // Описание - Строка - Описание таблицы - description -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция СоздатьТаблицу(Знач Токен, Знач База, Знач Наименование, Знач МассивПолей, Знач Описание = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(База); - + URL = "https://api.airtable.com/v0/meta/bases/" + База + "/tables"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - Параметры = СформироватьОписаниеТаблицы(Наименование, МассивПолей, Описание); - + Параметры = СформироватьОписаниеТаблицы(Наименование, МассивПолей, Описание); + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Изменить таблицу // Изменяет наименование и|или описание базы -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - Идентификатор базы - base // Таблица - Строка - Идентификатор таблицы - table // Наименование - Строка - Новое наименование - title // Описание - Строка - Новое описание - description -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция ИзменитьТаблицу(Знач Токен, Знач База, Знач Таблица, Знач Наименование = "", Знач Описание = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(База); OPI_ПреобразованиеТипов.ПолучитьСтроку(Таблица); - + URL = "https://api.airtable.com/v0/meta/bases/" + База + "/tables/" + Таблица; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - Параметры = Новый Структура; - + Параметры = Новый Структура; + OPI_Инструменты.ДобавитьПоле("name" , Наименование, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("description", Описание , "Строка", Параметры); - + Ответ = OPI_Инструменты.Patch(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции @@ -197,40 +197,40 @@ // Создать поле // Создет новое поле в таблице -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - Идентификатор базы - base // Таблица - Строка - Идентификатор таблицы - table // СтруктураПоля - Структура Из КлючИЗначение - Описание нового поля - fielddata -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция СоздатьПоле(Знач Токен, Знач База, Знач Таблица, Знач СтруктураПоля) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(База); OPI_ПреобразованиеТипов.ПолучитьСтроку(Таблица); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(СтруктураПоля); - - Если Не ТипЗнч(СтруктураПоля) = Тип("Структура") + + Если Не ТипЗнч(СтруктураПоля) = Тип("Структура") И Не ТипЗнч(СтруктураПоля) = Тип("Соответствие") Тогда - + ВызватьИсключение "Ошибка в данных описания поля"; - + КонецЕсли; - + URL = "https://api.airtable.com/v0/meta/bases/" + База + "/tables/" + Таблица + "/fields"; - Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Заголовки = ПолучитьЗаголовокАвторизации(Токен); + Ответ = OPI_Инструменты.Post(URL, СтруктураПоля, Заголовки); - + Возврат Ответ; КонецФункции // Изменить поле // Изменяет имя и|или описание существующего поля таблицы -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - Идентификатор базы База - base @@ -238,152 +238,152 @@ // Поле - Строка - Идентификатор поля - field // Наименование - Строка - Новое наименование - title // Описание - Строка - Новое описание - description -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция ИзменитьПоле(Знач Токен, Знач База, Знач Таблица, Знач Поле, Знач Наименование = "", Знач Описание = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(База); OPI_ПреобразованиеТипов.ПолучитьСтроку(Таблица); OPI_ПреобразованиеТипов.ПолучитьСтроку(Поле); - - URL = "https://api.airtable.com/v0/meta/bases/" - + База - + "/tables/" - + Таблица - + "/fields/" + + URL = "https://api.airtable.com/v0/meta/bases/" + + База + + "/tables/" + + Таблица + + "/fields/" + Поле; - + Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура(); OPI_Инструменты.ДобавитьПоле("name" , Наименование, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("description", Описание , "Строка", Параметры); - + Ответ = OPI_Инструменты.Patch(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Получить поле (строковое) // Получает описание поля строкового типа -// +// // Параметры: // Наименование - Строка - Наименование нового поля - title -// +// // Возвращаемое значение: // Структура - Описание поля Функция ПолучитьПолеСтроковое(Знач Наименование) Экспорт - + Возврат ОписаниеПримитивногоПоля(Наименование, "richText"); - + КонецФункции // Получить поле (числовое) // Получает описание поля числового типа -// +// // Параметры: // Наименование - Строка - Наименование нового поля - title // Точность - Число,Строка - Число знаков после запятой - precision -// +// // Возвращаемое значение: // Структура - Описание поля Функция ПолучитьПолеНомера(Знач Наименование, Знач Точность = 0) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьЧисло(Точность); - + СтруктураОпций = Новый Структура("precision", Точность); Возврат ОписаниеПримитивногоПоля(Наименование, "number", СтруктураОпций); - + КонецФункции // Получить поле (файл) // Получает описание поля файлового типа -// +// // Параметры: // Наименование - Строка - Наименование поля - title -// +// // Возвращаемое значение: // Структура - Описание поля Функция ПолучитьПолеВложения(Знач Наименование) Экспорт - + Возврат ОписаниеПримитивногоПоля(Наименование, "multipleAttachments"); - + КонецФункции // Получить поле (флажок) // Получает описание поля типа булево -// +// // Параметры: // Наименование - Строка - Наименование поля - title -// +// // Возвращаемое значение: // Структура - Описание поля Функция ПолучитьПолеФлажка(Знач Наименование) Экспорт - + СтруктураОпций = Новый Структура("icon,color", "check", "yellowBright"); Возврат ОписаниеПримитивногоПоля(Наименование, "checkbox", СтруктураОпций); - + КонецФункции // Получить поле (дата) // Получает описание поля типа дата -// +// // Параметры: // Наименование - Строка - Наименование поля - title -// +// // Возвращаемое значение: // Структура - Описание поля Функция ПолучитьПолеДаты(Знач Наименование) Экспорт - + СтруктураФормата = Новый Структура("format,name", "YYYY-MM-DD", "iso"); СтруктураОпций = Новый Структура("dateFormat", СтруктураФормата); - + Возврат ОписаниеПримитивногоПоля(Наименование, "date", СтруктураОпций); - + КонецФункции // Получить поле (email) // Получает описание поля с электронной почтой -// +// // Параметры: // Наименование - Строка - Наименование поля - title -// +// // Возвращаемое значение: // Структура - Описание поля Функция ПолучитьПолеПочты(Знач Наименование) Экспорт - + Возврат ОписаниеПримитивногоПоля(Наименование, "email"); - + КонецФункции // Получить поле (телефон) // Получает описание поля с номером телефона -// +// // Параметры: // Наименование - Строка - Наименование поля - title -// +// // Возвращаемое значение: // Структура - Описание поля Функция ПолучитьПолеТелефона(Знач Наименование) Экспорт - + Возврат ОписаниеПримитивногоПоля(Наименование, "phoneNumber"); - + КонецФункции // Получить поле (url) // Получает описание поля с URL -// +// // Параметры: // Наименование - Строка - Наименование поля - title -// +// // Возвращаемое значение: // Структура - Описание поля Функция ПолучитьПолеСсылки(Знач Наименование) Экспорт - + Возврат ОписаниеПримитивногоПоля(Наименование, "url"); - + КонецФункции #КонецОбласти @@ -392,67 +392,67 @@ // Получить список записей // Получает список записей выбранной таблицы -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - Идентификатор базы данных - base // Таблица - Строка - Идентификатор таблицы - table // Отступ - Строка - Иднтификатор следующей страницы данных из предыдущего запроса - offset -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция ПолучитьСписокЗаписей(Знач Токен, Знач База, Знач Таблица, Знач Отступ = "") Экспорт OPI_ПреобразованиеТипов.ПолучитьСтроку(База); OPI_ПреобразованиеТипов.ПолучитьСтроку(Таблица); - + URL = "https://api.airtable.com/v0/" + База + "/" + Таблица; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура(); OPI_Инструменты.ДобавитьПоле("offset", Отступ, "Строка", Параметры); - + Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить запись // Получает данные строки таблицы по идентификатору -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - Идентификатор базы данных - base // Таблица - Строка - Идентификатор таблицы - table // Запись - Строка - Идентификатор записи в таблице - record -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция ПолучитьЗапись(Знач Токен, Знач База, Знач Таблица, Знач Запись) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(База); OPI_ПреобразованиеТипов.ПолучитьСтроку(Таблица); OPI_ПреобразованиеТипов.ПолучитьСтроку(Запись); - + URL = "https://api.airtable.com/v0/" + База + "/" + Таблица + "/" + Запись; Заголовки = ПолучитьЗаголовокАвторизации(Токен); Ответ = OPI_Инструменты.Get(URL, , Заголовки); - + Возврат Ответ; - + КонецФункции // Создать записи // Создает одну или массив записей по описанию или массиву описаний значений полей -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - Идентификатор базы данных - base // Таблица - Строка - Идентификатор таблицы - table // Данные - Структура, Массив из Структура - Набор или массив наборов пар Ключ : Значение > Поле : Показатель - data -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция СоздатьЗаписи(Знач Токен, Знач База, Знач Таблица, Знач Данные) Экспорт @@ -460,52 +460,52 @@ OPI_ПреобразованиеТипов.ПолучитьСтроку(База); OPI_ПреобразованиеТипов.ПолучитьСтроку(Таблица); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Данные); - + Параметры = Новый Структура(); - ДобавитьОписаниеДанных(Данные, Параметры); + ДобавитьОписаниеДанных(Данные, Параметры); URL = "https://api.airtable.com/v0/" + База + "/" + Таблица; Заголовки = ПолучитьЗаголовокАвторизации(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции // Удалить записи // Удаляет одну или массив записей по идентификаторам -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - Идентификатор базы данных - base // Таблица - Строка - Идентификатор таблицы - table // Записи - Строка, Массив из Строка - Идентификатор или массив индентификаторов записей - records -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция УдалитьЗаписи(Знач Токен, Знач База, Знач Таблица, Знач Записи) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(База); OPI_ПреобразованиеТипов.ПолучитьСтроку(Таблица); OPI_ПреобразованиеТипов.ПолучитьМассив(Записи); - + СтрокаЗаписей = ""; - + Для Каждого Запись Из Записи Цикл - СтрокаЗаписей = СтрокаЗаписей + СтрокаЗаписей = СтрокаЗаписей + ?(ЗначениеЗаполнено(СтрокаЗаписей), "&", "?") + "records[]=" - + OPI_Инструменты.ЧислоВСтроку(Запись); + + OPI_Инструменты.ЧислоВСтроку(Запись); КонецЦикла; - + URL = "https://api.airtable.com/v0/" + База + "/" + Таблица + СтрокаЗаписей; Заголовки = ПолучитьЗаголовокАвторизации(Токен); Ответ = OPI_Инструменты.Delete(URL, , Заголовки); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции #КонецОбласти @@ -514,67 +514,67 @@ // Получить комментарии // Получает список комментариев к записи в таблице -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - Идентификатор базы данных - base // Таблица - Строка - Идентификатор таблицы - table // Запись - Строка - Идентификатор записи в таблице - record // Отступ - Строка - Иднтификатор следующей страницы данных из предыдущего запроса - offset -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция ПолучитьКомментарии(Знач Токен, Знач База, Знач Таблица, Знач Запись, Знач Отступ = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(База); OPI_ПреобразованиеТипов.ПолучитьСтроку(Таблица); OPI_ПреобразованиеТипов.ПолучитьСтроку(Запись); - + URL = "https://api.airtable.com/v0/" + База + "/" + Таблица + "/" + Запись + "/comments"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура(); OPI_Инструменты.ДобавитьПоле("offset", Отступ, "Строка", Параметры); - + Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Создать комментарий // Создает комментарий к записи в таблице -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - Идентификатор базы данных - base // Таблица - Строка - Идентификатор таблицы - table // Запись - Строка - Идентификатор записи в таблице - record // Текст - Строка - Текст комментария - text -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция СоздатьКомментарий(Знач Токен, Знач База, Знач Таблица, Знач Запись, Знач Текст) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(База); OPI_ПреобразованиеТипов.ПолучитьСтроку(Таблица); OPI_ПреобразованиеТипов.ПолучитьСтроку(Запись); - + URL = "https://api.airtable.com/v0/" + База + "/" + Таблица + "/" + Запись + "/comments"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура(); OPI_Инструменты.ДобавитьПоле("text", Текст, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Изменить комментарий // Изменяет текст существующего комментария -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - Идентификатор базы данных - base @@ -582,54 +582,54 @@ // Запись - Строка - Идентификатор записи в таблице - record // Комментарий - Строка - Идентификатор комментария - comment // Текст - Строка - Новый текст комментария - text -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция ИзменитьКомментарий(Знач Токен, Знач База, Знач Таблица, Знач Запись, Знач Комментарий, Знач Текст) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(База); OPI_ПреобразованиеТипов.ПолучитьСтроку(Таблица); OPI_ПреобразованиеТипов.ПолучитьСтроку(Запись); OPI_ПреобразованиеТипов.ПолучитьСтроку(Комментарий); - + URL = "https://api.airtable.com/v0/" + База + "/" + Таблица + "/" + Запись + "/comments/" + Комментарий; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура(); OPI_Инструменты.ДобавитьПоле("text", Текст, "Строка", Параметры); - + Ответ = OPI_Инструменты.Patch(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Удалить комментарий // Удаляет комментарий к записи таблицы -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - Идентификатор базы данных - base // Таблица - Строка - Идентификатор таблицы - table // Запись - Строка - Идентификатор записи в таблице - record // Комментарий - Строка - Идентификатор комментария - comment -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция УдалитьКомментарий(Знач Токен, Знач База, Знач Таблица, Знач Запись, Знач Комментарий) Экспорт OPI_ПреобразованиеТипов.ПолучитьСтроку(База); OPI_ПреобразованиеТипов.ПолучитьСтроку(Таблица); OPI_ПреобразованиеТипов.ПолучитьСтроку(Запись); OPI_ПреобразованиеТипов.ПолучитьСтроку(Комментарий); - + URL = "https://api.airtable.com/v0/" + База + "/" + Таблица + "/" + Запись + "/comments/" + Комментарий; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Ответ = OPI_Инструменты.Delete(URL, , Заголовки); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -639,58 +639,58 @@ #Область СлужебныеПроцедурыИФункции Функция ПолучитьЗаголовокАвторизации(Знач Токен) - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Заголовки = Новый Соответствие; Заголовки.Вставить("Authorization", "Bearer " + Токен); - + Возврат Заголовки; - + КонецФункции Функция СформироватьОписаниеТаблицы(Знач Наименование, Знач МассивПолей, Знач Описание = "") - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Наименование); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивПолей); - + ОписаниеТаблицы = Новый Структура("name,fields", Наименование, МассивПолей); - + OPI_Инструменты.ДобавитьПоле("description", Описание, "Строка", ОписаниеТаблицы); - + Возврат ОписаниеТаблицы; - + КонецФункции Функция ОписаниеПримитивногоПоля(Знач Наименование, Знач Тип, Знач Опции = "") - + СтруктураПоля = Новый Структура(); OPI_Инструменты.ДобавитьПоле("name" , Наименование, "Строка" , СтруктураПоля); OPI_Инструменты.ДобавитьПоле("type" , Тип , "Строка" , СтруктураПоля); OPI_Инструменты.ДобавитьПоле("options", Опции , "Коллекция", СтруктураПоля); - + Возврат СтруктураПоля; КонецФункции Процедура ДобавитьОписаниеДанных(Знач Данные, Параметры) - + Если ТипЗнч(Данные) = Тип("Массив") Тогда - + МассивОтправки = Новый Массив; - + Для Каждого ОписаниеЗаписи Из Данные Цикл - МассивОтправки.Добавить(Новый Структура("fields", ОписаниеЗаписи)); + МассивОтправки.Добавить(Новый Структура("fields", ОписаниеЗаписи)); КонецЦикла; - + OPI_Инструменты.ДобавитьПоле("records", МассивОтправки, "Массив", Параметры); - + Иначе - - OPI_Инструменты.ДобавитьПоле("fields", Данные, "Коллекция", Параметры); - + + OPI_Инструменты.ДобавитьПоле("fields", Данные, "Коллекция", Параметры); + КонецЕсли; - + КонецПроцедуры #КонецОбласти diff --git a/src/ru/OInt/core/Modules/OPI_Bitrix24.os b/src/ru/OInt/core/Modules/OPI_Bitrix24.os index 12cbc4723f..b1576e8e9b 100644 --- a/src/ru/OInt/core/Modules/OPI_Bitrix24.os +++ b/src/ru/OInt/core/Modules/OPI_Bitrix24.os @@ -47,105 +47,105 @@ // Получить ссылку авторизации приложения // Формирует ссылку для авторизации через браузер -// +// // Параметры: // Домен - Строка - Адрес битрикс вида portal.bitrix24.com - domain // ClientID - Строка - Client ID из настроек приложения - clientid -// +// // Возвращаемое значение: // Строка - URL для перехода в браузере Функция ПолучитьСсылкуАвторизацииПриложения(Знач Домен, Знач ClientID) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Домен); OPI_ПреобразованиеТипов.ПолучитьСтроку(ClientID); - + Если Не СтрНачинаетсяС(Домен, "http") Тогда URL = "https://" + Домен; КонецЕсли; - + Если Не СтрЗаканчиваетсяНа(URL, "/") Тогда URL = URL + "/"; КонецЕсли; - + URL = URL + "oauth/authorize/?client_id=" + ClientID; - + Возврат URL; - + КонецФункции // Получить токен // Получает токен по коду авторизации -// +// // Параметры: // ClientID - Строка - Client ID из настроек приложения - clientid // ClientSecret - Строка - Client secret из настроек приложения - clientsecret // Code - Строка - Code из авторизации через браузер - code -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьТокен(Знач ClientID, Знач ClientSecret, Знач Code) Экспорт - + URL = "https://oauth.bitrix.info/oauth/token/"; Строка_ = "Строка"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("grant_type" , "authorization_code", Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("client_id" , ClientID , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("client_secret", ClientSecret , Строка_, Параметры); - OPI_Инструменты.ДобавитьПоле("code" , Code , Строка_, Параметры); - + OPI_Инструменты.ДобавитьПоле("code" , Code , Строка_, Параметры); + Ответ = OPI_Инструменты.Get(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Обновить токен // Обновляет токен по Refresh токену -// +// // Параметры: // ClientID - Строка - Client ID из настроек приложения - clientid // ClientSecret - Строка - Client secret из настроек приложения - clientsecret // Refresh - Строка - Refresh токен - refresh -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ОбновитьТокен(Знач ClientID, Знач ClientSecret, Знач Refresh) Экспорт - + URL = "https://oauth.bitrix.info/oauth/token/"; Строка_ = "Строка"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("grant_type" , "refresh_token" , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("client_id" , ClientID , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("client_secret", ClientSecret , Строка_, Параметры); - OPI_Инструменты.ДобавитьПоле("refresh_token", Refresh , Строка_, Параметры); - + OPI_Инструменты.ДобавитьПоле("refresh_token", Refresh , Строка_, Параметры); + Ответ = OPI_Инструменты.Get(URL, Параметры); - + Возврат Ответ; КонецФункции // Серверное время // Получает текущее серверное время -// +// // Примечание: // Метод в документации API: [server_time](@dev.1c-bitrix.ru/rest_help/general/server_time.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция СерверноеВремя(Знач URL, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "server.time"); Ответ = OPI_Инструменты.Get(URL, Параметры); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -154,19 +154,19 @@ // Создать новость // Создает новую новость в ленте -// +// // Примечание: // Метод в документации API: [log.blogpost.add](@dev.1c-bitrix.ru/rest_help/log/log_blogpost_add.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Текст - Строка - Текст новости - text // Видимость - Строка - Массив или 1 получатель: UA все, SGn р. группа, Un пользователь, DRn отдел, Gn группа - vision // Файлы - Соответствие Из КлючИЗначение - Ключ > имя файла, значение > путь или двоичные данные - files // Заголовок - Строка - Заголовок новости - title -// Важное - Булево - Помечает новость как важную - important +// Важное - Булево - Помечает новость как важную - important // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция СоздатьНовость(Знач URL @@ -176,41 +176,41 @@ , Знач Заголовок = "" , Знач Важное = Ложь , Знач Токен = "") Экспорт - + ПривестиБулево(Важное); - + Строка_ = "Строка"; - + Параметры = НормализоватьАвторизацию(URL, Токен, "log.blogpost.add"); - OPI_Инструменты.ДобавитьПоле("POST_MESSAGE", Текст , Строка_, Параметры); - OPI_Инструменты.ДобавитьПоле("POST_TITLE" , Заголовок , Строка_, Параметры); + OPI_Инструменты.ДобавитьПоле("POST_MESSAGE", Текст , Строка_ , Параметры); + OPI_Инструменты.ДобавитьПоле("POST_TITLE" , Заголовок , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("DEST" , Видимость , "Массив", Параметры); - OPI_Инструменты.ДобавитьПоле("IMPORTANT" , Важное , Строка_, Параметры); - + OPI_Инструменты.ДобавитьПоле("IMPORTANT" , Важное , Строка_ , Параметры); + Если ЗначениеЗаполнено(Файлы) Тогда - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Файлы); - + МассивФайлов = НормализоватьФайлы(Файлы); - + Если Не МассивФайлов.Количество() = 0 Тогда Параметры.Вставить("FILES", МассивФайлов); КонецЕсли; - + КонецЕсли; - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Изменить новость // Изменяет новость в ленте -// +// // Примечание: // Метод в документации API: [log.blogpost.update](@dev.1c-bitrix.ru/rest_help/log/log_blogpost_update.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDНовости - Строка, Число - ID новости - postid @@ -219,170 +219,170 @@ // Файлы - Соответствие Из КлючИЗначение - Ключ > имя файла, значение > путь или двоичные данные - files // Заголовок - Строка - Заголовок новости - title // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ИзменитьНовость(Знач URL - , Знач IDНовости + , Знач IDНовости , Знач Текст , Знач Видимость = "UA" , Знач Файлы = "" , Знач Заголовок = "" , Знач Токен = "") Экспорт - + Строка_ = "Строка"; - + Параметры = НормализоватьАвторизацию(URL, Токен, "log.blogpost.update"); - OPI_Инструменты.ДобавитьПоле("POST_MESSAGE", Текст , Строка_, Параметры); - OPI_Инструменты.ДобавитьПоле("POST_TITLE" , Заголовок , Строка_, Параметры); + OPI_Инструменты.ДобавитьПоле("POST_MESSAGE", Текст , Строка_ , Параметры); + OPI_Инструменты.ДобавитьПоле("POST_TITLE" , Заголовок , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("DEST" , Видимость , "Массив", Параметры); - OPI_Инструменты.ДобавитьПоле("POST_ID" , IDНовости , Строка_, Параметры); - + OPI_Инструменты.ДобавитьПоле("POST_ID" , IDНовости , Строка_ , Параметры); + Если ЗначениеЗаполнено(Файлы) Тогда - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Файлы); - + МассивФайлов = НормализоватьФайлы(Файлы); - + Если Не МассивФайлов.Количество() = 0 Тогда Параметры.Вставить("FILES", МассивФайлов); КонецЕсли; - + КонецЕсли; - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Удалить новость // Удаляет новость из ленты по выбранному ID -// +// // Примечание: // Метод в документации API: [log.blogpost.delete](@dev.1c-bitrix.ru/rest_help/log/log_blogpost_delete.php) -// +// // Параметры: -// URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url +// URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDНовости - Строка, Число - ID новости для удаления - postid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УдалитьНовость(Знач URL, Знач IDНовости, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "log.blogpost.delete"); OPI_Инструменты.ДобавитьПоле("POST_ID", IDНовости, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить список просмотревших важное // Возвращает список пользователей, просмотревших выбранное важное сообщение -// +// // Примечание: // Метод в документации API: [log.blogpost.getusers.important](@dev.1c-bitrix.ru/rest_help/log/log_blogpost_getusers_important.php) -// +// // Параметры: -// URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url +// URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDНовости - Строка, Число - ID важной новости - postid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьСписокПросмотревшихВажное(Знач URL, Знач IDНовости, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "log.blogpost.getusers.important"); OPI_Инструменты.ДобавитьПоле("POST_ID", IDНовости, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить новости // Получает нвости или одну новость с отобором по ID или доступности -// +// // Примечание: // Метод в документации API: [log.blogpost.get](@dev.1c-bitrix.ru/rest_help/log/log_blogpost_get.php) -// +// // Параметры: -// URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url +// URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDНовости - Строка, Число - ID важной новости - postid -// Отбор - Строка - Отбор новостей по доступу: UA все, SGn раб. группа, Un пользователь, DRn отдел, Gn группа - sel +// Отбор - Строка - Отбор новостей по доступу: UA все, SGn раб. группа, Un пользователь, DRn отдел, Gn группа - sel // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьНовости(Знач URL, Знач IDНовости = "", Знач Отбор = "UA", Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "log.blogpost.get"); - + OPI_Инструменты.ДобавитьПоле("POST_ID" , IDНовости, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("LOG_RIGHTS", Отбор , "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Добавить комментарий новости // Добавляет комментарий к новости -// +// // Примечание: // Метод в документации API: [log.blogcomment.add](@dev.1c-bitrix.ru/rest_help/log/log_blogcomment_add.php) -// +// // Параметры: -// URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url +// URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDНовости - Строка, Число - ID новости - postid // Текст - Строка - Текст комментария - text // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ДобавитьКомментарийНовости(Знач URL, Знач IDНовости, Знач Текст, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "log.blogcomment.add"); - + OPI_Инструменты.ДобавитьПоле("POST_ID" , IDНовости, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("TEXT" , Текст , "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Добавить получателей к новости // Добавляет новые группы или пользователей в получатели -// +// // Примечание: // Метод в документации API: [log.blogpost.share](@dev.1c-bitrix.ru/rest_help/log/log_blogpost_share.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDНовости - Строка, Число - ID новости - postid // Видимость - Строка - Массив или 1 получатель: UA все, SGn р. группа, Un пользователь, DRn отдел, Gn группа - vision // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ДобавитьПолучателейКНовости(Знач URL, Знач IDНовости, Знач Видимость, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "log.blogpost.share"); - + OPI_Инструменты.ДобавитьПоле("POST_ID" , IDНовости, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("DEST" , Видимость, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -391,132 +391,132 @@ // Получить задачу // Получает задачу по ID -// +// // Примечание: // Метод в документации API: [tasks.task.get](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_get.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьЗадачу(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.get", Токен); Возврат Ответ; - + КонецФункции // Получить список задач // Получает список задач (50 шт. за запрос максимум) с фильтром или без (см. ПолучитьСтруктуруФильтраЗадач) -// +// // Примечание: // Метод в документации API: [tasks.task.list](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_list.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Фильтр - Структура из КлючИЗначение - Структура отбора задач (см. ПолучитьСтруктуруФильтраЗадач) - filter // Отступ - Число, Строка - Отступ от начала списка для полчения задач > 50 шт. рекурсивно - offset // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьСписокЗадач(Знач URL, Знач Фильтр = "", Знач Отступ = 0, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "tasks.task.list"); OPI_Инструменты.ДобавитьПоле("filter", Фильтр, "Коллекция", Параметры); OPI_Инструменты.ДобавитьПоле("start" , Отступ, "Строка" , Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Создать задачу // Создает новую задачу по структуре полей (см. ПолучитьСтруктуруЗадачи) -// +// // Примечание: // Метод в документации API: [tasks.task.add](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_add.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // СтруктураПолей - Структура Из КлючИЗначение - Структура полей задачи (см. ПолучитьСтруктуруЗадачи) - fields // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция СоздатьЗадачу(Знач URL, Знач СтруктураПолей, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "tasks.task.add"); OPI_Инструменты.ДобавитьПоле("fields", СтруктураПолей, "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; КонецФункции // Изменить задачу // Изменяет существующую задачу -// +// // Примечание: // Метод в документации API: [tasks.task.update](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_update.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // СтруктураПолей - Структура Из КлючИЗначение - Структура полей задачи - fields // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ИзменитьЗадачу(Знач URL, Знач IDЗадачи, Знач СтруктураПолей, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "tasks.task.update"); OPI_Инструменты.ДобавитьПоле("fields", СтруктураПолей, "Коллекция", Параметры); OPI_Инструменты.ДобавитьПоле("taskId", IDЗадачи , "Строка" , Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; КонецФункции // Удалить задачу // Удаляет задачу по ID -// +// // Примечание: // Метод в документации API: [tasks.task.delete](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_delete.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УдалитьЗадачу(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.delete", Токен); Возврат Ответ; - + КонецФункции // Добавить файл в задачу // Прикрепляет файл к выбранной задаче -// +// // Примечание: // Метод в документации API: [tasks.task.files.attach](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_files_attach.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число, Строка - ID задачи - task // IDФайла - Число, Строка - ID Файла - fileid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ДобавитьФайлВЗадачу(Знач URL, Знач IDЗадачи, Знач IDФайла, Знач Токен = "") Экспорт @@ -524,467 +524,467 @@ Параметры = НормализоватьАвторизацию(URL, Токен, "tasks.task.files.attach"); OPI_Инструменты.ДобавитьПоле("fileId", IDФайла , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("taskId", IDЗадачи, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Принять задачу // Принимает задачу по ID -// +// // Примечание: // Метод в документации API: [tasks.task.approve](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_approve.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПринятьЗадачу(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.approve", Токен); Возврат Ответ; - + КонецФункции // Отклонить задачу // Отклоняет задачу по ID -// +// // Примечание: // Метод в документации API: [tasks.task.disapprove](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_disapprove.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ОтклонитьЗадачу(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.disapprove", Токен); Возврат Ответ; - + КонецФункции // Завершить задачу // Завершает задачу по ID -// +// // Примечание: // Метод в документации API: [tasks.task.complete](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_complete.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ЗавершитьЗадачу(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.complete", Токен); Возврат Ответ; - + КонецФункции // Возобновить задачу // Возвращает в работу задачу по ID -// +// // Примечание: // Метод в документации API: [tasks.task.renew](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_renew.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ВозобновитьЗадачу(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.renew", Токен); Возврат Ответ; - + КонецФункции // Отложить задачу // Откладывает задачу по ID -// +// // Примечание: // Метод в документации API: [tasks.task.defer](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_defer.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ОтложитьЗадачу(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.defer", Токен); Возврат Ответ; - + КонецФункции // Приостановить задачу // Приостанавливает задачу по ID -// +// // Примечание: // Метод в документации API: [tasks.task.pause](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_pause.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПриостановитьЗадачу(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.pause", Токен); Возврат Ответ; - + КонецФункции // Начать выполнение задачи // Начинает выполнение задачи по ID -// +// // Примечание: // Метод в документации API: [tasks.task.start](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_start.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция НачатьВыполнениеЗадачи(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.start", Токен); Возврат Ответ; - + КонецФункции // Начать наблюдать за задачей // Начинает наблюдение за задачей по ID -// +// // Примечание: // Метод в документации API: [tasks.task.startwatch](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_startwatch.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция НачатьНаблюдатьЗаЗадачей(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.startwatch", Токен); Возврат Ответ; - + КонецФункции // Прекратить наблюдать за задачей // Прекращает наблюдение за задчей по ID -// +// // Примечание: // Метод в документации API: [tasks.task.stopwatch](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_stopwatch.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПрекратитьНаблюдатьЗаЗадачей(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.stopwatch", Токен); Возврат Ответ; - + КонецФункции // Делегировать задачу // Делегирует задачу на другого пользователя -// +// // Примечание: // Метод в документации API: [tasks.task.delegate](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_delegate.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // IDПользователя - Число,Строка - ID пользователя исполнителя - user // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ДелегироватьЗадачу(Знач URL, Знач IDЗадачи, Знач IDПользователя, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "tasks.task.delegate"); OPI_Инструменты.ДобавитьПоле("taskId", IDЗадачи , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("userId", IDПользователя, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Добавить задачу в избранное // Добавляет задачу в список избранного -// +// // Примечание: // Метод в документации API: [tasks.task.favorite.add](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_favorite_add.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ДобавитьЗадачуВИзбранное(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.favorite.add", Токен); Возврат Ответ; - + КонецФункции // Убрать задачу из избранного // Удаляет задачу из списка избранного -// +// // Примечание: // Метод в документации API: [tasks.task.favorite.remove](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_favorite_remove.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УбратьЗадачуИзИзбранного(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.favorite.remove", Токен); Возврат Ответ; - + КонецФункции // Получить историю задачи // Получает историю изменений задачи -// +// // Примечание: // Метод в документации API: [tasks.task.history.list](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_history_list.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьИсториюЗадачи(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.history.list", Токен); Возврат Ответ; - + КонецФункции // Проверить доступ к задаче // Проверяет доступность задачи для пользователей -// +// // Примечание: // Метод в документации API: [tasks.task.getaccess](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_getaccess.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Пользователи - Массив из Строка - ID пользователей для проверки доступа - users // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПроверитьДоступКЗадаче(Знач URL, Знач IDЗадачи, Знач Пользователи = "", Знач Токен = "") Экспорт Параметры = НормализоватьАвторизацию(URL, Токен, "tasks.task.getaccess"); OPI_Инструменты.ДобавитьПоле("taskId", IDЗадачи , "Строка" , Параметры); - OPI_Инструменты.ДобавитьПоле("users" , Пользователи, "Массив", Параметры); - + OPI_Инструменты.ДобавитьПоле("users" , Пользователи, "Массив" , Параметры); + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Отключить звук задачи // Устанавливает режим Без звука для задачи -// +// // Примечание: // Метод в документации API: [tasks.task.mute](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/mute_unmute.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ОтключитьЗвукЗадачи(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.mute", Токен); Возврат Ответ; - + КонецФункции // Включить звук задачи // Отключает режим Без звука для задачи -// +// // Примечание: // Метод в документации API: [tasks.task.unmute](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/mute_unmute.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ВключитьЗвукЗадачи(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.unmute", Токен); Возврат Ответ; - + КонецФункции // Создать зависимость задач // Создает зависимость одной задачи от другой -// +// // Примечание: // Метод в документации API: [task.dependence.add](@dev.1c-bitrix.ru/rest_help/tasks/task/dependence/task_dependence_add.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDИсточника - Строка, Число - ID задачи источника связи - taskfrom // IDПриемника - Строка, Число - ID задачи приемника связи - taskto // ТипСвязи - Строка, Число - Тип связи: 0 старт>старт, 1 старт>финиш, 2 финиш>старт, 3 финиш>финиш - linktype // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция СоздатьЗависимостьЗадач(Знач URL, Знач IDИсточника, Знач IDПриемника, Знач ТипСвязи, Знач Токен = "") Экспорт - + Строка_ = "Строка"; - + OPI_ПреобразованиеТипов.ПолучитьСтроку(ТипСвязи); - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.dependence.add"); OPI_Инструменты.ДобавитьПоле("taskIdFrom", IDИсточника, Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("taskIdTo" , IDПриемника, Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("linkType" , ТипСвязи , Строка_, Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Удалить зависимость задач // Удаляет зависимость одной задачи от другой -// +// // Примечание: // Метод в документации API: [task.dependence.delete](@dev.1c-bitrix.ru/rest_help/tasks/task/dependence/task_dependence_delete.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDИсточника - Строка, Число - ID задачи источника связи - taskfrom // IDПриемника - Строка, Число - ID задачи приемника связи - taskto // ТипСвязи - Строка, Число - Тип связи: 0 старт>старт, 1 старт>финиш, 2 финиш>старт, 3 финиш>финиш - linktype // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УдалитьЗависимостьЗадач(Знач URL, Знач IDИсточника, Знач IDПриемника, Знач ТипСвязи, Знач Токен = "") Экспорт - + Строка_ = "Строка"; - + OPI_ПреобразованиеТипов.ПолучитьСтроку(ТипСвязи); - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.dependence.delete"); OPI_Инструменты.ДобавитьПоле("taskIdFrom", IDИсточника, Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("taskIdTo" , IDПриемника, Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("linkType" , ТипСвязи , Строка_, Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить план задач на день // Получает план задач на день текущего пользователя -// +// // Примечание: // Метод в документации API: [task.planner.getlist](@dev.1c-bitrix.ru/rest_help/tasks/task/planner/getlist.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьПланЗадачНаДень(Знач URL, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.planner.getlist"); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить структуру задачи // Получает структуру с описанем полей для создания задачи -// +// // Примечание: // Метод в документации API: [tasks.task.getFields](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_getFields.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьСтруктуруЗадачи(Знач URL, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "tasks.task.getFields"); - Ответ = OPI_Инструменты.Get(URL, Параметры); - + Ответ = OPI_Инструменты.Get(URL, Параметры); + Возврат Ответ; - -КонецФункции + +КонецФункции // Получить структуру фильтра задач // Возвращает структуру полей для фильтрации задач в методе ПолучитьСписокЗадач -// +// // Параметры: // Пустая - Булево - Истина > структура с пустыми значениями, Ложь > в значениях будут описания полей - empty -// +// // Возвращаемое значение: -// Структура Из КлючИЗначение - Структура полей +// Структура Из КлючИЗначение - Структура полей Функция ПолучитьСтруктуруФильтраЗадач(Знач Пустая = Ложь) Экспорт - + // Подробнее // https://dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_list.php - + OPI_ПреобразованиеТипов.ПолучитьБулево(Пустая); - + СтруктураФильтра = Новый Структура; СтруктураФильтра.Вставить("ID" , "<идентификатор задачи>"); СтруктураФильтра.Вставить("PARENT_ID" , "<идентификатор родительской задачи>"); @@ -1013,7 +1013,7 @@ СтруктураФильтра.Вставить("UF_CRM_TASK" , "<элементы CRM>"); СтруктураФильтра.Вставить("STATUS" , "<статус для сортировки. Аналогичен REAL_STATUS, но имеет дополнительно три мета-статуса>"); - + Если Пустая Тогда Для Каждого Фильтр Из СтруктураФильтра Цикл Фильтр.Значение = ""; @@ -1022,7 +1022,7 @@ //@skip-check constructor-function-return-section Возврат СтруктураФильтра; - + КонецФункции #КонецОбласти @@ -1031,185 +1031,185 @@ // Добавить элемент чеклиста задачи // Добавляет новый элемент чеклиста задачи -// +// // Примечание: // Метод в документации API: [task.checklistitem.add](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/add.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число, Строка - ID задачи - task // Текст - Строка - Текст (заголовок) пункта чек листа - text // Выполнен - Булево - Отметить пункт как выполненный - complete // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ДобавитьЭлементЧеклистаЗадачи(Знач URL, Знач IDЗадачи, Знач Текст, Знач Выполнен = Ложь, Токен = "") Экспорт - + Строка_ = "Строка"; - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.checklistitem.add"); Поля = Новый Структура; - + ПривестиБулево(Выполнен); - + OPI_Инструменты.ДобавитьПоле("TITLE" , Текст , Строка_, Поля); OPI_Инструменты.ДобавитьПоле("IS_COMPLETE", Выполнен, Строка_, Поля); - + OPI_Инструменты.ДобавитьПоле("TASKID", IDЗадачи, Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("FIELDS", Поля , "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Изменить элемент чеклиста задачи // Изменяет текст элемента чеклиста задачи -// +// // Примечание: // Метод в документации API: [task.checklistitem.update](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/update.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число, Строка - ID задачи - task // IDЭлемента - Число, Строка - ID элемента чеклиста - element // Текст - Строка - Текст (заголовок) пункта чек листа - text // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ИзменитьЭлементЧеклистаЗадачи(Знач URL, Знач IDЗадачи, Знач IDЭлемента, Знач Текст, Знач Токен = "") Экспорт - + Строка_ = "Строка"; - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.checklistitem.update"); Поля = Новый Структура; - + OPI_Инструменты.ДобавитьПоле("TITLE", Текст, Строка_, Поля); - + OPI_Инструменты.ДобавитьПоле("TASKID", IDЗадачи , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("ITEMID", IDЭлемента, Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("FIELDS", Поля , "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции - + // Удалить элемент чеклиста задачи // Удаляет элемент из чеклиста задачи -// +// // Примечание: // Метод в документации API: [task.checklistitem.delete](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/delete.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число, Строка - ID задачи - task // IDЭлемента - Число, Строка - ID элемента для удаления - element // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УдалитьЭлементЧеклистаЗадачи(Знач URL, Знач IDЗадачи, Знач IDЭлемента, Знач Токен = "") Экспорт Ответ = УправлениеЭлементомЧеклиста(URL, IDЗадачи, IDЭлемента, "task.checklistitem.delete", Токен); - + Возврат Ответ; - + КонецФункции // Получить чеклист задачи // Получает список элементов чеклиста задачи -// +// // Примечание: // Метод в документации API: [task.checklistitem.getlist](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/getlist.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число, Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьЧеклистЗадачи(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.checklistitem.getlist"); - + OPI_Инструменты.ДобавитьПоле("TASKID", IDЗадачи , "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить элемент чеклиста задачи // Получить элемент чеклиста задачи по ID -// +// // Примечание: // Метод в документации API: [task.checklistitem.get](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/get.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число, Строка - ID задачи - task // IDЭлемента - Число, Строка - ID элемента для получения - element // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьЭлементЧеклистаЗадачи(Знач URL, Знач IDЗадачи, Знач IDЭлемента, Знач Токен = "") Экспорт - + Ответ = УправлениеЭлементомЧеклиста(URL, IDЗадачи, IDЭлемента, "task.checklistitem.get", Токен); - + Возврат Ответ; - + КонецФункции // Выполнить элемент чеклиста задачи // Помечает элемент чеклиста задачи как выполненный -// +// // Примечание: // Метод в документации API: [task.checklistitem.complete](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/complete.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число, Строка - ID задачи - task // IDЭлемента - Число, Строка - ID элемента - element // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ВыполнитьЭлементЧеклистаЗадачи(Знач URL, Знач IDЗадачи, Знач IDЭлемента, Знач Токен = "") Экспорт - + Ответ = УправлениеЭлементомЧеклиста(URL, IDЗадачи, IDЭлемента, "task.checklistitem.complete", Токен); - + Возврат Ответ; - + КонецФункции // Возобновить элемент чеклиста задачи -// Снимает пометку элемента как выполненного -// +// Снимает пометку элемента как выполненного +// // Примечание: // Метод в документации API: [task.checklistitem.renew](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/renew.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число, Строка - ID задачи - task // IDЭлемента - Число, Строка - ID элемента - element // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ВозобновитьЭлементЧеклистаЗадачи(Знач URL, Знач IDЗадачи, Знач IDЭлемента, Знач Токен = "") Экспорт - + Ответ = УправлениеЭлементомЧеклиста(URL, IDЗадачи, IDЭлемента, "task.checklistitem.renew", Токен); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -1218,15 +1218,15 @@ // Получить список комментариев задачи // Полчает список комментариев пользователей к задаче по ID -// +// // Примечание: // Метод в документации API: [task.commentitem.getlist](@dev.1c-bitrix.ru/rest_help/tasks/task/commentitem/getlist.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число, Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьСписокКомментариевЗадачи(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт @@ -1238,203 +1238,203 @@ // Получить комменатрий задачи // Получает информацию о комментарии задачи по ID -// +// // Примечание: // Метод в документации API: [task.commentitem.get](@dev.1c-bitrix.ru/rest_help/tasks/task/commentitem/get.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число, Строка - ID задачи - task // IDКомментария - Число, Строка - ID комментария - comment // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьКомменатрийЗадачи(Знач URL, Знач IDЗадачи, Знач IDКомментария, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.commentitem.get"); OPI_Инструменты.ДобавитьПоле("TASKID", IDЗадачи , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("ITEMID", IDКомментария, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Добавить комментарий задачи // Создает комментарий к задаче -// +// // Примечание: // Метод в документации API: [task.commentitem.add](@dev.1c-bitrix.ru/rest_help/tasks/task/commentitem/add.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число, Строка - ID задачи - task // Текст - Строка - Текст комментария - text // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ДобавитьКомментарийЗадачи(Знач URL, Знач IDЗадачи, Знач Текст, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.commentitem.add"); - + Комментарий = Новый Структура; OPI_Инструменты.ДобавитьПоле("POST_MESSAGE", Текст, "Строка", Комментарий); - + OPI_Инструменты.ДобавитьПоле("TASKID", IDЗадачи , "Строка" , Параметры); OPI_Инструменты.ДобавитьПоле("FIELDS", Комментарий, "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Изменить комментарий задачи // Изменяет текст комментария задачи -// +// // Примечание: // Метод в документации API: [task.commentitem.update](@dev.1c-bitrix.ru/rest_help/tasks/task/commentitem/update.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число, Строка - ID задачи - task // IDКомментария - Число, Строка - ID комментария - comment // Текст - Строка - Текст комментария - text // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ИзменитьКомментарийЗадачи(Знач URL, Знач IDЗадачи, Знач IDКомментария, Знач Текст, Знач Токен = "") Экспорт - + Строка_ = "Строка"; - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.commentitem.update"); - + Комментарий = Новый Структура; OPI_Инструменты.ДобавитьПоле("POST_MESSAGE", Текст, "Строка", Комментарий); - + OPI_Инструменты.ДобавитьПоле("TASKID", IDЗадачи , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("ITEMID", IDКомментария, Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("FIELDS", Комментарий , "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Удалить комментарий // Удаляет существующий комментарий задачи -// +// // Примечание: // Метод в документации API: [task.commentitem.delete](@dev.1c-bitrix.ru/rest_help/tasks/task/commentitem/delete.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число, Строка - ID задачи - task // IDКомментария - Число, Строка - ID удаляемого комментария - comment // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УдалитьКомментарийЗадачи(Знач URL, Знач IDЗадачи, Знач IDКомментария, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.commentitem.delete"); OPI_Инструменты.ДобавитьПоле("TASKID", IDЗадачи , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("ITEMID", IDКомментария, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить список результатов // Получает список результатов задачи -// +// // Примечание: // Метод в документации API: [tasks.task.result.list](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_result.list.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьСписокРезультатов(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.result.list", Токен); Возврат Ответ; - + КонецФункции // Создать результат из комментария // Создает результат задачи из комментария -// +// // Примечание: // Метод в документации API: [tasks.task.result.addFromComment](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_result_addFromComment.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDКомментария - Число, Строка - ID комментария - comment // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция СоздатьРезультатИзКомментария(Знач URL, Знач IDКомментария, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "tasks.task.result.addFromComment"); OPI_Инструменты.ДобавитьПоле("commentId", IDКомментария, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Удалить результат из комментария // Удаляет ранее созданный результат из комментария -// +// // Примечание: // Метод в документации API: [tasks.task.result.deleteFromComment](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_result_deleteFromComment.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDКомментария - Число, Строка - ID комментария - comment // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УдалитьРезультатИзКомментария(Знач URL, Знач IDКомментария, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "tasks.task.result.deleteFromComment"); OPI_Инструменты.ДобавитьПоле("commentId", IDКомментария, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить структуру комментария // Получает структуру полей комментария -// +// // Параметры: // Пустая - Булево - Истина > структура с пустыми значениями, Ложь > в значениях будут описания полей - empty -// +// // Возвращаемое значение: -// Структура Из КлючИЗначение - Структура полей +// Структура Из КлючИЗначение - Структура полей Функция ПолучитьСтруктуруКомментария(Знач Пустая = Ложь) Экспорт - + // Подробнее // https://dev.1c-bitrix.ru/rest_help/tasks/task/commentitem/add.php - + OPI_ПреобразованиеТипов.ПолучитьБулево(Пустая); - + СтруктураПолей = Новый Структура; СтруктураПолей.Вставить("AUTHOR_ID" , "<идентификатор автора комментария>"); СтруктураПолей.Вставить("AUTHOR_NAME" , "<Имя пользователя (опционально)>"); @@ -1442,16 +1442,16 @@ СтруктураПолей.Вставить("USE_SMILES" , "<(Y|N) - парсить или нет комментарии на наличие смайлов>"); СтруктураПолей.Вставить("POST_MESSAGE" , "<Текст сообщения>"); СтруктураПолей.Вставить("UF_FORUM_MESSAGE_DOC" , "<Массив файлов с диска для прикрепления>"); - + Если Пустая Тогда Для Каждого Поле Из СтруктураПолей Цикл Поле.Значение = ""; КонецЦикла; КонецЕсли; - + //@skip-check constructor-function-return-section Возврат СтруктураПолей; - + КонецФункции #КонецОбласти @@ -1460,10 +1460,10 @@ // Добавить стадию канбана // Добавляет стабию канбана или Моего плана -// +// // Примечание: // Метод в документации API: [task.stages.add](@dev.1c-bitrix.ru/rest_help/tasks/task/kanban/task_stages_add.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Наименование - Строка - Наименование новой стадии - title @@ -1472,7 +1472,7 @@ // IDСущности - Строка, Число - ID группы или пользователя владельца канбан. Свой по умолчанию - entityid // КакАдминистратор - Булево - Позволяет добавлять стадии без проверки прав (для администраторов) - admin // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ДобавитьСтадиюКанбана(Знач URL @@ -1482,34 +1482,34 @@ , Знач IDСущности = 0 , Знач КакАдминистратор = Ложь , Знач Токен = "") Экспорт - + Строка_ = "Строка"; - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.stages.add"); Поля = Новый Структура; - + ПривестиБулево(КакАдминистратор); - + OPI_Инструменты.ДобавитьПоле("TITLE" , Наименование , Строка_, Поля); OPI_Инструменты.ДобавитьПоле("COLOR" , Цвет , Строка_, Поля); OPI_Инструменты.ДобавитьПоле("AFTER_ID" , IDПредыдущей , Строка_, Поля); OPI_Инструменты.ДобавитьПоле("ENTITY_ID", IDСущности , Строка_, Поля); OPI_Инструменты.ДобавитьПоле("isAdmin" , КакАдминистратор, Строка_, Поля); - + Параметры.Вставить("fields", Поля); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Изменить стадию канбана // Изменяет свойства существующей стадии канбана или Моего плана -// +// // Примечание: // Метод в документации API: [task.stages.update](@dev.1c-bitrix.ru/rest_help/tasks/task/kanban/task_stages_update.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Наименование - Строка - Новое наименование стадии - title @@ -1518,7 +1518,7 @@ // IDПредыдущей - Строка, Число - ID стадии, после которой необходимо вставить выбранную - prevstage // КакАдминистратор - Булево - Позволяет добавлять стадии без проверки прав (для администраторов) - admin // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ИзменитьСтадиюКанбана(Знач URL @@ -1528,91 +1528,91 @@ , Знач IDПредыдущей = 0 , Знач КакАдминистратор = Ложь , Знач Токен = "") Экспорт - + Строка_ = "Строка"; - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.stages.update"); Поля = Новый Структура; - - OPI_Инструменты.ДобавитьПоле("TITLE" , Наименование , Строка_, Поля); - OPI_Инструменты.ДобавитьПоле("COLOR" , Цвет , Строка_, Поля); - OPI_Инструменты.ДобавитьПоле("AFTER_ID" , IDПредыдущей , Строка_, Поля); + + OPI_Инструменты.ДобавитьПоле("TITLE" , Наименование , Строка_ , Поля); + OPI_Инструменты.ДобавитьПоле("COLOR" , Цвет , Строка_ , Поля); + OPI_Инструменты.ДобавитьПоле("AFTER_ID" , IDПредыдущей , Строка_ , Поля); OPI_Инструменты.ДобавитьПоле("isAdmin" , КакАдминистратор, "Булево", Поля); - + OPI_Инструменты.ДобавитьПоле("id" , IDСтадии, Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("fields", Поля , "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Удалить стадию канбана // Удаляет стадию канбана или Моего плана, при условии, что в ней нет задач -// +// // Примечание: // Метод в документации API: [task.stages.delete](@dev.1c-bitrix.ru/rest_help/tasks/task/kanban/task_stages_delete.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDСтадии - Строка, Число - ID стадии для удаления - stage // КакАдминистратор - Булево - Позволяет добавлять стадии без проверки прав (для администраторов) - admin // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УдалитьСтадиюКанбана(Знач URL, Знач IDСтадии, Знач КакАдминистратор = Ложь, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.stages.delete"); - + ПривестиБулево(КакАдминистратор); - + OPI_Инструменты.ДобавитьПоле("id" , IDСтадии , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("isAdmin", КакАдминистратор, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить стадии канбана // Получает информацию о стадиях Канбана или Моего плана -// +// // Примечание: // Метод в документации API: [task.stages.get](@dev.1c-bitrix.ru/rest_help/tasks/task/kanban/task_stages_get.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDСущности - Строка, Число - ID группы или пользователя владельца канбан. Свой по умолчанию - entityid // КакАдминистратор - Булево - Позволяет получать стадии без проверки прав (для администраторов) - admin // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьСтадииКанбана(Знач URL, Знач IDСущности = 0, Знач КакАдминистратор = Ложь, Знач Токен = "") Экспорт - + IDСущности = OPI_Инструменты.ЧислоВСтроку(IDСущности); Параметры = НормализоватьАвторизацию(URL, Токен, "task.stages.get"); - + ПривестиБулево(КакАдминистратор); - + OPI_Инструменты.ДобавитьПоле("entityId", IDСущности , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("isAdmin" , КакАдминистратор, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Перенести задачу в стадию канбана // Переносит задачу в выбранную стадию канбана -// +// // Примечание: // Метод в документации API: [task.stages.movetask](@dev.1c-bitrix.ru/rest_help/tasks/task/kanban/task_stages_movetask.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Строка, Число - ID задачи для переноса - task @@ -1620,7 +1620,7 @@ // Перед - Строка, Число - ID задачи, перед которой надо поставить выбранную (если не заполнено После) - before // После - Строка, Число - ID задачи, после которой надо поставить выбранную (если не заполнено Перед) - after // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПеренестиЗадачуВСтадиюКанбана(Знач URL @@ -1629,29 +1629,29 @@ , Знач Перед = 0 , Знач После = 0 , Знач Токен = "") Экспорт - + Строка_ = "Строка"; - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.stages.movetask"); - + OPI_Инструменты.ДобавитьПоле("id" , IDЗадачи, Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("stageId", IDСтадии, Строка_, Параметры); - + Если ЗначениеЗаполнено(Перед) Тогда - + OPI_Инструменты.ДобавитьПоле("before", Перед, Строка_, Параметры); - + Иначе - + OPI_ПреобразованиеТипов.ПолучитьСтроку(После); OPI_Инструменты.ДобавитьПоле("after", После, Строка_, Параметры); - + КонецЕсли; - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -1660,10 +1660,10 @@ // Добавить трудозатраты задачи // Добавляет информацию о затраченном времени пользователя в задачу -// +// // Примечание: // Метод в документации API: [task.elapseditem.add](@dev.1c-bitrix.ru/rest_help/tasks/task/elapseditem/add.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Строка, Число - ID задачи для добавления затрат - task @@ -1672,7 +1672,7 @@ // Текст - Строка - Текст комментария трудозатраты - text // ДатаУстановки - Строка - Дата установки трудозатрат - date // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ДобавитьТрудозатратыЗадачи(Знач URL @@ -1682,111 +1682,111 @@ , Знач Текст = "" , Знач ДатаУстановки = "" , Знач Токен = "") Экспорт - + Строка_ = "Строка"; - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.elapseditem.add"); Поля = Новый Структура; - + OPI_Инструменты.ДобавитьПоле("SECONDS" , Время , Строка_ , Поля); OPI_Инструменты.ДобавитьПоле("COMMENT_TEXT", Текст , Строка_ , Поля); OPI_Инструменты.ДобавитьПоле("USER_ID" , IDПользователя, Строка_ , Поля); OPI_Инструменты.ДобавитьПоле("CREATED_DATE", ДатаУстановки , "ДатаISO", Поля); - + OPI_Инструменты.ДобавитьПоле("TASKID" , IDЗадачи, Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("ARFIELDS", Поля , "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Удалить трудозатраты задачи // Удаляет запись о трудозатратах из задачи -// +// // Примечание: // Метод в документации API: [task.elapseditem.delete](@dev.1c-bitrix.ru/rest_help/tasks/task/elapseditem/delete.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Строка, Число - ID задачи для добавления затрат - task // IDЗаписи - Строка, Число - ID записи о трудозатратах - record // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УдалитьТрудозатратыЗадачи(Знач URL, Знач IDЗадачи, Знач IDЗаписи, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.elapseditem.delete"); - + OPI_Инструменты.ДобавитьПоле("TASKID", IDЗадачи, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("ITEMID", IDЗаписи, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить список трудозатрат задачи // Получает список записей о трудозатратах задачи -// +// // Примечание: // Метод в документации API: [task.elapseditem.getlist](@dev.1c-bitrix.ru/rest_help/tasks/task/elapseditem/getlist.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Строка, Число - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьСписокТрудозатратЗадачи(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.elapseditem.getlist"); - + OPI_Инструменты.ДобавитьПоле("TASKID", IDЗадачи, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить трудозатраты задачи // Получает информацию о записи трудозатрат задачи по ID -// +// // Примечание: // Метод в документации API: [task.elapseditem.get](@dev.1c-bitrix.ru/rest_help/tasks/task/elapseditem/get.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Строка, Число - ID задачи - task // IDЗаписи - Строка, Число - ID записи о трудозатратах - record // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьТрудозатратыЗадачи(Знач URL, Знач IDЗадачи, Знач IDЗаписи, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.elapseditem.get"); - + OPI_Инструменты.ДобавитьПоле("TASKID", IDЗадачи, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("ITEMID", IDЗаписи, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Изменить трудозатраты задачи // Изменяет данные записи о трудозатратах задачи -// +// // Примечание: // Метод в документации API: [task.elapseditem.update](@dev.1c-bitrix.ru/rest_help/tasks/task/elapseditem/update.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Строка, Число - ID задачи - task @@ -1795,7 +1795,7 @@ // Текст - Строка - Текст комментария трудозатраты - text // ДатаУстановки - Строка - Дата установки трудозатрат - date // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ИзменитьТрудозатратыЗадачи(Знач URL @@ -1805,24 +1805,24 @@ , Знач Текст = "" , Знач ДатаУстановки = "" , Знач Токен = "") Экспорт - + Строка_ = "Строка"; - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.elapseditem.update"); Поля = Новый Структура; - + OPI_Инструменты.ДобавитьПоле("SECONDS" , Время , Строка_ , Поля); OPI_Инструменты.ДобавитьПоле("COMMENT_TEXT", Текст , Строка_ , Поля); OPI_Инструменты.ДобавитьПоле("CREATED_DATE", ДатаУстановки , "ДатаISO", Поля); - + OPI_Инструменты.ДобавитьПоле("TASKID" , IDЗадачи, Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("ITEMID" , IDЗаписи, Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("ARFIELDS", Поля , "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -1831,142 +1831,142 @@ // Получить список хранилищ // Получает список доступных хранилищ файлов -// +// // Примечание: // Метод в документации API: [disk.storage.getlist](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_getlist.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьСписокХранилищ(Знач URL, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.storage.getlist"); Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; КонецФункции // Получить хранилище приложения // Получает информацию о хранилище с которым может работать приложение для хранения своих данных -// +// // Примечание: // Метод в документации API: [disk.storage.getforapp](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_getforapp.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьХранилищеПриложения(Знач URL, Знач Токен = "") Экспорт - - Параметры = НормализоватьАвторизацию(URL, Токен, "disk.storage.getforapp"); + + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.storage.getforapp"); Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить хранилище // Получает информацию о хранилище по ID -// +// // Примечание: // Метод в документации API: [disk.storage.get](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_get.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDХранилища - Строка, Число - Идентификатор хранилища - storageid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьХранилище(Знач URL, Знач IDХранилища, Знач Токен = "") Экспорт - + Ответ = УправлениеФайлом(URL, IDХранилища, "disk.storage.get", Токен); Возврат Ответ; - + КонецФункции // Переименовать хранилище // Изменяет имя хранилища (только для хранилища приложения см. ПолучитьСписокХранилищПриложения) -// +// // Примечание: // Метод в документации API: [disk.storage.rename](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_rename.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDХранилища - Строка, Число - Идентификатор хранилища - storageid // Наименование - Строка - Новое наименование хранилища - title // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПереименоватьХранилище(Знач URL, Знач IDХранилища, Знач Наименование, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.storage.rename"); - + OPI_Инструменты.ДобавитьПоле("id" , IDХранилища , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("newName", Наименование, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить содержимое хранилища // Получает список файлов и каталогов, находящихся в корне хранилища -// +// // Примечание: // Метод в документации API: [disk.storage.getchildren](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_getchildren.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDХранилища - Строка, Число - Идентификатор хранилища - storageid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьСодержимоеХранилища(Знач URL, Знач IDХранилища, Знач Токен = "") Экспорт - + Ответ = УправлениеФайлом(URL, IDХранилища, "disk.storage.getchildren", Токен); Возврат Ответ; - + КонецФункции // Создать каталог в хранилище // Создает пустой каталог в хранилище -// +// // Примечание: // Метод в документации API: [disk.storage.addfolder](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_addfolder.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDХранилища - Строка - Идентификатор хранилища - storageid // Наименование - Строка - Имя каталога - title // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция СоздатьКаталогВХранилище(Знач URL, Знач IDХранилища, Знач Наименование, Знач Токен = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Наименование); - + СтруктураПапки = Новый Структура("NAME", Наименование); - + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.storage.addfolder"); - + OPI_Инструменты.ДобавитьПоле("id" , IDХранилища , "Строка" , Параметры); OPI_Инструменты.ДобавитьПоле("data", СтруктураПапки, "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции #КонецОбласти @@ -1975,279 +1975,279 @@ // Получить информацию о каталоге // Получает информацию о каталоге -// +// // Примечание: // Метод в документации API: [disk.folder.get](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_get.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDКаталога - Строка, Число - Идентификатор каталога - folderid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьИнформациюОКаталоге(Знач URL, Знач IDКаталога, Знач Токен = "") Экспорт - + Ответ = УправлениеФайлом(URL, IDКаталога, "disk.folder.get", Токен); Возврат Ответ; - + КонецФункции // Создать подкаталог // Создает каталог внутри другого каталога -// +// // Примечание: // Метод в документации API: [disk.folder.addsubfolder](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_addsubfolder.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDКаталога - Строка, Число - Идентификатор каталога родителя - folderid // Наименование - Строка - Наименование нового каталога - title // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция СоздатьПодкаталог(Знач URL, Знач IDКаталога, Знач Наименование, Знач Токен = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Наименование); - + СтруктураПапки = Новый Структура("NAME", Наименование); - + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.folder.addsubfolder"); - + OPI_Инструменты.ДобавитьПоле("id" , IDКаталога , "Строка" , Параметры); OPI_Инструменты.ДобавитьПоле("data", СтруктураПапки, "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции // Скопировать каталог // Копирует один каталог в другой -// +// // Примечание: // Метод в документации API: [disk.folder.copyto](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_copyto.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDКаталога - Строка, Число - Идентификатор каталога - folderid // IDПриемника - Строка, Число - ID каталога назначения - tagetid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция СкопироватьКаталог(Знач URL, Знач IDКаталога, Знач IDПриемника, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.folder.copyto"); - + OPI_Инструменты.ДобавитьПоле("id" , IDКаталога , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("targetFolderId", IDПриемника, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции // Переместить каталог // Перемещает один каталог внутрь другого -// +// // Примечание: // Метод в документации API: [disk.folder.moveto](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_moveto.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDКаталога - Строка, Число - Идентификатор каталога - folderid // IDПриемника - Строка, Число - ID каталога назначения - tagetid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПереместитьКаталог(Знач URL, Знач IDКаталога, Знач IDПриемника, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.folder.moveto"); - + OPI_Инструменты.ДобавитьПоле("id" , IDКаталога , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("targetFolderId", IDПриемника, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции // Удалить каталог // Удаляет каталог с подкаталогами -// +// // Примечание: // Метод в документации API: [disk.folder.deletetree](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_deletetree.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDКаталога - Строка, Число - Идентификатор удаляемого каталога - folderid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УдалитьКаталог(Знач URL, Знач IDКаталога, Знач Токен = "") Экспорт - + Ответ = УправлениеФайлом(URL, IDКаталога, "disk.folder.deletetree", Токен); Возврат Ответ; - + КонецФункции // Получить внешнюю ссылку каталога // Получает внешнюю ссылку для доступа к каталогу -// +// // Примечание: // Метод в документации API: [disk.folder.getExternalLink](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_getexternallink.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDКаталога - Строка, Число - Идентификатор каталога - folderid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьВнешнююСсылкуКаталога(Знач URL, Знач IDКаталога, Знач Токен = "") Экспорт - + Ответ = УправлениеФайлом(URL, IDКаталога, "disk.folder.getExternalLink", Токен); Возврат Ответ; - + КонецФункции // Получить дочерние элементы каталога // Получает дочерние элементы каталога -// +// // Примечание: // Метод в документации API: [disk.folder.getchildren](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_getchildren.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDКаталога - Строка, Число - Идентификатор каталога - folderid // Фильтр - Структура из КлючИЗначение - Отбор элементов (См. ПолучитьСтруктуруФильтраКаталога) - filter // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьДочерниеЭлементыКаталога(Знач URL, Знач IDКаталога, Знач Фильтр = "", Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.folder.getchildren"); OPI_Инструменты.ДобавитьПоле("id" , IDКаталога, "Строка" , Параметры); OPI_Инструменты.ДобавитьПоле("filter", Фильтр , "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Поместить каталог в корзину // Перемещает каталог в корзину удаляемых файлов -// +// // Примечание: // Метод в документации API: [disk.folder.markdeleted](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_markdeleted.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDКаталога - Строка, Число - Идентификатор каталога - folderid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПоместитьКаталогВКорзину(Знач URL, Знач IDКаталога, Знач Токен = "") Экспорт - + Ответ = УправлениеФайлом(URL, IDКаталога, "disk.folder.markdeleted", Токен); Возврат Ответ; - + КонецФункции // Восстановить каталог // Восстанавливает каталог из корзины -// +// // Примечание: // Метод в документации API: [disk.folder.restore](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_restore.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDКаталога - Строка, Число - Идентификатор каталога - folderid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ВосстановитьКаталог(Знач URL, Знач IDКаталога, Знач Токен = "") Экспорт - + Ответ = УправлениеФайлом(URL, IDКаталога, "disk.folder.restore", Токен); - Возврат Ответ; - + Возврат Ответ; + КонецФункции // Переименовать каталог // Изменяет имя каталога -// +// // Примечание: // Метод в документации API: [disk.folder.rename](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_rename.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDКаталога - Строка, Число - Идентификатор каталога - folderid // Наименование - Строка - Новое наименование каталога - title // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПереименоватьКаталог(Знач URL, Знач IDКаталога, Знач Наименование, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.folder.rename"); - + OPI_Инструменты.ДобавитьПоле("id" , IDКаталога , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("newName", Наименование, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции // Получить структуру фильтра каталога // Возвращает структуру полей для фильтрации дочерних элементов каталога -// +// // Примечание: // Метод в документации API: [disk.folder.getfields](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_getfields.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Пустая - Булево - Истина > структура с пустыми значениями, Ложь > в значениях будут описания типов полей - empty // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: -// Структура Из КлючИЗначение - Структура полей +// Структура Из КлючИЗначение - Структура полей Функция ПолучитьСтруктуруФильтраКаталога(Знач URL, Знач Пустая = Ложь, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.folder.getfields"); Фильтр = Новый Структура; - + Ответ = OPI_Инструменты.Post(URL, Параметры); Поля = Ответ["result"]; - + Для Каждого Поле Из Поля Цикл - + Имя = Поле.Ключ; Описание = Поле.Значение; - + Если Описание["USE_IN_FILTER"] Тогда - - ТипДанных = ?(Пустая, "", Описание["TYPE"]); + + ТипДанных = ?(Пустая, "", Описание["TYPE"]); Фильтр.Вставить(Имя, ТипДанных); - + КонецЕсли; - + КонецЦикла; - + Возврат Фильтр; - + КонецФункции #КонецОбласти @@ -2256,18 +2256,18 @@ // Загрузить файл в хранилище // Загружает файл в выбранное хранилище -// +// // Примечание: // Метод в документации API: [disk.storage.uploadfile](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_uploadfile.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Наименование - Строка - Наименование файла с расширением для сохранения - title -// Файл - Строка, ДвоичныеДанные - Файл для загрузки - file +// Файл - Строка, ДвоичныеДанные - Файл для загрузки - file // IDХранилища - Строка - Идентификатор хранилища для загрузки - storageid // Доступы - Строка - Массив доступов по задачам, если необходимо - rights // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ЗагрузитьФайлВХранилище(Знач URL @@ -2276,118 +2276,118 @@ , Знач IDХранилища , Знач Доступы = "" , Знач Токен = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDХранилища); OPI_ПреобразованиеТипов.ПолучитьСтроку(Наименование); - + Метод = "disk.storage.uploadfile"; ДанныеФайла = Новый Структура("NAME", Наименование); СодержимоеФайла = Новый Соответствие(); СодержимоеФайла.Вставить(Наименование, Файл); - + Параметры = НормализоватьАвторизацию(URL, Токен, Метод); OPI_Инструменты.ДобавитьПоле("data" , ДанныеФайла, "Коллекция", Параметры); OPI_Инструменты.ДобавитьПоле("rights", Доступы , "Массив" , Параметры); OPI_Инструменты.ДобавитьПоле("id" , IDХранилища, "Строка" , Параметры); МассивФайла = НормализоватьФайлы(СодержимоеФайла); - + Если Не МассивФайла.Количество() = 0 Тогда Параметры.Вставить("fileContent", МассивФайла[0]); КонецЕсли; - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Загрузить файл в каталог // Загружает переданный файл в каталог -// +// // Примечание: // Метод в документации API: [disk.folder.uploadfile](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_uploadfile.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Наименование - Строка - Наименование файла с расширением для сохранения - title -// Файл - Строка, ДвоичныеДанные - Файл для загрузки - file +// Файл - Строка, ДвоичныеДанные - Файл для загрузки - file // IDКаталога - Строка - Идентификатор каталога для загрузки - folderid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ЗагрузитьФайлВКаталог(Знач URL, Знач Наименование, Знач Файл, Знач IDКаталога, Знач Токен = "") Экспорт OPI_ПреобразованиеТипов.ПолучитьСтроку(Наименование); OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Файл); - + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.folder.uploadFile"); OPI_Инструменты.ДобавитьПоле("id", IDКаталога, "Строка", Параметры); - + Ответ = OPI_Инструменты.Get(URL, Параметры); Результат = Ответ["result"]; - + Если ЗначениеЗаполнено(Результат) Тогда - + ИмяПоля = Результат["field"]; URLЗагрузки = Результат["uploadUrl"]; - + Если ЗначениеЗаполнено(ИмяПоля) И ЗначениеЗаполнено(URLЗагрузки) Тогда - + ИмяПоля = СокрЛП(ИмяПоля); URLЗагрузки = СокрЛП(URLЗагрузки); ИмяФайла = ИмяПоля + "|" + Наименование; - + СоответствиеФайла = Новый Соответствие; - СоответствиеФайла.Вставить(ИмяФайла, Файл); - - Ответ = OPI_Инструменты.PostMultipart(URLЗагрузки, , СоответствиеФайла, ""); - + СоответствиеФайла.Вставить(ИмяФайла, Файл); + + Ответ = OPI_Инструменты.PostMultipart(URLЗагрузки, , СоответствиеФайла, ""); + КонецЕсли; - - КонецЕсли; - - Возврат Ответ; - + + КонецЕсли; + + Возврат Ответ; + КонецФункции // Получить информацию о файле // Получает информацию о файле по ID -// +// // Примечание: // Метод в документации API: [disk.file.get](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_get.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDФайла - Строка, Число - Идентификатор файла - fileid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьИнформациюОФайле(Знач URL, Знач IDФайла, Знач Токен = "") Экспорт - + Ответ = УправлениеФайлом(URL, IDФайла, "disk.file.get", Токен); Возврат Ответ; - + КонецФункции // Удалить файл // Удаляет файл по ID -// +// // Примечание: // Метод в документации API: [disk.file.delete](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_delete.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDФайла - Строка, Число - Идентификатор удаляемого файла - fileid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УдалитьФайл(Знач URL, Знач IDФайла, Знач Токен = "") Экспорт - + Ответ = УправлениеФайлом(URL, IDФайла, "disk.file.delete", Токен); Возврат Ответ; @@ -2395,143 +2395,143 @@ // Получить внешнюю ссылку файла // Получает внешнюю ссылку для доступа к файлу -// +// // Примечание: // Метод в документации API: [disk.file.getExternalLink](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_getexternallink.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDФайла - Строка, Число - Идентификатор файла - fileid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьВнешнююСсылкуФайла(Знач URL, Знач IDФайла, Знач Токен = "") Экспорт - + Ответ = УправлениеФайлом(URL, IDФайла, "disk.file.getExternalLink", Токен); Возврат Ответ; - + КонецФункции // Поместить файл в корзину // Перемещает файл в корзину удаляемых файлов -// +// // Примечание: // Метод в документации API: [disk.file.markdeleted](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_markdeleted.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDФайла - Строка, Число - Идентификатор файла - fileid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПоместитьФайлВКорзину(Знач URL, Знач IDФайла, Знач Токен = "") Экспорт - + Ответ = УправлениеФайлом(URL, IDФайла, "disk.file.markdeleted", Токен); Возврат Ответ; - + КонецФункции // Восстановить файл // Восстанавливает файл из корзины -// +// // Примечание: // Метод в документации API: [disk.file.restore](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_restore.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDФайла - Строка, Число - Идентификатор файла - fileid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ВосстановитьФайл(Знач URL, Знач IDФайла, Знач Токен = "") Экспорт - + Ответ = УправлениеФайлом(URL, IDФайла, "disk.file.restore", Токен); Возврат Ответ; - + КонецФункции // Скопировать файл // Копирует файл из одного расположения в другое -// +// // Примечание: // Метод в документации API: [disk.file.copyto](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_copyto.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDФайла - Строка, Число - ID файла для копирования - fileid -// IDКаталога - Строка, Число - ID каталога размещения копии - folderid +// IDКаталога - Строка, Число - ID каталога размещения копии - folderid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция СкопироватьФайл(Знач URL, Знач IDФайла, Знач IDКаталога, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.file.copyto"); - + OPI_Инструменты.ДобавитьПоле("id" , IDФайла , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("targetFolderId", IDКаталога, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции // Переместить файл // Перемещает файл из одного расположения в другое -// +// // Примечание: // Метод в документации API: [disk.file.moveto](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_moveto.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDФайла - Строка, Число - ID файла для перемещения - fileid -// IDКаталога - Строка, Число - ID каталога нового размещения - folderid +// IDКаталога - Строка, Число - ID каталога нового размещения - folderid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПереместитьФайлВКаталог(Знач URL, Знач IDФайла, Знач IDКаталога, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.file.moveto"); - + OPI_Инструменты.ДобавитьПоле("id" , IDФайла , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("targetFolderId", IDКаталога, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции // Переименовать файл // Изменяет имя существующего файла -// +// // Примечание: // Метод в документации API: [disk.file.rename](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_rename.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDФайла - Строка, Число - Идентификатор файла - fileid // Наименование - Строка - Новое наименование каталога - title // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПереименоватьФайл(Знач URL, Знач IDФайла, Знач Наименование, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.file.rename"); - + OPI_Инструменты.ДобавитьПоле("id" , IDФайла , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("newName", Наименование, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции #КонецОбласти @@ -2540,109 +2540,109 @@ // Создать чат // Создает новый чат на основе структуры полей -// +// // Примечание: // Метод в документации API: [im.chat.add](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12093) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url -// СтруктураЧата - Структура Из КлючИЗначение - Структура полей чата. См. ПолучитьСтруктуруЧата - fields +// СтруктураЧата - Структура Из КлючИЗначение - Структура полей чата. См. ПолучитьСтруктуруЧата - fields // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция СоздатьЧат(Знач URL, Знач СтруктураЧата, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.chat.add"); - + Для Каждого Элемент Из СтруктураЧата Цикл Параметры.Вставить(Элемент.Ключ, Элемент.Значение); КонецЦикла; - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить список пользователей чата // Получает список пользователей чата по ID -// +// // Примечание: // Метод в документации API: [im.chat.user.list](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12095) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата - chat // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьСписокПользователейЧата(Знач URL, Знач IDЧата, Знач Токен = "") Экспорт - - Ответ = УправлениеЧатом(URL, IDЧата, "im.chat.user.list", Токен); + + Ответ = УправлениеЧатом(URL, IDЧата, "im.chat.user.list", Токен); Возврат Ответ; - + КонецФункции // Покинуть чат // Исключает текущего пользователя из чата -// +// // Примечание: // Метод в документации API: [im.chat.leave](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12101) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата - chat // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПокинутьЧат(Знач URL, Знач IDЧата, Знач Токен = "") Экспорт - - Ответ = УправлениеЧатом(URL, IDЧата, "im.chat.leave", Токен); + + Ответ = УправлениеЧатом(URL, IDЧата, "im.chat.leave", Токен); Возврат Ответ; - + КонецФункции // Получить пользователей // Получает информацию о пользователях для диалога -// +// // Примечание: // Метод в документации API: [im.user.list.get ](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=11493) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDПользователей - Массив Из Строка, Число - ID пользователя или нескольких пользователей - users // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьПользователей(Знач URL, Знач IDПользователей, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.user.list.get"); - + OPI_Инструменты.ДобавитьПоле("ID", IDПользователей, "Массив", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Добавить пользователей в чат // Добавляет пользователей в чат по массиву ID -// +// // Примечание: // Метод в документации API: [im.chat.user.add](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12097) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата - chat // IDПользователей - Массив из Строка, Число - ID пользователей для добавления - users // СкрытьИсторию - Булево - Скрыть старые сообщения от новых пользователей - hide // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ДобавитьПользователейВЧат(Знач URL @@ -2650,213 +2650,213 @@ , Знач IDПользователей , Знач СкрытьИсторию = Ложь , Знач Токен = "") Экспорт - + ПривестиБулево(СкрытьИсторию); - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.chat.user.add"); - + OPI_Инструменты.ДобавитьПоле("CHAT_ID" , IDЧата , "Строка" , Параметры); OPI_Инструменты.ДобавитьПоле("USERS" , IDПользователей, "Коллекция", Параметры); OPI_Инструменты.ДобавитьПоле("HIDE_HISTORY", СкрытьИсторию , "Строка" , Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Исключить пользователя из чата // Исключает выбранного пользователя из чата -// +// // Примечание: // Метод в документации API: [im.chat.user.delete](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12099) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата - chat // IDПользователя - Строка, Число - ID пользователя - user // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ИсключитьПользователяИзЧата(Знач URL, Знач IDЧата, Знач IDПользователя, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.chat.user.delete"); - + OPI_Инструменты.ДобавитьПоле("CHAT_ID", IDЧата , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("USER_ID", IDПользователя, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Изменить заголовок чата // Изменяет текст заголовка чата -// +// // Примечание: // Метод в документации API: [im.chat.updateTitle](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12105) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата - chat // Заголовок - Строка - Новый текст заголовка - title // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ИзменитьЗаголовокЧата(Знач URL, Знач IDЧата, Знач Заголовок, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.chat.updateTitle"); - + OPI_Инструменты.ДобавитьПоле("CHAT_ID", IDЧата , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("TITLE" , Заголовок, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Изменить цвет чата // Изменяет цвет чата для мобильного приложения -// +// // Примечание: // Метод в документации API: [im.chat.updateTitle](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12105) // Доступные цвета: RED, GREEN, MINT, LIGHT_BLUE, DARK_BLUE, PURPLE, AQUA, PINK, LIME, BROWN, AZURE, KHAKI, SAND, MARENGO, GRAY, GRAPHITE -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата - chat // Цвет - Строка - Новый цвет чата - color // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ИзменитьЦветЧата(Знач URL, Знач IDЧата, Знач Цвет, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.chat.updateColor"); - + OPI_Инструменты.ДобавитьПоле("CHAT_ID", IDЧата, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("COLOR" , Цвет , "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Изменить картинку чата // Устанавливает новую картинку чата -// +// // Примечание: // Метод в документации API: [im.chat.updateAvatar](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12109) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата - chat // Картинка - Строка, ДвоичныеДанные - Данные файла картинки - picture // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ИзменитьКартинкуЧата(Знач URL, Знач IDЧата, Знач Картинка, Знач Токен = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Картинка); - + Картинка = Base64Строка(Картинка); Параметры = НормализоватьАвторизацию(URL, Токен, "im.chat.updateAvatar"); - + OPI_Инструменты.ДобавитьПоле("CHAT_ID", IDЧата , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("AVATAR" , Картинка, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Сменить владельца чата // Изменяет пользователя владельца чата -// +// // Примечание: // Метод в документации API: [im.chat.setOwner](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12111) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата - chat // IDПользователя - Строка, Число - ID пользователя - user // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция СменитьВладельцаЧата(Знач URL, Знач IDЧата, Знач IDПользователя, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.chat.setOwner"); - + OPI_Инструменты.ДобавитьПоле("CHAT_ID", IDЧата , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("USER_ID", IDПользователя, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Отключить уведомления чата // Отключает уведомлений чата -// +// // Примечание: // Метод в документации API: [im.chat.mute](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=11473) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата - chat // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ОтключитьУведомленияЧата(Знач URL, Знач IDЧата, Знач Токен = "") Экспорт - + Ответ = УправлениеЗвукомЧата(URL, IDЧата, Истина, Токен); Возврат Ответ; - + КонецФункции // Включить уведомления чата // Включает уведомления в чате -// +// // Примечание: // Метод в документации API: [im.chat.mute](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=11473) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата - chat // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ВключитьУведомленияЧата(Знач URL, Знач IDЧата, Знач Токен = "") Экспорт - + Ответ = УправлениеЗвукомЧата(URL, IDЧата, Ложь, Токен); Возврат Ответ; - + КонецФункции // Получить список сообщений чата // Получает список из 20 сообщений чата или диалога, в зависимости от указания IDПервого и IDПоследнего -// +// // Примечание: // Метод в документации API: [im.dialog.messages.get](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=11479) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата (chatXXX) или пользователя (XXX) для диалога - chat // IDПоследнего - Строка, Число - ID последнего загруженного сообщения - last // IDПервого - Строка, Число - ID первого загруженного сообщения - first // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьСписокСообщенийЧата(Знач URL @@ -2864,199 +2864,199 @@ , Знач IDПоследнего = "" , Знач IDПервого = "" , Знач Токен = "") Экспорт - + Строка_ = "Строка"; - + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDПоследнего); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDПервого); - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.dialog.messages.get"); - + OPI_Инструменты.ДобавитьПоле("DIALOG_ID", IDЧата , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("LAST_ID" , IDПоследнего, Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("FIRST_ID" , IDПервого , Строка_, Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить диалог // Получает информацию о диалоге по ID -// +// // Примечание: // Метод в документации API: [im.dialog.get](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12886) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата (chatXXX) или пользователя (XXX) для диалога - chat // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьДиалог(Знач URL, Знач IDЧата, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.dialog.get"); - + OPI_Инструменты.ДобавитьПоле("DIALOG_ID", IDЧата, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить список пользователей диалога // Получает список участников далога -// +// // Примечание: // Метод в документации API: [im.dialog.users.list](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=23800) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата (chatXXX) или пользователя (XXX) для диалога - chat // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьСписокПользователейДиалога(Знач URL, Знач IDЧата, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.dialog.users.list"); - + OPI_Инструменты.ДобавитьПоле("DIALOG_ID", IDЧата, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Отправить уведомление о вводе // Отправляет в чат статус Вам пишут... -// +// // Примечание: // Метод в документации API: [im.dialog.writing](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=23802) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата (chatXXX) или пользователя (XXX) для диалога - chat // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ОтправитьУведомлениеОВводе(Знач URL, Знач IDЧата, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.dialog.writing"); - + OPI_Инструменты.ДобавитьПоле("DIALOG_ID", IDЧата, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить статус пользователя // Получает статус (онлайн) текущего пользователя -// +// // Примечание: // Метод в документации API: [im.user.status.get](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=11497) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьСтатусПользователя(Знач URL, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.user.status.get"); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Установить статус пользователя // Устанавливает статус (онлайн) текущего пользователя -// +// // Примечание: // Метод в документации API: [im.user.status.set](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=11499) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Статус - Строка, Число - Статус пользователя: online, dnd, away - status // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УстановитьСтатусПользователя(Знач URL, Знач Статус, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.user.status.set"); - + OPI_Инструменты.ДобавитьПоле("STATUS", Статус, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Прочитать все // Отмечает все сообщения во всех доступных чатах как прочитанные -// +// // Примечание: // Метод в документации API: [im.dialog.read.all](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=23804) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПрочитатьВсе(Знач URL, Знач Токен = "") Экспорт - - Параметры = НормализоватьАвторизацию(URL, Токен, "im.dialog.read.all"); + + Параметры = НормализоватьАвторизацию(URL, Токен, "im.dialog.read.all"); Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить каталог файлов чата // Получает каталог для хранения фйлов чата -// +// // Примечание: // Метод в документации API: [im.disk.folder.get](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=11483) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата - chat // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьКаталогФайловЧата(Знач URL, Знач IDЧата, Знач Токен = "") Экспорт - - Ответ = УправлениеЧатом(URL, IDЧата, "im.disk.folder.get", Токен); + + Ответ = УправлениеЧатом(URL, IDЧата, "im.disk.folder.get", Токен); Возврат Ответ; - + КонецФункции // Получить структуру чата // Получает структуру полей чата -// +// // Параметры: // Пустая - Булево - Истина > структура с пустыми значениями, Ложь > в значениях будут описания типов полей - empty -// +// // Возвращаемое значение: -// Структура Из КлючИЗначение - Структура полей +// Структура Из КлючИЗначение - Структура полей Функция ПолучитьСтруктуруЧата(Знач Пустая = Ложь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьБулево(Пустая); - + СтруктураЧата = Новый Структура; СтруктураЧата.Вставить("TYPE" , "<Тип чата OPEN (публичный) | CHAT (по приглашениям)>"); СтруктураЧата.Вставить("TITLE" , "<Заголовок чата>"); @@ -3066,7 +3066,7 @@ СтруктураЧата.Вставить("USERS" , "<Массив участников чата>"); СтруктураЧата.Вставить("AVATAR" , "<Аватар чата в base64 формате>"); СтруктураЧата.Вставить("OWNER_ID" , "<Идентификатор владельца чата. Текущий пользователь, если не указано>"); - + Если Пустая Тогда Для Каждого Элемент Из СтруктураЧата Цикл Элемент.Значение = ""; @@ -3075,7 +3075,7 @@ //@skip-check constructor-function-return-section Возврат СтруктураЧата; - + КонецФункции #КонецОбласти @@ -3084,253 +3084,253 @@ // Отправить сообщение // Отправляет сообщение в диалог -// +// // Примечание: // Метод в документации API: [im.message.add](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12115) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата (chatXXX) или пользователя (XXX) для диалога - chat // Текст - Строка - Текст сообщения - text // Вложения - Массив из Структура - Массив блоков вложений - blocks // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ОтправитьСообщение(Знач URL, Знач IDЧата, Знач Текст, Знач Вложения = "", Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.message.add"); - + OPI_Инструменты.ДобавитьПоле("DIALOG_ID", IDЧата , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("MESSAGE" , Текст , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("ATTACH" , Вложения, "Массив", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Изменить сообщение // Изменяет сообщение в диалоге -// +// // Примечание: // Метод в документации API: [im.message.update](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12117) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDСообщения - Строка, Число - ID сообщения для изменения - message // Текст - Строка - Новый текст сообщения - text // Вложения - Массив из Структура - Новый массив блоков вложений - blocks // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ИзменитьСообщение(Знач URL, Знач IDСообщения, Знач Текст = "", Знач Вложения = "", Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.message.update"); - + OPI_Инструменты.ДобавитьПоле("MESSAGE_ID", IDСообщения, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("MESSAGE" , Текст , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("ATTACH" , Вложения , "Массив", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Установить реакцию на сообщение // Устанавливает или снимает реакцию на сообщение -// +// // Примечание: // Метод в документации API: [im.message.like](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12121) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDСообщения - Строка, Число - ID сообщения - message // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УстановитьРеакциюНаСообщение(Знач URL, Знач IDСообщения, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.message.like"); - + OPI_Инструменты.ДобавитьПоле("MESSAGE_ID", IDСообщения, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Удалить сообщение // Удаляет сообщение в диалоге -// +// // Примечание: // Метод в документации API: [im.message.delete](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12119) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDСообщения - Строка, Число - ID сообщения для удаления - message // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УдалитьСообщение(Знач URL, Знач IDСообщения, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.message.delete"); - + OPI_Инструменты.ДобавитьПоле("MESSAGE_ID", IDСообщения , "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Отправить файл // Отправляет файл диска в чат по ID -// +// // Примечание: // Метод в документации API: [im.disk.file.commit](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=11485) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата - chat // IDФайла - Строка, Число - ID файла, загруженного при помощи ЗагрузитьФайлВКаталог - fileid // Описание - Строка - Описание файла - description // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ОтправитьФайл(Знач URL, Знач IDЧата, Знач IDФайла, Знач Описание = "", Знач Токен = "") Экспорт - + Строка_ = "Строка"; - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.disk.file.commit"); - + OPI_Инструменты.ДобавитьПоле("CHAT_ID" , IDЧата , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("UPLOAD_ID", IDФайла , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("MESSAGE" , Описание, Строка_, Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Отметить сообщение как прочитанное // Отмечает выбранное сообщение и все сообщения до него как прочитанные -// +// // Примечание: // Метод в документации API: [im.dialog.read](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12053) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата (chatXXX) или пользователя (XXX) для диалога - chat // IDСообщения - Строка, Число - ID последнего прочитанного сообщения - message // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ОтметитьСообщениеКакПрочитанное(Знач URL, Знач IDЧата, Знач IDСообщения, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.dialog.read"); - + OPI_Инструменты.ДобавитьПоле("DIALOG_ID" , IDЧата , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("MESSAGE_ID", IDСообщения, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Отметить сообщение как непрочитанное // Отмечает выбранное сообщение и все сообщения после него как непрочитанные -// +// // Примечание: // Метод в документации API: [im.dialog.unread](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12055) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата (chatXXX) или пользователя (XXX) для диалога - chat // IDСообщения - Строка, Число - ID послднего непрочитанного сообщения - message // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ОтметитьСообщениеКакНепрочитанное(Знач URL, Знач IDЧата, Знач IDСообщения, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.dialog.unread"); - + OPI_Инструменты.ДобавитьПоле("DIALOG_ID" , IDЧата , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("MESSAGE_ID", IDСообщения, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции - + // Получить блок картинки // Формирует картинку для отправки в функции ОтправитьСообщение -// +// // Примечание: // Блоки в документации API: [Ссылка](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&CHAPTER_ID=07867) -// +// // Параметры: // Наименование - Строка - Наименование картинки - title // URL - Строка - URL картинки для отправки - url -// +// // Возвращаемое значение: // Структура - Блок с картинкой Функция ПолучитьБлокКартинки(Знач Наименование, Знач URL) Экспорт - СтруктураКартинки = Новый Структура; + СтруктураКартинки = Новый Структура; OPI_Инструменты.ДобавитьПоле("NAME", Наименование, "Строка", СтруктураКартинки); OPI_Инструменты.ДобавитьПоле("LINK", URL , "Строка", СтруктураКартинки); - + //@skip-check constructor-function-return-section Возврат Новый Структура("IMAGE", СтруктураКартинки); - + КонецФункции // Получить блок файла // Формирует блок файла для отправки в функции ОтправитьСообщение -// +// // Примечание: // Блоки в документации API: [Ссылка](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&CHAPTER_ID=07867) -// +// // Параметры: // Наименование - Строка - Наименование картинки - title // URL - Строка - URL файла для отправки - url -// +// // Возвращаемое значение: // Структура - Блок с файлом Функция ПолучитьБлокФайла(Знач Наименование, Знач URL) Экспорт - СтруктураКартинки = Новый Структура; + СтруктураКартинки = Новый Структура; OPI_Инструменты.ДобавитьПоле("NAME", Наименование, "Строка", СтруктураКартинки); OPI_Инструменты.ДобавитьПоле("LINK", URL , "Строка", СтруктураКартинки); - + //@skip-check constructor-function-return-section Возврат Новый Структура("FILE", СтруктураКартинки); - + КонецФункции - + #КонецОбласти #Область РаботаСУведомлениями // Создать персональное уведомление // Создает персональное уведомление пользователю -// +// // Примечание: // Метод в документации API: [im.notify.personal.add](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=12129) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDПользователя - Строка, Число - ID пользователя для отправки уведомления - user @@ -3338,7 +3338,7 @@ // Тег - Строка - Тег уникальности Если уже существет - другие увед. будут удалены - tag // Вложения - Массив из Структура - Массив блоков вложений - blocks // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция СоздатьПерсональноеУведомление(Знач URL @@ -3347,26 +3347,26 @@ , Знач Тег , Знач Вложения = "" , Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.notify.personal.add"); - + OPI_Инструменты.ДобавитьПоле("USER_ID", IDПользователя, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("MESSAGE", Текст , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("TAG" , Тег , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("ATTACH" , Вложения , "Массив", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Создать системное уведомление // Создает системное уведомление пользователю -// +// // Примечание: // Метод в документации API: [im.notify.system.add](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=12131) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDПользователя - Строка, Число - ID пользователя для отправки уведомления - user @@ -3374,7 +3374,7 @@ // Тег - Строка - Тег уникальности Если уже существет - другие увед. будут удалены - tag // Вложения - Массив из Структура - Массив блоков вложений - blocks // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция СоздатьСистемноеУведомление(Знач URL @@ -3383,43 +3383,43 @@ , Знач Тег , Знач Вложения = "" , Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.notify.system.add"); - + OPI_Инструменты.ДобавитьПоле("USER_ID", IDПользователя, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("MESSAGE", Текст , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("TAG" , Тег , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("ATTACH" , Вложения , "Массив", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Удалить уведомление // Удаляет уведомление по ID -// +// // Примечание: // Метод в документации API: [im.notify.delete](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=12133) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDУведомления - Строка, Число - ID уведомления для удаления - notif // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УдалитьУведомление(Знач URL, Знач IDУведомления, Знач Токен = "") Экспорт Параметры = НормализоватьАвторизацию(URL, Токен, "im.notify.delete"); - + OPI_Инструменты.ДобавитьПоле("ID", IDУведомления, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -3432,137 +3432,137 @@ OPI_ПреобразованиеТипов.ПолучитьБулево(Значение); Значение = ?(Значение, "Y", "N"); - + КонецПроцедуры Функция НормализоватьАвторизацию(URL, Знач Токен, Знач Метод = "") - + OPI_ПреобразованиеТипов.ПолучитьСтроку(URL); OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Параметры = Новый Структура; ЭтоАвторизацияТокеном = ЗначениеЗаполнено(Токен); - + МассивЛишнихЭлементов = Новый Массив; МассивЛишнихЭлементов.Добавить("https://"); МассивЛишнихЭлементов.Добавить("http://"); МассивЛишнихЭлементов.Добавить("www."); - + Для Каждого УдаляемыйЭлемент Из МассивЛишнихЭлементов Цикл URL = СтрЗаменить(URL, УдаляемыйЭлемент, ""); КонецЦикла; - + URL = СокрЛП(URL); - + Если Не СтрЗаканчиваетсяНа(URL, "/") Тогда URL = URL + "/"; КонецЕсли; - + Если ЭтоАвторизацияТокеном Тогда - + Если Не СтрЗаканчиваетсяНа(URL, "rest/") Тогда URL = URL + "rest/"; КонецЕсли; - + Параметры.Вставить("auth", Токен); - + КонецЕсли; - + Если ЗначениеЗаполнено(Метод) Тогда URL = URL + СокрЛП(Метод); КонецЕсли; - + Возврат Параметры; КонецФункции Функция НормализоватьФайлы(Знач Файлы) - + НормализованныеФайлы = Новый Массив; Если ТипЗнч(Файлы) = Тип("Соответствие") Тогда - - Для Каждого Файл Из Файлы Цикл - + + Для Каждого Файл Из Файлы Цикл + ТекущийМассив = Новый Массив; ТекущийФайл = Файл.Значение; ТекущееИмя = Файл.Ключ; - + OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(ТекущийФайл); OPI_ПреобразованиеТипов.ПолучитьСтроку(ТекущееИмя); - + ТекущийМассив.Добавить(ТекущееИмя); ТекущийМассив.Добавить(Base64Строка(ТекущийФайл)); - + НормализованныеФайлы.Добавить(ТекущийМассив); - + КонецЦикла; - + КонецЕсли; - + Возврат НормализованныеФайлы; - + КонецФункции Функция УправлениеЗадачей(Знач URL, Знач IDЗадачи, Знач Метод, Знач Токен = "") - + Параметры = НормализоватьАвторизацию(URL, Токен, Метод); OPI_Инструменты.ДобавитьПоле("taskId", IDЗадачи, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции Функция УправлениеФайлом(Знач URL, Знач IDФайла, Знач Метод, Знач Токен = "") Параметры = НормализоватьАвторизацию(URL, Токен, Метод); OPI_Инструменты.ДобавитьПоле("id", IDФайла, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции -Функция УправлениеЭлементомЧеклиста(Знач URL, Знач IDЗадачи, Знач IDЭлемента, Знач Метод, Знач Токен = "") - +Функция УправлениеЭлементомЧеклиста(Знач URL, Знач IDЗадачи, Знач IDЭлемента, Знач Метод, Знач Токен = "") + Параметры = НормализоватьАвторизацию(URL, Токен, Метод); - + OPI_Инструменты.ДобавитьПоле("TASKID", IDЗадачи , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("ITEMID", IDЭлемента, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции Функция УправлениеЧатом(Знач URL, Знач IDЧата, Знач Метод, Знач Токен = "") Параметры = НормализоватьАвторизацию(URL, Токен, Метод); OPI_Инструменты.ДобавитьПоле("CHAT_ID", IDЧата, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции Функция УправлениеЗвукомЧата(Знач URL, Знач IDЧата, Знач Выключить, Знач Токен = "") ПривестиБулево(Выключить); - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.chat.mute"); - + OPI_Инструменты.ДобавитьПоле("CHAT_ID", IDЧата , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("MUTE" , Выключить, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции #КонецОбласти diff --git a/src/ru/OInt/core/Modules/OPI_Dropbox.os b/src/ru/OInt/core/Modules/OPI_Dropbox.os index 5482164a1a..9f25fb697b 100644 --- a/src/ru/OInt/core/Modules/OPI_Dropbox.os +++ b/src/ru/OInt/core/Modules/OPI_Dropbox.os @@ -42,44 +42,44 @@ // Получить ссылку авторизации // Генерирует ссылку авторизации для перехода в браузере -// +// // Параметры: // КлючПриложения - Строка - Ключ приложения - appkey -// +// // Возвращаемое значение: // Строка - URL для перехода в браузере Функция ПолучитьСсылкуАвторизации(Знач КлючПриложения) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(КлючПриложения); - Возврат "https://www.dropbox.com/oauth2/authorize?client_id=" - + КлючПриложения + Возврат "https://www.dropbox.com/oauth2/authorize?client_id=" + + КлючПриложения + "&response_type=code&token_access_type=offline"; - + КонецФункции // Получить токен // Полеучает токен на основе кода со страницы ПолучитьСсылкуАвторизации -// +// // Параметры: // КлючПриложения - Строка - Ключ приложения - appkey // СекретПриложения - Строка - Секрет приложения - appsecret // Код - Строка - Код со страницы авторизации - code -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ПолучитьТокен(Знач КлючПриложения, Знач СекретПриложения, Знач Код) Экспорт - + URL = "https://api.dropbox.com/oauth2/token"; ТипДанных = "application/x-www-form-urlencoded; charset=utf-8"; - - Параметры = Новый Структура; + + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("code" , Код , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("grant_type", "authorization_code", "Строка", Параметры); - + СтруктураURL = OPI_Инструменты.РазбитьURL(URL); Сервер = СтруктураURL["Сервер"]; Адрес = СтруктураURL["Адрес"]; - + Запрос = OPI_Инструменты.СоздатьЗапрос(Адрес, , ТипДанных); Соединение = OPI_Инструменты.СоздатьСоединение(Сервер, КлючПриложения, СекретПриложения); @@ -87,83 +87,83 @@ Данные = Прав(СтрокаПараметров, СтрДлина(СтрокаПараметров) - 1); Запрос.УстановитьТелоИзСтроки(Данные); - + Ответ = Соединение.ВызватьHTTPМетод("POST", Запрос); OPI_Инструменты.ОбработатьОтвет(Ответ); - + Возврат Ответ; - + КонецФункции // Обновить токен // Получает новый токен на основе рефреш токена -// +// // Параметры: // КлючПриложения - Строка - Ключ приложения - appkey // СекретПриложения - Строка - Секрет приложения - appsecret // РефрешТокен - Строка - Рефреш токен - refresh -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ОбновитьТокен(Знач КлючПриложения, Знач СекретПриложения, Знач РефрешТокен) Экспорт - + Строка_ = "Строка"; URL = "https://api.dropbox.com/oauth2/token"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("refresh_token", РефрешТокен , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("grant_type" , "refresh_token" , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("client_id" , КлючПриложения , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("client_secret", СекретПриложения, Строка_, Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры, , Ложь); - + Возврат Ответ; - + КонецФункции // Получить информацию об аккаунте // Получает информацию об аккаунте -// +// // Параметры: // Токен - Строка - Токен - token // Аккаунт - Строка - ID аккаунта. Текущий аккаунт токена, если не заполнено - account -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ПолучитьИнформациюОбАккаунте(Знач Токен, Знач Аккаунт = "") Экспорт - + Если ЗначениеЗаполнено(Аккаунт) Тогда Результат = ПолучитьАккаунт(Токен, Аккаунт); Иначе Результат = ПолучитьСвойАккаунт(Токен); КонецЕсли; - + Возврат Результат; - + КонецФункции // Получить данные использования пространства // Получает информацию о количестве использованного дискового пространства -// +// // Параметры: -// Токен - Строка - Токен - token -// +// Токен - Строка - Токен - token +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ПолучитьДанныеИспользованияПространства(Знач Токен) Экспорт - + URL = "https://api.dropboxapi.com/2/users/get_space_usage"; Заголовки = ПолучитьЗаголовкиЗапроса(Токен); - + Ответ = OPI_Инструменты.PostBinary(URL , ПолучитьДвоичныеДанныеИзСтроки("null") , Заголовки - , - , "text/plain; charset=dropbox-cors-hack"); - + , + , "text/plain; charset=dropbox-cors-hack"); + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -172,344 +172,344 @@ // Получить информацию об объекте // Получает информацию о файле или каталоге -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к объекту - path -// Подробно - Булево - Добавляет дополнительные поля информации для медиафайлов - detail -// +// Подробно - Булево - Добавляет дополнительные поля информации для медиафайлов - detail +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ПолучитьИнформациюОбОбъекте(Знач Токен, Знач Путь, Знач Подробно = Ложь) Экспорт - - URL = "https://api.dropboxapi.com/2/files/get_metadata"; - + + URL = "https://api.dropboxapi.com/2/files/get_metadata"; + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("path" , Путь , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("include_media_info", Подробно, "Булево", Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить список файлов папки // Получает список первых файлов каталога или продолжает получение следующих при указании курсора -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к каталогу. Необязателен, если указан курсор - path // Подробно - Булево - Добавляет дополнительные поля информации для медиафайлов - detail // Курсор - Строка - Курсор из предыдущего запроса для получения следующего набора файлов - cursor -// +// // Возвращаемое значение: // HTTPОтвет - Получить список файлов папки Функция ПолучитьСписокФайловПапки(Знач Токен, Знач Путь = "", Знач Подробно = Ложь, Знач Курсор = "") Экспорт - + Если Не ЗначениеЗаполнено(Курсор) Тогда - + URL = "https://api.dropboxapi.com/2/files/list_folder"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("path" , Путь , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("include_media_info", Подробно , "Булево", Параметры); - + Иначе - + URL = "https://api.dropboxapi.com/2/files/list_folder/continue"; - + Параметры = Новый Структура; - OPI_Инструменты.ДобавитьПоле("cursor", Курсор, "Строка", Параметры); - + OPI_Инструменты.ДобавитьПоле("cursor", Курсор, "Строка", Параметры); + КонецЕсли; - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить превью // Получает PDF или HTML превью объекта (только для токументов) -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к объекту - path -// +// // Возвращаемое значение: -// ДвоичныеДанные - превью документа +// ДвоичныеДанные - превью документа Функция ПолучитьПревью(Знач Токен, Знач Путь) Экспорт - + URL = "https://content.dropboxapi.com/2/files/get_preview"; Ответ = ОбработатьОбъект(Токен, URL, Путь, Истина); - + Возврат Ответ; - + КонецФункции // Загрузить файл // Загружает файл на облачный диск -// +// // Параметры: // Токен - Строка - Токен - token // Файл - Строка, ДвоичныеДанные - Данные файл для загрузки - file // Путь - Строка - Путь сохранения на Dropbox - path // Перезаписывать - Булево - Перезаписывать файл при конфликте путей - overwrite -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ЗагрузитьФайл(Знач Токен, Знач Файл, Знач Путь, Знач Перезаписывать = Ложь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Файл); OPI_ПреобразованиеТипов.ПолучитьБулево(Перезаписывать); OPI_ПреобразованиеТипов.ПолучитьСтроку(Путь); - + Режим = ?(Перезаписывать, "overwrite", "add"); Размер = Файл.Размер(); Граница = 100000000; - + Если Размер > Граница Тогда Ответ = ЗагрузитьБольшойФайл(Токен, Файл, Путь, Режим); Иначе Ответ = ЗагрузитьМалыйФайл(Токен, Файл, Путь, Режим); КонецЕсли; - + Возврат Ответ; - + КонецФункции // Загрузить файл по URL -// Загружает файл на облачный диск, получая его по указанному URL -// +// Загружает файл на облачный диск, получая его по указанному URL +// // Параметры: // Токен - Строка - Токен - token // URLФайла - Строка - URL источник файла - url // Путь - Строка - Путь сохранения на Dropbox - path -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ЗагрузитьФайлПоURL(Знач Токен, Знач URLФайла, Знач Путь) Экспорт - - URL = "https://api.dropboxapi.com/2/files/save_url"; - + + URL = "https://api.dropboxapi.com/2/files/save_url"; + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("path", Путь , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("url" , URLФайла , "Строка", Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить статус загрузки по URL // Получает статус загрузки файла по URL -// +// // Параметры: // Токен - Строка - Токен - token -// IDРаботы - Строка - ID асинхронной работы из ответа ЗагрузитьФайлПоURL - job -// +// IDРаботы - Строка - ID асинхронной работы из ответа ЗагрузитьФайлПоURL - job +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ПолучитьСтатусЗагрузкиПоURL(Знач Токен, Знач IDРаботы) Экспорт - - URL = "https://api.dropboxapi.com/2/files/save_url/check_job_status"; - + + URL = "https://api.dropboxapi.com/2/files/save_url/check_job_status"; + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("async_job_id", IDРаботы, "Строка", Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Удалить объект // Удаляет объект с облачного диска -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к объекту удаления - path // БезВозвратно - Строка - Удалить объект без возможности востановления - permanently -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция УдалитьОбъект(Знач Токен, Знач Путь, Знач Безвозвратно = Ложь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьБулево(Безвозвратно); - + Если Безвозвратно Тогда URL = "https://api.dropboxapi.com/2/files/permanently_delete"; Иначе URL = "https://api.dropboxapi.com/2/files/delete_v2"; КонецЕсли; - + Ответ = ОбработатьОбъект(Токен, URL, Путь); - + Возврат Ответ; КонецФункции // Копировать объект // Копирует файл или каталог по выбранному пути -// +// // Параметры: // Токен - Строка - Токен - token // Откуда - Строка - Путь к объекту оригинала - form // Куда - Строка - Целевой путь для нового объекта - to -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция КопироватьОбъект(Знач Токен, Знач Откуда, Знач Куда) Экспорт - + URL = "https://api.dropboxapi.com/2/files/copy_v2"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("from_path", Откуда, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("to_path" , Куда , "Строка", Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Переместить объект // Перемещает объект по выбранному пути -// +// // Параметры: // Токен - Строка - Токен - token // Откуда - Строка - Путь к объекту оригинала - form // Куда - Строка - Целевой путь для нового объекта - to -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ПереместитьОбъект(Знач Токен, Знач Откуда, Знач Куда) Экспорт URL = "https://api.dropboxapi.com/2/files/move_v2"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("from_path", Откуда, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("to_path" , Куда , "Строка", Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Создать папку // Создает пустой каталог по выбранному пути -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Целевой путь создания каталога - path -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция СоздатьПапку(Знач Токен, Знач Путь) Экспорт - + URL = "https://api.dropboxapi.com/2/files/create_folder_v2"; Ответ = ОбработатьОбъект(Токен, URL, Путь); - + Возврат Ответ; - + КонецФункции // Скачать файл // Скачивает файл по указанному пути или ID -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь или ID файла - path -// +// // Возвращаемое значение: // ДвоичныеДанные - двоичные данные файла Функция СкачатьФайл(Знач Токен, Знач Путь) Экспорт - + URL = "https://content.dropboxapi.com/2/files/download"; Ответ = ОбработатьОбъект(Токен, URL, Путь, Истина); - + Возврат Ответ; - + КонецФункции // Скачать папку // Скачивает zip архив с содержимым указанного каталога -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь или ID каталога - path -// +// // Возвращаемое значение: // ДвоичныеДанные - двоичные данные zip архива с содержимым каталога Функция СкачатьПапку(Знач Токен, Знач Путь) Экспорт - + URL = "https://content.dropboxapi.com/2/files/download_zip"; Ответ = ОбработатьОбъект(Токен, URL, Путь, Истина); - + Возврат Ответ; - + КонецФункции // Получить список версий объекта // Получает список версий (ревизий) объекта -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к объекту - path // Количество - Строка, Число - Число последних версий объекта для отображения - amount -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ПолучитьСписокВерсийОбъекта(Знач Токен, Знач Путь, Знач Количество = 10) Экспорт - - URL = "https://api.dropboxapi.com/2/files/list_revisions"; - + + URL = "https://api.dropboxapi.com/2/files/list_revisions"; + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("path" , Путь , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("limit", Количество, "Число" , Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Восстановить объект к версии // Восстанавливает состояние объекта к необходимой версии (ревизии) -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к объекту - path // Версия - Строка - ID версии (ревизии) для востановления - rev -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ВосстановитьОбъектКВерсии(Знач Токен, Знач Путь, Знач Версия) Экспорт - - URL = "https://api.dropboxapi.com/2/files/restore"; - + + URL = "https://api.dropboxapi.com/2/files/restore"; + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("path", Путь , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("rev" , Версия, "Строка", Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -518,58 +518,58 @@ // Получить список тегов // Получает список тегов выбранных файлов -// +// // Параметры: // Токен - Строка - Токен - token // Пути - Строка, Массив Из Строка - Путь или набору путей к файлам - paths -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ПолучитьСписокТегов(Знач Токен, Знач Пути) Экспорт - + URL = "https://api.dropboxapi.com/2/files/tags/get"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("paths", Пути, "Массив", Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Добавить тег // Добавляет новый текстовый тег к файлу или каталогу -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к объекту, для которого необходимо создать тег - path // Тег - Строка - Текст тега - tag -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ДобавитьТег(Знач Токен, Знач Путь, Знач Тег) Экспорт - + Возврат ОбработатьТег(Токен, Путь, Тег); - + КонецФункции // Удалить тег // Удаляет текстовый тег файла или каталога -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к объекту, тег которого необходимо удалить - path // Тег - Строка - Текст тега - tag -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция УдалитьТег(Знач Токен, Знач Путь, Знач Тег) Экспорт - + Возврат ОбработатьТег(Токен, Путь, Тег, Истина); - + КонецФункции #КонецОбласти @@ -578,38 +578,38 @@ // Опубликовать папку // Переводит каталог в режим публичного доступа -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к целевому каталогу - path -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ОпубликоватьПапку(Знач Токен, Знач Путь) Экспорт - + URL = "https://api.dropboxapi.com/2/sharing/share_folder"; Ответ = ОбработатьОбъект(Токен, URL, Путь); - + Возврат Ответ; - + КонецФункции // Отменить публикацию папки // Отменяет режим общего доступа для каталога -// +// // Параметры: // Токен - Строка - Токен - token // IDПапки - Строка - ID публичного каталога (shared folder ID) - folder -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ОтменитьПубликациюПапки(Знач Токен, Знач IDПапки) Экспорт - + URL = "https://api.dropboxapi.com/2/sharing/unshare_folder"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("shared_folder_id", IDПапки, "Строка", Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); @@ -619,120 +619,120 @@ // Добавить пользователя к файлу // Определяет доступ к файлу для стороннего пользователя -// +// // Параметры: // Токен - Строка - Токен - token // IDФайла - Строка - ID файла, к которому предоставляется доступ - fileid // АдресаПочты - Строка, Массив Из Строка - Список адресов почты добавляемых пользователей - emails // ТолькоПросмотр - Булево - Запрещает редактирование файла для стороннего пользователя - readonly -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ДобавитьПользователейКФайлу(Знач Токен, Знач IDФайла, Знач АдресаПочты, Знач ТолькоПросмотр = Истина) Экспорт - + Строка_ = "Строка"; - + OPI_ПреобразованиеТипов.ПолучитьМассив(АдресаПочты); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDФайла); OPI_ПреобразованиеТипов.ПолучитьБулево(ТолькоПросмотр); - + Если Не СтрНачинаетсяС(IDФайла, "id:") Тогда IDФайла = "id:" + IDФайла; КонецЕсли; - + URL = "https://api.dropboxapi.com/2/sharing/add_file_member"; - + МассивПользователей = Новый Массив; - + Для Каждого Адрес Из АдресаПочты Цикл - + ДанныеПользователя = Новый Соответствие; OPI_Инструменты.ДобавитьПоле(".tag" , "email", Строка_, ДанныеПользователя); OPI_Инструменты.ДобавитьПоле("email", Адрес , Строка_, ДанныеПользователя); - + МассивПользователей.Добавить(ДанныеПользователя); КонецЦикла; - + Параметры = Новый Структура; - OPI_Инструменты.ДобавитьПоле("file" , IDФайла , Строка_, Параметры); + OPI_Инструменты.ДобавитьПоле("file" , IDФайла , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("members", МассивПользователей , "Массив", Параметры); - + Режим = ?(ТолькоПросмотр, "viewer", "editor"); - + OPI_Инструменты.ДобавитьПоле("access_level", Режим , Строка_, Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Добавить пользователей к папке // Предоставляет стороннии пользователям доступ к каталогу -// +// // Параметры: // Токен - Строка - Токен - token // IDПапки - Строка - ID публичного каталога (shared folder ID) - folder // АдресаПочты - Строка, Массив Из Строка - Список адресов почты добавляемых пользователей - emails // ТолькоПросмотр - Булево - Запрещает редактирование файла для стороннего пользователя - readonly -// +// // Возвращаемое значение: // Неопределено - пустой ответ Функция ДобавитьПользователейКПапке(Знач Токен, Знач IDПапки, Знач АдресаПочты, Знач ТолькоПросмотр = Истина) Экспорт - + Строка_ = "Строка"; - + OPI_ПреобразованиеТипов.ПолучитьМассив(АдресаПочты); OPI_ПреобразованиеТипов.ПолучитьБулево(ТолькоПросмотр); Режим = ?(ТолькоПросмотр, "viewer", "editor"); - + URL = "https://api.dropboxapi.com/2/sharing/add_folder_member"; - + МассивПользователей = Новый Массив; - + Для Каждого Адрес Из АдресаПочты Цикл - + ДанныеПользователя = Новый Соответствие; OPI_Инструменты.ДобавитьПоле(".tag" , "email", Строка_, ДанныеПользователя); OPI_Инструменты.ДобавитьПоле("email", Адрес , Строка_, ДанныеПользователя); - - СтруктураПользователя = Новый Структура("member,access_level", ДанныеПользователя, Режим); - + + СтруктураПользователя = Новый Структура("member,access_level", ДанныеПользователя, Режим); + МассивПользователей.Добавить(СтруктураПользователя); КонецЦикла; - + Параметры = Новый Структура; - OPI_Инструменты.ДобавитьПоле("shared_folder_id", IDПапки , Строка_, Параметры); + OPI_Инструменты.ДобавитьПоле("shared_folder_id", IDПапки , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("members" , МассивПользователей , "Массив", Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Получить статус асинхронного изменения // Получает статус асинхронной работы по изменению доступов -// +// // Параметры: // Токен - Строка - Токен - token // IDРаботы - Строка - ID асинхронной работы - job -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ПолучитьСтатусАсинхронногоИзменения(Знач Токен, Знач IDРаботы) Экспорт - + URL = "https://api.dropboxapi.com/2/sharing/check_job_status"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("async_job_id", IDРаботы, "Строка", Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); @@ -742,31 +742,31 @@ // Отменить публикацию файла // Запрещает доступ к файлу для внешних пользователей -// +// // Параметры: // Токен - Строка - Токен - token // IDФайла - Строка - ID файла, к которому предоставляется доступ - fileid -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ОтменитьПубликациюФайла(Знач Токен, Знач IDФайла) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDФайла); - + Если Не СтрНачинаетсяС(IDФайла, "id:") Тогда IDФайла = "id:" + IDФайла; КонецЕсли; - + URL = "https://api.dropboxapi.com/2/sharing/unshare_file"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("file", IDФайла, "Строка", Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); Возврат Ответ; - + КонецФункции #КонецОбласти @@ -776,10 +776,10 @@ #Область СлужебныеПроцедурыИФункции Функция ОбработатьОбъект(Знач Токен, Знач URL, Знач Путь, Знач ВЗаголовках = Ложь) - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("path", Путь, "Строка", Параметры); - + Если ВЗаголовках Тогда Заголовки = ПолучитьЗаголовкиЗапроса(Токен, Параметры); Ответ = OPI_Инструменты.PostBinary(URL, ПолучитьДвоичныеДанныеИзСтроки(""), Заголовки); @@ -787,9 +787,9 @@ Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); КонецЕсли; - + Возврат Ответ; - + КонецФункции Функция ОбработатьТег(Знач Токен, Знач Путь, Знач Тег, Знач ЭтоУдаление = Ложь) @@ -799,168 +799,168 @@ Иначе URL = "https://api.dropboxapi.com/2/files/tags/add"; КонецЕсли; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("path" , Путь, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("tag_text" , Тег , "Строка", Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции Функция ПолучитьЗаголовкиЗапроса(Знач Токен, Знач Параметры = "") - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Заголовки = Новый Соответствие; Заголовки.Вставить("Authorization" , "Bearer " + Токен); - + Если ЗначениеЗаполнено(Параметры) Тогда - + JSON = OPI_Инструменты.JSONСтрокой(Параметры, "Нет"); JSON = СтрЗаменить(JSON, Символы.ВК + Символы.ПС, ""); Заголовки.Вставить("Dropbox-API-Arg", JSON); - + КонецЕсли; - + Возврат Заголовки; - + КонецФункции Функция ЗагрузитьБольшойФайл(Знач Токен, Знач Файл, Знач Путь, Знач Режим) - - URL = "https://content.dropboxapi.com/2/files/upload_session/append_v2"; + + URL = "https://content.dropboxapi.com/2/files/upload_session/append_v2"; РазмерЧасти = 100000000; ТекущаяПозиция = 0; ПрочитаноБайт = 0; - ОбщийРазмер = Файл.Размер(); + ОбщийРазмер = Файл.Размер(); Сессия = ОткрытьСессию(Токен); - + Пока ПрочитаноБайт < ОбщийРазмер Цикл - + Отступ = ТекущаяПозиция; Курсор = Новый Структура("offset,session_id", Отступ, Сессия); - + Параметры = Новый Структура("cursor", Курсор); Заголовки = ПолучитьЗаголовкиЗапроса(Токен, Параметры); - + ЧтениеДанных = Новый ЧтениеДанных(Файл); ПрочитаноБайт = ЧтениеДанных.Пропустить(ТекущаяПозиция); Результат = ЧтениеДанных.Прочитать(РазмерЧасти); ТекущиеДанные = Результат.ПолучитьДвоичныеДанные(); РазмерТекущих = ТекущиеДанные.Размер(); - СледующаяПозиция = ТекущаяПозиция + РазмерТекущих; - + СледующаяПозиция = ТекущаяПозиция + РазмерТекущих; + Если Не ЗначениеЗаполнено(ТекущиеДанные) Тогда Прервать; КонецЕсли; Ответ = OPI_Инструменты.PostBinary(URL, ТекущиеДанные, Заголовки); - + ТекущаяПозиция = СледующаяПозиция; - + КБайт = 1024; МБайт = КБайт * КБайт; Сообщить(OPI_Инструменты.ИнформацияОПрогрессе(ТекущаяПозиция, ОбщийРазмер, "МБ", МБайт)); - + ВыполнитьСборкуМусора(); ОсвободитьОбъект(ТекущиеДанные); - + КонецЦикла; - + Ответ = ЗакрытьСессию(Токен, Путь, Режим, ОбщийРазмер, Сессия); - + Возврат Ответ; - + КонецФункции Функция ЗагрузитьМалыйФайл(Знач Токен, Знач Файл, Знач Путь, Знач Режим) - + Булево_ = "Булево"; Строка_ = "Строка"; URL = "https://content.dropboxapi.com/2/files/upload"; - + Параметры = Новый Структура; - + OPI_Инструменты.ДобавитьПоле("autorename" , Ложь , Булево_, Параметры); OPI_Инструменты.ДобавитьПоле("mode" , Режим, Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("mute" , Ложь , Булево_, Параметры); OPI_Инструменты.ДобавитьПоле("path" , Путь , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("strict_conflict", Ложь , Булево_, Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен, Параметры); Ответ = OPI_Инструменты.PostBinary(URL, Файл, Заголовки); - + Возврат Ответ; - + КонецФункции Функция ОткрытьСессию(Знач Токен) - + SessionId = "session_id"; URL = "https://content.dropboxapi.com/2/files/upload_session/start"; Заголовки = ПолучитьЗаголовкиЗапроса(Токен); - - Ответ = OPI_Инструменты.PostBinary(URL, ПолучитьДвоичныеДанныеИзСтроки(""), Заголовки); - + + Ответ = OPI_Инструменты.PostBinary(URL, ПолучитьДвоичныеДанныеИзСтроки(""), Заголовки); + Возврат Ответ[SessionId]; - + КонецФункции Функция ЗакрытьСессию(Знач Токен, Знач Путь, Знач Режим, Знач ОбщийРазмер, Знач Сессия) URL = "https://content.dropboxapi.com/2/files/upload_session/finish"; - + Коммит = Новый Структура(); OPI_Инструменты.ДобавитьПоле("mode", Режим, "Строка", Коммит); - OPI_Инструменты.ДобавитьПоле("path", Путь, "Строка", Коммит); - + OPI_Инструменты.ДобавитьПоле("path", Путь , "Строка", Коммит); + Курсор = Новый Структура("offset,session_id", ОбщийРазмер, Сессия); - + Параметры = Новый Структура("commit,cursor", Коммит, Курсор); Заголовки = ПолучитьЗаголовкиЗапроса(Токен, Параметры); - + Ответ = OPI_Инструменты.PostBinary(URL, ПолучитьДвоичныеДанныеИзСтроки(""), Заголовки); - + Возврат Ответ; - + КонецФункции Функция ПолучитьАккаунт(Знач Токен, Знач Аккаунт) - + URL = "https://api.dropboxapi.com/2/users/get_account"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("account_id", Аккаунт, "Строка", Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции Функция ПолучитьСвойАккаунт(Знач Токен) - + URL = "https://api.dropboxapi.com/2/users/get_current_account"; Заголовки = ПолучитьЗаголовкиЗапроса(Токен); - + Ответ = OPI_Инструменты.PostBinary(URL , ПолучитьДвоичныеДанныеИзСтроки("null") , Заголовки - , - , "text/plain; charset=dropbox-cors-hack"); - + , + , "text/plain; charset=dropbox-cors-hack"); + Возврат Ответ; - + КонецФункции #КонецОбласти diff --git a/src/ru/OInt/core/Modules/OPI_GoogleCalendar.os b/src/ru/OInt/core/Modules/OPI_GoogleCalendar.os index af0ad43554..962964bf62 100644 --- a/src/ru/OInt/core/Modules/OPI_GoogleCalendar.os +++ b/src/ru/OInt/core/Modules/OPI_GoogleCalendar.os @@ -43,131 +43,131 @@ // Создать календарь // Создает пустой календарь -// +// // Параметры: // Токен - Строка - Токен - token // Наименование - Строка - Наименование создаваемого календаря - title -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция СоздатьКалендарь(Знач Токен, Знач Наименование) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Наименование); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://www.googleapis.com/calendar/v3/calendars"; - + Параметры = Новый Структура; Параметры.Вставить("summary" , Наименование); Параметры.Вставить("timeZone", "Europe/Moscow"); - + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить календарь // Получает информацию о календаре по ID -// +// // Параметры: // Токен - Строка - Токен - token // Календарь - Строка - ID календаря - calendar -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ПолучитьМетаданныеКалендаря(Знач Токен, Знач Календарь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Календарь); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/calendar/v3/calendars/" + Календарь; + URL = "https://www.googleapis.com/calendar/v3/calendars/" + Календарь; Ответ = OPI_Инструменты.Get(URL, , Заголовки); - + Возврат Ответ; КонецФункции // Изменить календарь // Изменяет свойства существуещего календаря -// +// // Параметры: // Токен - Строка - Токен - token // Календарь - Строка - ID календаря - calendar // Наименование - Строка - Новое наименование - title // Описание - Строка - Новое описание календаря - description -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ИзменитьМетаданныеКалендаря(Знач Токен , Знач Календарь , Знач Наименование = "" , Знач Описание = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Календарь); OPI_ПреобразованиеТипов.ПолучитьСтроку(Наименование); OPI_ПреобразованиеТипов.ПолучитьСтроку(Описание); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://www.googleapis.com/calendar/v3/calendars/" + Календарь; - + Параметры = Новый Структура; - + Если ЗначениеЗаполнено(Наименование) Тогда Параметры.Вставить("summary", Наименование); КонецЕсли; - + Если ЗначениеЗаполнено(Описание) Тогда Параметры.Вставить("description", Описание); КонецЕсли; - + Ответ = OPI_Инструменты.Patch(URL, Параметры, Заголовки, Истина); - + Возврат Ответ; КонецФункции // Очистить основной календарь // Очищает список событий основного календаря -// +// // Параметры: // Токен - Строка - Токен - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ОчиститьОсновнойКалендарь(Знач Токен) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/calendar/v3/calendars/primary/clear"; + URL = "https://www.googleapis.com/calendar/v3/calendars/primary/clear"; Ответ = OPI_Инструменты.Post(URL, , Заголовки, Ложь); - + Возврат Ответ; КонецФункции // Удалить календарь // Удаляет календарь по ID -// +// // Параметры: // Токен - Строка - Токен - token // Календарь - Строка - ID календаря - calendar -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция УдалитьКалендарь(Знач Токен, Знач Календарь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Календарь); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/calendar/v3/calendars/" + Календарь; + URL = "https://www.googleapis.com/calendar/v3/calendars/" + Календарь; Ответ = OPI_Инструменты.Delete(URL, , Заголовки); - + Возврат Ответ; КонецФункции @@ -178,105 +178,105 @@ // Получить список календарей // Получает массив календарей аккаунта -// +// // Параметры: // Токен - Строка - Токен - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - Массив соответствий данных календарей Функция ПолучитьСписокКалендарей(Знач Токен) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); МассивКалендарей = Новый Массив; - + ПолучитьСписокКалендарейРекурсивно(Заголовки, МассивКалендарей); - + Возврат МассивКалендарей; - + КонецФункции // Добавить календарь в список // Добавляет существующий календарь в список пользователя -// +// // Параметры: // Токен - Строка - Токен - token // Календарь - Строка - ID календаря - calendar -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ДобавитьКалендарьВСписок(Знач Токен, Знач Календарь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Календарь); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://www.googleapis.com/calendar/v3/users/me/calendarList"; - + Параметры = Новый Структура; Параметры.Вставить("id", Календарь); - + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить календарь списка // Получает календарь из списка пользователя по ID -// +// // Параметры: // Токен - Строка - Токен - token // Календарь - Строка - ID календаря - calendar -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ПолучитьКалендарьСписка(Знач Токен, Знач Календарь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Календарь); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://www.googleapis.com/calendar/v3/users/me/calendarList/" + Календарь; Ответ = OPI_Инструменты.Get(URL, , Заголовки); - + Возврат Ответ; КонецФункции // Удалить календарь из списка // Удаляет календарь из списка пользователя -// +// // Параметры: // Токен - Строка - Токен - token // Календарь - Строка - ID календаря - calendar -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция УдалитьКалендарьИзСписка(Знач Токен, Знач Календарь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Календарь); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://www.googleapis.com/calendar/v3/users/me/calendarList/" + Календарь; Ответ = OPI_Инструменты.Delete(URL, , Заголовки); - + Возврат Ответ; КонецФункции // Изменить календарь списка // Изменяет свойства календаря из списка пользователей -// +// // Параметры: // Токен - Строка - Токен - token // Календарь - Строка - ID календаря - calendar // ОсновнойЦвет - Строка - HEX основного цвета (#ffffff) - primary // ДополнительныйЦвет - Строка - HEX дополнительного цвета (#ffffff) - secondary // Скрытый - Булево - Скрытый календарь - hidden -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ИзменитьКалендарьСписка(Знач Токен @@ -284,23 +284,23 @@ , Знач ОсновнойЦвет , Знач ДополнительныйЦвет , Знач Скрытый = Ложь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Календарь); OPI_ПреобразованиеТипов.ПолучитьСтроку(ОсновнойЦвет); OPI_ПреобразованиеТипов.ПолучитьСтроку(ДополнительныйЦвет); OPI_ПреобразованиеТипов.ПолучитьБулево(Скрытый); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://www.googleapis.com/calendar/v3/users/me/calendarList/" + Календарь + "?colorRgbFormat=true"; - + Параметры = Новый Соответствие; Параметры.Вставить("hidden" , Скрытый); Параметры.Вставить("foregroundColor", ОсновнойЦвет); Параметры.Вставить("backgroundColor", ДополнительныйЦвет); - + Ответ = OPI_Инструменты.Put(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции @@ -310,15 +310,15 @@ #Область РаботаССобытиями // Получить описание события !NOCLI -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - Пустой макет события Функция ПолучитьОписаниеСобытия() Экспорт - + ТекущаяДата = OPI_Инструменты.ПолучитьТекущуюДату(); Час = 3600; Событие = Новый Соответствие; - + Событие.Вставить("Описание" , ""); // Описание события Событие.Вставить("Заголовок" , "Новое событие"); // Заголовок события Событие.Вставить("МестоПроведения" , ""); // Строка описание места проведения @@ -328,149 +328,149 @@ Событие.Вставить("ОтправлятьУведомления" , Истина); // Признак отправки уведомлений участникам Возврат Событие; - + КонецФункции // Получить список событий // Получает список всех событий календаря -// +// // Параметры: // Токен - Строка - Токен - token // Календарь - Строка - ID календаря - calendar -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - Массив соответствий событий Функция ПолучитьСписокСобытий(Знач Токен, Знач Календарь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Календарь); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); МассивСобытий = Новый Массив; - + ПолучитьСписокСобытийРекурсивно(Заголовки, Календарь, МассивСобытий); - + Возврат МассивСобытий; - + КонецФункции // Получить событие // Получает событие по ID -// +// // Параметры: // Токен - Строка - Токен - token // Календарь - Строка - ID календаря - calendar // Событие - Строка - ID события - event -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ПолучитьСобытие(Знач Токен, Знач Календарь, Знач Событие) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Календарь); OPI_ПреобразованиеТипов.ПолучитьСтроку(Событие); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/calendar/v3/calendars/" - + Календарь + URL = "https://www.googleapis.com/calendar/v3/calendars/" + + Календарь + "/events/" - + Событие; - + + Событие; + Ответ = OPI_Инструменты.Get(URL, , Заголовки); - + Возврат Ответ; КонецФункции // Создать событие // Создает новое событие -// +// // Параметры: -// Токен - Строка - Токен - token +// Токен - Строка - Токен - token // Календарь - Строка - ID календаря - calendar // ОписаниеСобытия - Соответствие Из КлючИЗначение - Описание события - props -// +// // Возвращаемое значение: // Строка, Произвольный, HTTPОтвет, ДвоичныеДанные, Неопределено - ответ сервера Google -Функция СоздатьСобытие(Знач Токен, Знач Календарь, Знач ОписаниеСобытия) Экспорт - +Функция СоздатьСобытие(Знач Токен, Знач Календарь, Знач ОписаниеСобытия) Экспорт + Возврат УправлениеСобытием(Токен, Календарь, ОписаниеСобытия); - + КонецФункции // Переместить событие // Перемещает событие в другой календарь -// +// // Параметры: // Токен - Строка - Токен - token // КалендарьИсточник - Строка - ID календаря источника - from // КалендарьПриемник - Строка - ID календаря приемника - to // Событие - Строка - ID события календаря источника - event -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ПереместитьСобытие(Знач Токен, Знач КалендарьИсточник, Знач КалендарьПриемник, Знач Событие) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(КалендарьИсточник); OPI_ПреобразованиеТипов.ПолучитьСтроку(КалендарьПриемник); OPI_ПреобразованиеТипов.ПолучитьСтроку(Событие); - - Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/calendar/v3/calendars/" - + КалендарьИсточник + + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); + URL = "https://www.googleapis.com/calendar/v3/calendars/" + + КалендарьИсточник + "/events/" + Событие + "/move?destination=" - + КалендарьПриемник; - + + КалендарьПриемник; + Ответ = OPI_Инструменты.Post(URL, , Заголовки); - + Возврат Ответ; КонецФункции // Изменить событие // Изменяет существующее событие -// +// // Параметры: // Токен - Строка - Токен - token // Календарь - Строка - ID календаря - calendar // ОписаниеСобытия - Строка - Новое описание события - props // Событие - Строка - ID события - event -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ИзменитьСобытие(Знач Токен, Знач Календарь, Знач ОписаниеСобытия, Знач Событие) Экспорт - + Возврат УправлениеСобытием(Токен, Календарь, ОписаниеСобытия, Событие); - + КонецФункции // Удалить событие // Удаляет событие по ID -// +// // Параметры: // Токен - Строка - Токен - token // Календарь - Строка - ID календаря - calendar // Событие - Строка - ID события - event -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция УдалитьСобытие(Знач Токен, Знач Календарь, Знач Событие) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Календарь); OPI_ПреобразованиеТипов.ПолучитьСтроку(Событие); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/calendar/v3/calendars/" - + Календарь + URL = "https://www.googleapis.com/calendar/v3/calendars/" + + Календарь + "/events/" - + Событие; - + + Событие; + Ответ = OPI_Инструменты.Delete(URL, , Заголовки); - + Возврат Ответ; КонецФункции @@ -482,51 +482,51 @@ #Область СлужебныеПроцедурыИФункции Функция ПреобразоватьДату(Знач Дата) - + OPI_ПреобразованиеТипов.ПолучитьДату(Дата); - + СтруктураДаты = Новый Структура; - + Если Не ТипЗнч(Дата) = Тип("Дата") Тогда Возврат Неопределено; КонецЕсли; - - Если Дата = НачалоДня(Дата) Тогда + + Если Дата = НачалоДня(Дата) Тогда ФорматДаты = "ДФ=yyyy-MM-dd"; Поле = "date"; Иначе ФорматДаты = "ДФ=yyyy-MM-ddTHH:mm:ssZ"; Поле = "dateTime"; КонецЕсли; - + Дата = Формат(Дата, ФорматДаты); СтруктураДаты.Вставить(Поле , Дата); СтруктураДаты.Вставить("timeZone", "Europe/Moscow"); - + Возврат СтруктураДаты; - + КонецФункции Функция ПреобразоватьВложения(Знач Вложения) - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Вложения); - + МассивВложений = Новый Массив; - + Если ТипЗнч(Вложения) = Тип("Соответствие") Или ТипЗнч(Вложения) = Тип("Структура") Тогда - + Для Каждого Вложение Из Вложения Цикл - + ТекущеВложение = Новый Структура; ТекущеВложение.Вставить("title" , Вложение.Ключ); ТекущеВложение.Вставить("fileUrl", Вложение.Значение); - + МассивВложений.Добавить(ТекущеВложение); - + КонецЦикла; - + КонецЕсли; - + Если МассивВложений.Количество() > 0 Тогда Возврат МассивВложений; Иначе @@ -536,19 +536,19 @@ КонецФункции Функция УправлениеСобытием(Знач Токен, Знач Календарь, Знач ОписаниеСобытия, Знач Событие = "") - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Календарь); OPI_ПреобразованиеТипов.ПолучитьСтроку(Событие); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(ОписаниеСобытия); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); Существующее = ЗначениеЗаполнено(Событие); - URL = "https://www.googleapis.com/calendar/v3/calendars/" - + Календарь + URL = "https://www.googleapis.com/calendar/v3/calendars/" + + Календарь + "/events" - + ?(Существующее, "/" + Событие, ""); - + + ?(Существующее, "/" + Событие, ""); + Дата0 = ОписаниеСобытия["ДатаНачала"]; Дата1 = ОписаниеСобытия["ДатаОкончания"]; Вложения = ОписаниеСобытия["МассивURLФайловВложений"]; @@ -556,85 +556,85 @@ Уведомления = ?(ОписаниеСобытия["ОтправлятьУведомления"] = Неопределено , Ложь , ОписаниеСобытия["ОтправлятьУведомления"]); - + Параметры = Новый Структура; Параметры.Вставить("summary" , ОписаниеСобытия["Заголовок"]); Параметры.Вставить("description", ОписаниеСобытия["Описание"]); Параметры.Вставить("location" , ОписаниеСобытия["МестоПроведения"]); Параметры.Вставить("start" , ПреобразоватьДату(Дата0)); Параметры.Вставить("end" , ПреобразоватьДату(Дата1)); - Параметры.Вставить("attachments", Вложения); - - ПараметрыURL = Новый Структура; - ПараметрыURL.Вставить("sendUpdates" , ?(Уведомления, "all", "none")); + Параметры.Вставить("attachments", Вложения); + + ПараметрыURL = Новый Структура; + ПараметрыURL.Вставить("sendUpdates" , ?(Уведомления , "all" , "none")); ПараметрыURL.Вставить("supportsAttachments" , ?(ЗначениеЗаполнено(Вложения), "true", "false")); - + URL = URL + OPI_Инструменты.ПараметрыЗапросаВСтроку(ПараметрыURL); - + OPI_Инструменты.УдалитьПустыеПоляКоллекции(Параметры); - + Если Существующее Тогда Ответ = OPI_Инструменты.Patch(URL, Параметры, Заголовки, Истина); Иначе Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки, Истина); КонецЕсли; - + Возврат Ответ; КонецФункции -Процедура ПолучитьСписокКалендарейРекурсивно(Знач Заголовки, МассивКалендарей, Страница = "") - +Процедура ПолучитьСписокКалендарейРекурсивно(Знач Заголовки, МассивКалендарей, Страница = "") + Items = "items"; NPT = "nextPageToken"; Параметры = Новый Структура; - + Если ЗначениеЗаполнено(Страница) Тогда Параметры.Вставить("pageToken", Страница); КонецЕсли; - + Результат = OPI_Инструменты.Get("https://www.googleapis.com/calendar/v3/users/me/calendarList" , Параметры , Заголовки); - + Календари = Результат[Items]; Страница = Результат[NPT]; - + Для Каждого Календарь Из Календари Цикл - МассивКалендарей.Добавить(Календарь); - КонецЦикла; - + МассивКалендарей.Добавить(Календарь); + КонецЦикла; + Если Календари.Количество() > 0 И ЗначениеЗаполнено(Страница) Тогда - ПолучитьСписокКалендарейРекурсивно(Заголовки, МассивКалендарей, Страница); + ПолучитьСписокКалендарейРекурсивно(Заголовки, МассивКалендарей, Страница); КонецЕсли; - + КонецПроцедуры -Процедура ПолучитьСписокСобытийРекурсивно(Знач Заголовки, Знач Календарь, МассивСобытий, Страница = "") - +Процедура ПолучитьСписокСобытийРекурсивно(Знач Заголовки, Знач Календарь, МассивСобытий, Страница = "") + Items = "items"; NPT = "nextPageToken"; Параметры = Новый Структура; - + Если ЗначениеЗаполнено(Страница) Тогда Параметры.Вставить("pageToken", Страница); КонецЕсли; - + Результат = OPI_Инструменты.Get("https://www.googleapis.com/calendar/v3/calendars/" + Календарь + "/events" , Параметры , Заголовки); - + События = Результат[Items]; Страница = Результат[NPT]; - + Для Каждого Событие Из События Цикл - МассивСобытий.Добавить(Событие); - КонецЦикла; - + МассивСобытий.Добавить(Событие); + КонецЦикла; + Если События.Количество() > 0 И ЗначениеЗаполнено(Страница) Тогда - ПолучитьСписокСобытийРекурсивно(Заголовки, МассивСобытий, Страница); + ПолучитьСписокСобытийРекурсивно(Заголовки, МассивСобытий, Страница); КонецЕсли; - + КонецПроцедуры #КонецОбласти diff --git a/src/ru/OInt/core/Modules/OPI_GoogleDrive.os b/src/ru/OInt/core/Modules/OPI_GoogleDrive.os index 0b4ab066c6..7b591b41cc 100644 --- a/src/ru/OInt/core/Modules/OPI_GoogleDrive.os +++ b/src/ru/OInt/core/Modules/OPI_GoogleDrive.os @@ -43,277 +43,277 @@ // Получить информацию об объекте // Получает информацию о папке или файле по ID -// +// // Параметры: // Токен - Строка - Токен - token // Идентификатор - Строка - Идентификатор файла или каталога - object -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ПолучитьИнформациюОбОбъекте(Знач Токен, Знач Идентификатор) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Идентификатор); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/drive/v3/files/" + Идентификатор; - + URL = "https://www.googleapis.com/drive/v3/files/" + Идентификатор; + Параметры = Новый Структура; Параметры.Вставить("fields", "*"); - + Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Получить список каталогов // Получает список каталогов диска -// +// // Параметры: // Токен - Строка - Токен - token // ИмяСодержит - Строка - Отбор по имени - querry // Подробно - Булево - Добавляет список файлов к полям каталога - depth -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - Массив соответствий каталогов Функция ПолучитьСписокКаталогов(Знач Токен, Знач ИмяСодержит = "", Знач Подробно = Ложь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(ИмяСодержит); OPI_ПреобразованиеТипов.ПолучитьБулево(Подробно); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); МассивОбъектов = Новый Массив; Отбор = Новый Массив; - + Отбор.Добавить("mimeType = 'application/vnd.google-apps.folder'"); - + Если ЗначениеЗаполнено(ИмяСодержит) Тогда Отбор.Добавить("name contains '" + ИмяСодержит + "'"); КонецЕсли; - + ПолучитьСписокОбъектовРекурсивно(Заголовки, МассивОбъектов, Подробно, Отбор); - + Если Подробно Тогда - РазложитьОбъектыПодробно(Токен, МассивОбъектов); + РазложитьОбъектыПодробно(Токен, МассивОбъектов); КонецЕсли; - + Возврат МассивОбъектов; - + КонецФункции // Получить список файлов // Получает список файлов -// +// // Параметры: // Токен - Строка - Токен - token // ИмяСодержит - Строка - Отбор по имени - querry // Каталог - Строка - Отбор по ID каталога родителя - catalog -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - Массив соответствий файлов Функция ПолучитьСписокФайлов(Знач Токен, Знач ИмяСодержит = "", Знач Каталог = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(ИмяСодержит); OPI_ПреобразованиеТипов.ПолучитьСтроку(Каталог); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); МассивОбъектов = Новый Массив; Отбор = Новый Массив; - + Отбор.Добавить("mimeType != 'application/vnd.google-apps.folder'"); - + Если ЗначениеЗаполнено(ИмяСодержит) Тогда Отбор.Добавить("name contains '" + ИмяСодержит + "'"); КонецЕсли; - + Если ЗначениеЗаполнено(Каталог) Тогда Отбор.Добавить("'" + Каталог + "' in parents"); КонецЕсли; - + ПолучитьСписокОбъектовРекурсивно(Заголовки, МассивОбъектов, , Отбор); - + Возврат МассивОбъектов; КонецФункции // Загрузить файл // Загружает файл на диск -// +// // Параметры: // Токен - Строка - Токен - token // Файл - ДвоичныеДанные,Строка - Загружаемый файл - file // Описание - Соответствие Из КлючИЗначение - См. ПолучитьОписаниеФайла - props - JSON описания или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ЗагрузитьФайл(Знач Токен, Знач Файл, Знач Описание) Экспорт - - Возврат УправлениеФайлом(Токен, Файл, Описание); - + + Возврат УправлениеФайлом(Токен, Файл, Описание); + КонецФункции // Создать папку // Создает пустой каталог на диске -// +// // Параметры: // Токен - Строка - Токен - token // Имя - Строка - Имя папки - title // Родитель - Строка - Родитель - catalog -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция СоздатьПапку(Знач Токен, Знач Имя, Знач Родитель = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Имя); OPI_ПреобразованиеТипов.ПолучитьСтроку(Родитель); - + Описание = Новый Соответствие; Описание.Вставить("MIME" , "application/vnd.google-apps.folder"); Описание.Вставить("Имя" , Имя); Описание.Вставить("Описание", ""); Описание.Вставить("Родитель", ?(ЗначениеЗаполнено(Родитель), Родитель, "root")); - + Возврат УправлениеФайлом(Токен, , Описание); - + КонецФункции // Скачать файл // Получает файл по ID -// +// // Параметры: // Токен - Строка - Токен - token // Идентификатор - Строка - Идентификатор файла - object -// ПутьСохранения - Строка - Путь сохранения файла - out -// +// ПутьСохранения - Строка - Путь сохранения файла - out +// // Возвращаемое значение: // ДвоичныеДанные,Строка - Двоичные данные или путь к файлу при указании параметра ПутьСохранения Функция СкачатьФайл(Знач Токен, Знач Идентификатор, Знач ПутьСохранения = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Идентификатор); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/drive/v3/files/" + Идентификатор; - + URL = "https://www.googleapis.com/drive/v3/files/" + Идентификатор; + Параметры = Новый Соответствие; Параметры.Вставить("alt", "media"); - + Ответ = OPI_Инструменты.Get(URL, Параметры , Заголовки, ПутьСохранения); - + Возврат Ответ; КонецФункции // Скоприровать объект // Копирует файл или каталог -// +// // Параметры: // Токен - Строка - Токен - token // Идентификатор - Строка - Идентификатор объекта - object // НовоеИмя - Строка - Новое имя объекта - title // НовыйРодитель - Строка - Новый каталог размещения - catalog -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция СкопироватьОбъект(Знач Токен, Знач Идентификатор, Знач НовоеИмя = "", Знач НовыйРодитель = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(НовоеИмя); OPI_ПреобразованиеТипов.ПолучитьСтроку(Идентификатор); OPI_ПреобразованиеТипов.ПолучитьСтроку(НовыйРодитель); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/drive/v3/files/" + Идентификатор + "/copy"; - + URL = "https://www.googleapis.com/drive/v3/files/" + Идентификатор + "/copy"; + Параметры = Новый Структура; - + Если ЗначениеЗаполнено(НовоеИмя) Тогда Параметры.Вставить("name", НовоеИмя); КонецЕсли; - + Если ЗначениеЗаполнено(НовыйРодитель) Тогда - + МассивРодителей = Новый Массив; МассивРодителей.Добавить(НовыйРодитель); Параметры.Вставить("parents", МассивРодителей); - + КонецЕсли; - + Ответ = OPI_Инструменты.Post(URL, Параметры , Заголовки, Истина); - + Возврат Ответ; КонецФункции // Обновить файл // Обновляет двоичные данные файла -// +// // Параметры: // Токен - Строка - Токен - token // Идентификатор - Строка - Идентификатор обновляемого объекта - object // Файл - ДвоичныеДанные,Строка - Файл источник обновления - file // НовоеИмя - Строка - Новое имя файла (если необходимо) - title -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ОбновитьФайл(Знач Токен, Знач Идентификатор, Знач Файл, Знач НовоеИмя = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Идентификатор); OPI_ПреобразованиеТипов.ПолучитьСтроку(НовоеИмя); OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Файл); - + Если ЗначениеЗаполнено(НовоеИмя) Тогда Описание = Новый Соответствие; Описание.Вставить("Имя", НовоеИмя); Иначе Описание = ""; КонецЕсли; - + Возврат УправлениеФайлом(Токен, Файл, Описание, Идентификатор); - + КонецФункции // Удалить объект // Удаляет файл или каталог по ID -// +// // Параметры: // Токен - Строка - Токен - token // Идентификатор - Строка - Идентификатор объекта для удаления - object -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция УдалитьОбъект(Знач Токен, Знач Идентификатор) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Идентификатор); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/drive/v3/files/" + Идентификатор; + URL = "https://www.googleapis.com/drive/v3/files/" + Идентификатор; Ответ = OPI_Инструменты.Delete(URL, , Заголовки); - + Возврат Ответ; КонецФункции // Получить описание файла !NOCLI -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - Описание файла Функция ПолучитьОписаниеФайла() Экспорт - + Описание = Новый Соответствие; Описание.Вставить("MIME" , "image/jpeg"); // MIME-тип загружаемого файла Описание.Вставить("Имя" , "Новый файл.jpg"); // Имя файла с расширением Описание.Вставить("Описание" , "Это новый файл"); // Описание файла Описание.Вставить("Родитель" , "root"); // ID каталога загрузки или "root" для загрузки в корень - + Возврат Описание; - + КонецФункции #КонецОбласти @@ -322,107 +322,107 @@ // Создать комментарий // Создает комментарий к файлу или каталогу -// +// // Параметры: // Токен - Строка - Токен - token -// Идентификатор - Строка - Идентификатор объекта, для которого необходим комментарий - object +// Идентификатор - Строка - Идентификатор объекта, для которого необходим комментарий - object // Комментарий - Строка - Текст комментария - text -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция СоздатьКомментарий(Знач Токен, Знач Идентификатор, Знач Комментарий) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Идентификатор); OPI_ПреобразованиеТипов.ПолучитьСтроку(Комментарий); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/drive/v3/files/" + Идентификатор + "/comments?fields=*"; - + URL = "https://www.googleapis.com/drive/v3/files/" + Идентификатор + "/comments?fields=*"; + Параметры = Новый Структура; Параметры.Вставить("content", Комментарий); - + Ответ = OPI_Инструменты.POST(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Получить комментарий // Получает комментарий по ID -// +// // Параметры: // Токен - Строка - Токен - token // ИДОбъекта - Строка - Идентификатор файла или каталога размещения комментария - object // ИДКомментария - Строка - Идентификатор комментария - comment -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ПолучитьКомментарий(Знач Токен, Знач ИДОбъекта, Знач ИДКомментария) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(ИДОбъекта); OPI_ПреобразованиеТипов.ПолучитьСтроку(ИДКомментария); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/drive/v3/files/" + ИДОбъекта + "/comments/" + ИДКомментария; - + URL = "https://www.googleapis.com/drive/v3/files/" + ИДОбъекта + "/comments/" + ИДКомментария; + Параметры = Новый Структура; Параметры.Вставить("fields", "*"); - + Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Получить список комментариев // Получает список всех комментариев объекта -// +// // Параметры: // Токен - Строка - Токен - token // ИДОбъекта - Строка - Идентификатор объекта - object -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ПолучитьСписокКомментариев(Знач Токен, Знач ИДОбъекта) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(ИДОбъекта); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/drive/v3/files/" + ИДОбъекта + "/comments"; - + URL = "https://www.googleapis.com/drive/v3/files/" + ИДОбъекта + "/comments"; + Параметры = Новый Структура; Параметры.Вставить("fields", "*"); - + Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Удалить комментарий // Удаляет комментарий по ID -// +// // Параметры: // Токен - Строка - Токен - token // ИДОбъекта - Строка - Идентификатор файла или каталога размещения комментария - object // ИДКомментария - Строка - Идентификатор комментария - comment -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция УдалитьКомментарий(Знач Токен, Знач ИДОбъекта, Знач ИДКомментария) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(ИДОбъекта); OPI_ПреобразованиеТипов.ПолучитьСтроку(ИДКомментария); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/drive/v3/files/" + ИДОбъекта + "/comments/" + ИДКомментария; - + URL = "https://www.googleapis.com/drive/v3/files/" + ИДОбъекта + "/comments/" + ИДКомментария; + Ответ = OPI_Инструменты.Delete(URL, , Заголовки); - + Возврат Ответ; КонецФункции @@ -433,59 +433,59 @@ #Область СлужебныеПроцедурыИФункции -Процедура ПолучитьСписокОбъектовРекурсивно(Знач Заголовки, МассивОбъектов, Подробно = Ложь, Отбор = "", Страница = "") - +Процедура ПолучитьСписокОбъектовРекурсивно(Знач Заголовки, МассивОбъектов, Подробно = Ложь, Отбор = "", Страница = "") + URL = "https://www.googleapis.com/drive/v3/files"; Files = "files"; NPT = "nextPageToken"; Параметры = Новый Структура; Параметры.Вставить("fields", "*"); - + Если ЗначениеЗаполнено(Страница) Тогда Параметры.Вставить("pageToken", Страница); КонецЕсли; - - Если ЗначениеЗаполнено(Отбор) И ТипЗнч(Отбор) = Тип("Массив") Тогда + + Если ЗначениеЗаполнено(Отбор) И ТипЗнч(Отбор) = Тип("Массив") Тогда ОтборСтрока = СтрСоединить(Отбор, " and "); - Параметры.Вставить("q", ОтборСтрока); + Параметры.Вставить("q", ОтборСтрока); КонецЕсли; - + Результат = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Объекты = Результат[Files]; Страница = Результат[NPT]; - + Для Каждого ТекущийОбъект Из Объекты Цикл МассивОбъектов.Добавить(ТекущийОбъект); - КонецЦикла; - + КонецЦикла; + Если Объекты.Количество() > 0 И ЗначениеЗаполнено(Страница) Тогда - ПолучитьСписокОбъектовРекурсивно(Заголовки, МассивОбъектов, Подробно, Отбор, Страница); + ПолучитьСписокОбъектовРекурсивно(Заголовки, МассивОбъектов, Подробно, Отбор, Страница); КонецЕсли; - + КонецПроцедуры -Процедура РазложитьОбъектыПодробно(Знач Токен, МассивОбъектов) - +Процедура РазложитьОбъектыПодробно(Знач Токен, МассивОбъектов) + Для Каждого ТекущийОбъект Из МассивОбъектов Цикл - + МассивФайлов = Новый Массив; ТекущийИД = ТекущийОбъект["id"]; - + Результат = ПолучитьСписокФайлов(Токен, , ТекущийИД); - + Для Каждого Файл Из Результат Цикл - МассивФайлов.Добавить(Файл); + МассивФайлов.Добавить(Файл); КонецЦикла; - + ТекущийОбъект.Вставить("files", МассивФайлов); - + КонецЦикла; - + КонецПроцедуры Процедура СформироватьПараметрыЗагрузкиФайла(Описание) - + СформированноеОписание = Новый Соответствие; OPI_Инструменты.УдалитьПустыеПоляКоллекции(Описание); @@ -495,81 +495,81 @@ СоответствиеПолей.Вставить("Описание" , "description"); СоответствиеПолей.Вставить("Родитель" , "parents"); СоответствиеПолей.Вставить("Расширение", "fileExtension"); - + Для Каждого Элемент Из Описание Цикл - + Если Элемент.Ключ = "Родитель" Тогда - + ТекущееЗначение = Новый Массив; ТекущееЗначение.Добавить(Элемент.Значение); - + Иначе - + ТекущееЗначение = Элемент.Значение; - + КонецЕсли; - + ИмяПоля = СоответствиеПолей.Получить(Элемент.Ключ); СформированноеОписание.Вставить(ИмяПоля, ТекущееЗначение); - + КонецЦикла; - + Описание = СформированноеОписание; - + КонецПроцедуры -Функция УправлениеФайлом(Знач Токен, Знач Файл = "", Знач Описание = "", Знач Идентификатор = "") - +Функция УправлениеФайлом(Знач Токен, Знач Файл = "", Знач Описание = "", Знач Идентификатор = "") + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Идентификатор); - + Если ЗначениеЗаполнено(Описание) Тогда OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Описание); КонецЕсли; - + MimeType = "mimeType"; - + Если ЗначениеЗаполнено(Идентификатор) Тогда MIME = ПолучитьИнформациюОбОбъекте(Токен, Идентификатор)[MimeType]; Иначе MIME = Описание["MIME"]; - КонецЕсли; - + КонецЕсли; + Если Не ЗначениеЗаполнено(Описание) Тогда Описание = Новый Соответствие; КонецЕсли; - - Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); + + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); СформироватьПараметрыЗагрузкиФайла(Описание); ОписаниеJSON = OPI_Инструменты.JSONСтрокой(Описание); - + СоответствиеФайла = Новый Соответствие; - + Если ЗначениеЗаполнено(Файл) Тогда - - РазмерЧасти = 268435457; + + РазмерЧасти = 268435457; Размер = OPI_Инструменты.ПреобразоватьДанныеСПолучениемРазмера(Файл, РазмерЧасти); - + СоответствиеФайла.Вставить(Файл, MIME); - + Если Размер < РазмерЧасти И ТипЗнч(Файл) = Тип("ДвоичныеДанные") Тогда Ответ = ЗагрузитьМалыйФайл(ОписаниеJSON, СоответствиеФайла, Заголовки, Идентификатор); Иначе Ответ = ЗагрузитьБольшойФайл(Описание, СоответствиеФайла, Заголовки, Идентификатор); КонецЕсли; - + Иначе - Ответ = ЗагрузитьМалыйФайл(ОписаниеJSON, СоответствиеФайла, Заголовки, Идентификатор); + Ответ = ЗагрузитьМалыйФайл(ОписаниеJSON, СоответствиеФайла, Заголовки, Идентификатор); КонецЕсли; - + Возврат Ответ; - + КонецФункции Функция ЗагрузитьМалыйФайл(Знач Описание, Знач СоответствиеФайла, Знач Заголовки, Знач Идентификатор = "") - + URL = "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart"; - + Если ЗначениеЗаполнено(Идентификатор) Тогда URL = СтрЗаменить(URL, "/files", "/files/" + Идентификатор); Ответ = OPI_Инструменты.PatchMultipartRelated(URL, Описание, СоответствиеФайла, Заголовки); @@ -578,149 +578,149 @@ КонецЕсли; Возврат Ответ; - + КонецФункции Функция ЗагрузитьБольшойФайл(Знач Описание, Знач СоответствиеФайла, Знач Заголовки, Знач Идентификатор = "") - + Для Каждого Файл Из СоответствиеФайла Цикл Двоичные = Файл.Ключ; Прервать; КонецЦикла; - + URL = "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable"; - + Если ЗначениеЗаполнено(Идентификатор) Тогда URL = СтрЗаменить(URL, "/files", "/files/" + Идентификатор); Ответ = OPI_Инструменты.Patch(URL, Описание, Заголовки, Истина, Истина); Иначе Ответ = OPI_Инструменты.Post(URL, Описание, Заголовки, Истина, Истина); КонецЕсли; - + АдресЗагрузки = Ответ.Заголовки["Location"]; - + Если Не ЗначениеЗаполнено(АдресЗагрузки) Тогда OPI_Инструменты.ОбработатьОтвет(Ответ); Возврат Ответ; КонецЕсли; - + ОтветЗагрузки = ЗагрузитьФайлЧастями(Двоичные, АдресЗагрузки); Ответ = ?(ЗначениеЗаполнено(ОтветЗагрузки), ОтветЗагрузки, Ответ); - + OPI_Инструменты.ОбработатьОтвет(Ответ); Возврат Ответ; - + КонецФункции Функция ЗагрузитьФайлЧастями(Знач Двоичные, Знач АдресЗагрузки) - - Ответ = ""; - РазмерЧасти = 268435456; - ПрочитаноБайт = 0; + + Ответ = ""; + РазмерЧасти = 268435456; + ПрочитаноБайт = 0; ТекущаяПозиция = 0; ОбщийРазмер = Двоичные.Размер(); СтрОбщийРазмер = OPI_Инструменты.ЧислоВСтроку(ОбщийРазмер); ЧтениеДанных = Новый ЧтениеДанных(Двоичные); ИсходныйПоток = ЧтениеДанных.ИсходныйПоток(); - + Пока ПрочитаноБайт < ОбщийРазмер Цикл - + ПрочитаноБайт = ИсходныйПоток.ТекущаяПозиция(); Результат = ЧтениеДанных.Прочитать(РазмерЧасти); ТекущиеДанные = Результат.ПолучитьДвоичныеДанные(); РазмерТекущих = ТекущиеДанные.Размер(); - СледующаяПозиция = ТекущаяПозиция + РазмерТекущих - 1; - + СледующаяПозиция = ТекущаяПозиция + РазмерТекущих - 1; + Если Не ЗначениеЗаполнено(ТекущиеДанные) Тогда Прервать; КонецЕсли; - + ЗаголовокПотока = "bytes " + OPI_Инструменты.ЧислоВСтроку(ТекущаяПозиция) - + "-" - + OPI_Инструменты.ЧислоВСтроку(СледующаяПозиция) - + "/" + + "-" + + OPI_Инструменты.ЧислоВСтроку(СледующаяПозиция) + + "/" + СтрОбщийРазмер; - + ДопЗаголовки = Новый Соответствие; ДопЗаголовки.Вставить("Content-Length", OPI_Инструменты.ЧислоВСтроку(РазмерТекущих)); - ДопЗаголовки.Вставить("Content-Range" , ЗаголовокПотока); + ДопЗаголовки.Вставить("Content-Range" , ЗаголовокПотока); ДопЗаголовки.Вставить("Content-Type" , "application/octet-stream"); - + Ответ = OPI_Инструменты.Put(АдресЗагрузки, ТекущиеДанные, ДопЗаголовки, Ложь, Истина); - + РезультатПроверки = ПроверитьЗагрузкуЧасти(Ответ, СтрОбщийРазмер, ДопЗаголовки, АдресЗагрузки, ТекущаяПозиция); - + Если ЗначениеЗаполнено(РезультатПроверки) Тогда Возврат РезультатПроверки; КонецЕсли; - + КБайт = 1024; МБайт = КБайт * КБайт; Сообщить(OPI_Инструменты.ИнформацияОПрогрессе(ТекущаяПозиция, ОбщийРазмер, "МБ", МБайт)); - + ВыполнитьСборкуМусора(); ОсвободитьОбъект(ТекущиеДанные); - + КонецЦикла; - + Возврат Ответ; - + КонецФункции Функция ПроверитьЗагрузкуЧасти(Ответ, СтрОбщийРазмер, ДопЗаголовки, АдресЗагрузки, ТекущаяПозиция) - + НачалоКодовОшибок = 400; КонецКодовПадений = 600; НачалоКодовУспеха = 200; КонецКодовУспеха = 300; Перенаправление = 308; - + Если Ответ.КодСостояния >= НачалоКодовОшибок И Ответ.КодСостояния < КонецКодовПадений Тогда - + ЗаголовокПотока = "bytes */" + СтрОбщийРазмер; ДопЗаголовки.Вставить("Content-Range" , ЗаголовокПотока); - + ОтветПроверки = OPI_Инструменты.Put(АдресЗагрузки, "", ДопЗаголовки, Ложь, Истина); - + Если ОтветПроверки.КодСостояния >= НачалоКодовУспеха И ОтветПроверки.КодСостояния < КонецКодовУспеха Тогда - + OPI_Инструменты.ОбработатьОтвет(ОтветПроверки); Возврат ОтветПроверки; - + ИначеЕсли ОтветПроверки.КодСостояния = Перенаправление Тогда - + ЗагруженныеДанные = Ответ.Заголовки["Range"]; - + Иначе - + OPI_Инструменты.ОбработатьОтвет(Ответ); Возврат Ответ; - + КонецЕсли; - + Иначе ЗагруженныеДанные = Ответ.Заголовки["Range"]; КонецЕсли; - + Если Не ЗначениеЗаполнено(ЗагруженныеДанные) Тогда OPI_Инструменты.ОбработатьОтвет(Ответ); Возврат Ответ; КонецЕсли; - + ЗагруженныеДанные = СтрЗаменить(ЗагруженныеДанные, "bytes=", ""); МассивИнформации = СтрРазделить(ЗагруженныеДанные, "-", Ложь); НеобходимоЧастей = 2; - + Если Не МассивИнформации.Количество() = НеобходимоЧастей Тогда OPI_Инструменты.ОбработатьОтвет(Ответ); Возврат Ответ; КонецЕсли; - + ТекущаяПозиция = Число(МассивИнформации[1]) + 1; - + Возврат ""; - + КонецФункции #КонецОбласти diff --git a/src/ru/OInt/core/Modules/OPI_GoogleSheets.os b/src/ru/OInt/core/Modules/OPI_GoogleSheets.os index 198bebce47..fd940edbee 100644 --- a/src/ru/OInt/core/Modules/OPI_GoogleSheets.os +++ b/src/ru/OInt/core/Modules/OPI_GoogleSheets.os @@ -43,90 +43,90 @@ // Создать книгу // Создает новую книгу -// +// // Параметры: // Токен - Строка - Токен - token // Наименование - Строка - Наименование - title // МассивИменЛистов - Массив из Строка - Массив имен для добавления новых листов в книгу - sheets -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция СоздатьКнигу(Знач Токен, Знач Наименование, Знач МассивИменЛистов) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Наименование); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивИменЛистов); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://sheets.googleapis.com/v4/spreadsheets"; - + Свойства = Новый Структура("title" , Наименование); Листы = Новый Массив; - + ЗаполнитьМассивЛистов(МассивИменЛистов, Листы); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("properties", Свойства, "Коллекция", Параметры); OPI_Инструменты.ДобавитьПоле("sheets" , Листы , "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Получить книгу // Получает информацию о книге по ID -// +// // Параметры: // Токен - Строка - Токен - token // Идентификатор - Строка - Идентификатор книги - spreadsheet -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ПолучитьКнигу(Знач Токен, Знач Идентификатор) Экспорт - OPI_ПреобразованиеТипов.ПолучитьСтроку(Идентификатор); - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Идентификатор); + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Идентификатор; - + Ответ = OPI_Инструменты.Get(URL, , Заголовки); - + Возврат Ответ; КонецФункции // Изменить наименование книги // Изменяет наименование существующей книги -// +// // Параметры: // Токен - Строка - Токен - token // Книга - Строка - ID книги - spreadsheet // Наименование - Строка - Новое наименование - title -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ИзменитьНаименованиеКниги(Знач Токен, Знач Книга, Знач Наименование) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Книга); OPI_ПреобразованиеТипов.ПолучитьСтроку(Наименование); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Книга + ":batchUpdate"; - + Изменение = Новый Структура("title", Наименование); ЗапросИзменения = Новый Структура("properties,fields", Изменение, "title"); Запрос = Новый Структура("updateSpreadsheetProperties", ЗапросИзменения); - + МассивЗапросов = Новый Массив; МассивЗапросов.Добавить(Запрос); - + Параметры = Новый Структура("requests", МассивЗапросов); - + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -135,95 +135,95 @@ // Добавить лист // Добавляет новый лист в книгу -// -// +// +// // Параметры: // Токен - Строка - Токен - token // Книга - Строка - Идентификатор книги - spreadsheet // Наименование - Строка - Наименование нового листа - title -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ДобавитьЛист(Знач Токен, Знач Книга, Знач Наименование) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Книга); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Книга + ":batchUpdate"; Лист = СоздатьЛист(Наименование); - + Запросы = Новый Массив; Изменение = Новый Структура("addSheet", Лист); Запросы.Добавить(Изменение); - + Параметры = Новый Структура("requests", Запросы); - + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Удалить лист // Удаляет лист из книги -// +// // Параметры: // Токен - Строка - Токен - token // Книга - Строка - Идентификатор книги - spreadsheet // Лист - Строка - Идентификатор удаляемого листа - sheet -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция УдалитьЛист(Знач Токен, Знач Книга, Знач Лист) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Книга); OPI_ПреобразованиеТипов.ПолучитьСтроку(Лист); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Книга + ":batchUpdate"; - + Запросы = Новый Массив; Лист = Новый Структура("sheetId" , Лист); Изменение = Новый Структура("deleteSheet", Лист); Запросы.Добавить(Изменение); - + Параметры = Новый Структура("requests", Запросы); - + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Копировать лист // Копирует лист из одной книги в другую -// +// // Параметры: // Токен - Строка - Токен - token // Откуда - Строка - ID книги источника - from // Куда - Строка - ID книги приемника - to // Лист - Строка - ID копируемого листа - sheet -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция КопироватьЛист(Знач Токен, Знач Откуда, Знач Куда, Знач Лист) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Откуда); OPI_ПреобразованиеТипов.ПолучитьСтроку(Куда); OPI_ПреобразованиеТипов.ПолучитьСтроку(Лист); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Откуда + "/sheets/" + Лист + ":copyTo"; - - Параметры = Новый Структура("destinationSpreadsheetId", Куда); + + Параметры = Новый Структура("destinationSpreadsheetId", Куда); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -232,14 +232,14 @@ // Установить значения ячеек // Устанавливает значения ячеек листа -// +// // Параметры: // Токен - Строка - Токен - token -// Книга - Строка - ID книги - spreadsheet +// Книга - Строка - ID книги - spreadsheet // СоответствиеЗначений - Соответствие Из КлючИЗначение - Данные заполнения, где ключ это имя ячейки вида A1 - data // Лист - Строка - Имя листа (первый лист по умолчанию) - sheetname // ОсновноеИзмерение - Строка - Основное измерение при заполнении диапазона массивом - dim -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция УстановитьЗначенияЯчеек(Знач Токен @@ -247,90 +247,90 @@ , Знач СоответствиеЗначений , Знач Лист = "" , Знач ОсновноеИзмерение = "COLUMNS") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Книга); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(СоответствиеЗначений); - - Если Не ТипЗнч(СоответствиеЗначений) = Тип("Структура") + + Если Не ТипЗнч(СоответствиеЗначений) = Тип("Структура") И Не ТипЗнч(СоответствиеЗначений) = Тип("Соответствие") Тогда Возврат "Не удалось привести структуру значений к коллекции"; КонецЕсли; - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Книга + "/values:batchUpdate"; МассивДанных = СформироватьМассивДанныхЯчеек(СоответствиеЗначений, ОсновноеИзмерение, Лист); Параметры = Новый Структура("data,valueInputOption", МассивДанных, "USER_ENTERED"); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Очистить ячейки // Очищает значение в ячейках -// +// // Параметры: // Токен - Строка - Токен - token // Книга - Строка - ID книги - spreadsheet // МассивЯчеек - Массив из Строка - Массив ячеек вида А1 для очистки - cells // Лист - Строка - Имя листа (первый лист по умолчанию) - sheetname -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ОчиститьЯчейки(Знач Токен, Знач Книга, Знач МассивЯчеек, Знач Лист = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Книга); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивЯчеек); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Книга + "/values:batchClear"; - + СформироватьМассивИменЯчеек(МассивЯчеек, Лист); - + Параметры = Новый Структура("ranges", МассивЯчеек); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить значения ячеек // Получает значения ячеек таблицы -// +// // Параметры: // Токен - Строка - Токен - token // Книга - Строка - ID книги - spreadsheet // МассивЯчеек - Массив из Строка - Массив ячеек вида А1 для получения (весь лист, если не заполнено) - cells // Лист - Строка - Имя листа (первый лист по умолчанию) - sheetname -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ПолучитьЗначенияЯчеек(Знач Токен, Знач Книга, Знач МассивЯчеек = "", Знач Лист = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Книга); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Книга + "/values:batchGet"; - + Если ЗначениеЗаполнено(МассивЯчеек) Тогда - OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивЯчеек); + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивЯчеек); СформироватьМассивИменЯчеек(МассивЯчеек, Лист); - - Первый = Истина; + + Первый = Истина; Для Каждого Ячейка Из МассивЯчеек Цикл Разделитель = ?(Первый, "?", "&"); URL = URL + Разделитель + "ranges=" + Ячейка; Первый = Ложь; КонецЦикла; Иначе - URL = URL + "?ranges='" + Лист + "'"; + URL = URL + "?ranges ='" + Лист + "'"; КонецЕсли; - + Ответ = OPI_Инструменты.Get(URL, , Заголовки); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -340,75 +340,75 @@ #Область СлужебныеПроцедурыИФункции Процедура ЗаполнитьМассивЛистов(Знач МассивИмен, МассивЛистов) - + Для Каждого ИмяЛиста Из МассивИмен Цикл - + Лист = СоздатьЛист(ИмяЛиста); МассивЛистов.Добавить(Лист); - + КонецЦикла; КонецПроцедуры Процедура ДобавитьИмяЛиста(Ячейка, Знач Лист) - + Если ЗначениеЗаполнено(Лист) Тогда Ячейка = "'" + Лист + "'!" + Ячейка; КонецЕсли; - + КонецПроцедуры Функция СоздатьЛист(Знач Наименование) - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Наименование); - + СвойстваЛиста = Новый Структура("title" , Наименование); Лист = Новый Структура("properties", СвойстваЛиста); Возврат Лист; - + КонецФункции Функция СформироватьМассивДанныхЯчеек(Знач СтруктураЗначений, Знач ОсновноеИзмерение, Знач Лист) - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Лист); - + МассивДанных = Новый Массив; - + Для Каждого ДанныеЯчейки Из СтруктураЗначений Цикл - + ТекущееЗначение = ДанныеЯчейки.Значение; ТекущийКлюч = ДанныеЯчейки.Ключ; - + ДобавитьИмяЛиста(ТекущийКлюч, Лист); - + OPI_ПреобразованиеТипов.ПолучитьМассив(ТекущееЗначение); - + ТекущиеДанные = Новый Соответствие; ТекущийМассив = Новый Массив; - + ТекущийМассив.Добавить(ТекущееЗначение); - + OPI_Инструменты.ДобавитьПоле("range" , ТекущийКлюч , "Строка", ТекущиеДанные); OPI_Инструменты.ДобавитьПоле("values" , ТекущийМассив , "Массив", ТекущиеДанные); OPI_Инструменты.ДобавитьПоле("majorDimension", ОсновноеИзмерение, "Строка", ТекущиеДанные); - + МассивДанных.Добавить(ТекущиеДанные); - + КонецЦикла; - + Возврат МассивДанных; - + КонецФункции Процедура СформироватьМассивИменЯчеек(Знач МассивИмен, Знач Лист) - OPI_ПреобразованиеТипов.ПолучитьСтроку(Лист); - - Для Н = 0 По МассивИмен.ВГраница() Цикл + OPI_ПреобразованиеТипов.ПолучитьСтроку(Лист); + + Для Н = 0 По МассивИмен.ВГраница() Цикл ДобавитьИмяЛиста(МассивИмен[Н], Лист); КонецЦикла; - + КонецПроцедуры #КонецОбласти diff --git a/src/ru/OInt/core/Modules/OPI_GoogleWorkspace.os b/src/ru/OInt/core/Modules/OPI_GoogleWorkspace.os index 2b268f314d..840cbd1f3a 100644 --- a/src/ru/OInt/core/Modules/OPI_GoogleWorkspace.os +++ b/src/ru/OInt/core/Modules/OPI_GoogleWorkspace.os @@ -41,97 +41,97 @@ // Сформировать ссылку получения кода // Возвращает URL для авторизации в браузере -// +// // Параметры: // ClientID - Строка - Client ID - id // Calendar - Булево - разрешение на методы Calendar - calendar // Drive - Булево - разрешение на методы Drive - drive // Sheets - Булево - разрешение на методы Sheets - sheets -// +// // Возвращаемое значение: // Строка - Ссылка получения кода Функция СформироватьСсылкуПолученияКода(Знач ClientID , Знач Calendar = Истина , Знач Drive = Истина , Знач Sheets = Истина) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(ClientID); OPI_ПреобразованиеТипов.ПолучитьБулево(Calendar); OPI_ПреобразованиеТипов.ПолучитьБулево(Sheets); OPI_ПреобразованиеТипов.ПолучитьБулево(Drive); - + URL = "https://accounts.google.com/o/oauth2/auth"; - + ПараметрыURL = Новый Структура; ПараметрыURL.Вставить("response_type", "code"); ПараметрыURL.Вставить("client_id" , ClientID); ПараметрыURL.Вставить("redirect_uri" , "http://localhost"); ПараметрыURL.Вставить("access_type" , "offline"); ПараметрыURL.Вставить("scope" , ПолучитьСписокРазрешений(Calendar, Drive, Sheets)); - + URL = URL + OPI_Инструменты.ПараметрыЗапросаВСтроку(ПараметрыURL); - + Возврат URL; - + КонецФункции // Получить токен по коду // Получает токен по коду из авторизации в бразуере -// +// // Параметры: // ClientID - Строка - Client ID - id // ClientSecret - Строка - Client secret - secret // Code - Строка - Code из браузера - code -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ПолучитьТокенПоКоду(Знач ClientID, Знач ClientSecret, Знач Code) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(ClientID); OPI_ПреобразованиеТипов.ПолучитьСтроку(ClientSecret); OPI_ПреобразованиеТипов.ПолучитьСтроку(Code); - + URL = "https://accounts.google.com/o/oauth2/token"; - + ПараметрыURL = Новый Структура; ПараметрыURL.Вставить("grant_type" , "authorization_code"); ПараметрыURL.Вставить("client_id" , ClientID); ПараметрыURL.Вставить("client_secret", ClientSecret); - ПараметрыURL.Вставить("redirect_uri" , "http://localhost"); + ПараметрыURL.Вставить("redirect_uri" , "http://localhost"); ПараметрыURL.Вставить("code" , Code); - + Ответ = OPI_Инструменты.Post(URL, ПараметрыURL, , Ложь); - + Возврат Ответ; КонецФункции // Обновить токен // Обновляет токен по Refresh token -// +// // Параметры: // ClientID - Строка - Client ID - id // ClientSecret - Строка - Client secret - secret // RefreshToken - Строка - Refresh token - refresh -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ОбновитьТокен(Знач ClientID, Знач ClientSecret, Знач RefreshToken) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(ClientID); OPI_ПреобразованиеТипов.ПолучитьСтроку(ClientSecret); OPI_ПреобразованиеТипов.ПолучитьСтроку(RefreshToken); - + URL = "https://accounts.google.com/o/oauth2/token"; - + ПараметрыURL = Новый Структура; ПараметрыURL.Вставить("grant_type" , "refresh_token"); ПараметрыURL.Вставить("client_id" , ClientID); - ПараметрыURL.Вставить("client_secret", ClientSecret); + ПараметрыURL.Вставить("client_secret", ClientSecret); ПараметрыURL.Вставить("refresh_token", RefreshToken); - + Ответ = OPI_Инструменты.Post(URL, ПараметрыURL, , Ложь); - + Возврат Ответ; КонецФункции @@ -141,14 +141,14 @@ #Область СлужебныйПрограммныйИнтерфейс Функция ПолучитьЗаголовокАвторизации(Знач Токен) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Заголовки = Новый Соответствие; Заголовки.Вставить("Authorization", "Bearer " + Токен); - + Возврат Заголовки; - + КонецФункции #КонецОбласти @@ -156,23 +156,23 @@ #Область СлужебныеПроцедурыИфункции Функция ПолучитьСписокРазрешений(Calendar, Drive, Sheets) - + МассивРазрешений = Новый Массив; - + Если Calendar Тогда МассивРазрешений.Добавить("https://www.googleapis.com/auth/calendar"); КонецЕсли; - + Если Drive Тогда МассивРазрешений.Добавить("https://www.googleapis.com/auth/drive"); КонецЕсли; - + Если Sheets Тогда МассивРазрешений.Добавить("https://www.googleapis.com/auth/spreadsheets"); КонецЕсли; - + Возврат СтрСоединить(МассивРазрешений, " "); - + КонецФункции #КонецОбласти diff --git a/src/ru/OInt/core/Modules/OPI_Notion.os b/src/ru/OInt/core/Modules/OPI_Notion.os index 3592be70f3..cd94b93bbb 100644 --- a/src/ru/OInt/core/Modules/OPI_Notion.os +++ b/src/ru/OInt/core/Modules/OPI_Notion.os @@ -45,91 +45,91 @@ // Создать страницу // Создает дочернюю страницу над другой страницей-родителем -// +// // Параметры: // Токен - Строка - Токен - token // Родитель - Строка - ID Родителя - page // Заголовок - Строка - Заголовок страницы - title -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Notion Функция СоздатьСтраницу(Знач Токен, Знач Родитель, Знач Заголовок) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Родитель); OPI_ПреобразованиеТипов.ПолучитьСтроку(Заголовок); - - Заголовки = СоздатьЗаголовкиЗапроса(Токен); + + Заголовки = СоздатьЗаголовкиЗапроса(Токен); Свойства = Новый Структура; Параметры = Новый Структура; - + ДобавитьЗаголовокСтраницы(Заголовок, Свойства); ДобавитьРодителяСтраницы(Родитель, Ложь, Параметры); - + Параметры.Вставить("properties", Свойства); - + Ответ = OPI_Инструменты.Post("https://api.notion.com/v1/pages", Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Создать страницу в базу // Создает страницу в базе-родителе -// +// // Параметры: -// Токен - Строка - Токен - token +// Токен - Строка - Токен - token // Родитель - Строка - ID родительской базы - base // Данные - Соответствие Из КлючИЗначение - Соответствие свойств - data -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Notion Функция СоздатьСтраницуВБазу(Знач Токен, Знач Родитель, Знач Данные) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Родитель); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Данные); - + Заголовки = СоздатьЗаголовкиЗапроса(Токен); Параметры = Новый Структура; - + ДобавитьРодителяСтраницы(Родитель, Истина, Параметры); - Свойства = ЗаполнитьДанныеПоСхеме(Родитель, Данные, Токен); + Свойства = ЗаполнитьДанныеПоСхеме(Родитель, Данные, Токен); Параметры.Вставить("properties", Свойства); - + Ответ = OPI_Инструменты.Post("https://api.notion.com/v1/pages", Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить страницу // Получает информацию о странице по ID -// +// // Параметры: // Токен - Строка - Токен - token -// Страница - Строка - ID страницы - page -// +// Страница - Строка - ID страницы - page +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Notion Функция ПолучитьСтраницу(Знач Токен, Знач Страница) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Страница); - + Заголовки = СоздатьЗаголовкиЗапроса(Токен); - ПреобразоватьИД(Страница); - + ПреобразоватьИД(Страница); + Ответ = OPI_Инструменты.Get("https://api.notion.com/v1/pages/" + Страница, , Заголовки); - + Возврат Ответ; - + КонецФункции // Изменить свойства страницы // Изменяет свойства существующей страницы -// +// // Параметры: // Токен - Строка - Токен - token // Страница - Строка - ID изменяемой страницы - page @@ -137,7 +137,7 @@ // Иконка - Строка - URL картинки иконки страницы - icon // Обложка - Строка - URL картинки обложки страницы - cover // Архивирована - Булево - Архивировать страницу или нет (булево) - archive -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Notion Функция ИзменитьСвойстваСтраницы(Знач Токен @@ -146,36 +146,36 @@ , Знач Иконка = "" , Знач Обложка = "" , Знач Архивирована = Ложь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Страница); OPI_ПреобразованиеТипов.ПолучитьСтроку(Иконка); OPI_ПреобразованиеТипов.ПолучитьСтроку(Обложка); OPI_ПреобразованиеТипов.ПолучитьБулево(Архивирована); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Данные); - + Заголовки = СоздатьЗаголовкиЗапроса(Токен); Параметры = Новый Структура; Files = "files"; - - Если ЗначениеЗаполнено(Данные) + + Если ЗначениеЗаполнено(Данные) И (ТипЗнч(Данные) = Тип("Соответствие") Или ТипЗнч(Данные) = Тип("Структура")) Тогда - Свойства = ЗаполнитьДанныеПоСхеме(Страница, Данные, Токен, Ложь); - Иначе - Свойства = Новый Соответствие; + Свойства = ЗаполнитьДанныеПоСхеме(Страница, Данные, Токен, Ложь); + Иначе + Свойства = Новый Соответствие; КонецЕсли; - + Если ЗначениеЗаполнено(Иконка) Тогда СоответствиеИконки = Новый Соответствие; СоответствиеИконки.Вставить("Icon", Иконка); - + ОбъектИконка = ПреобразоватьЗначениеПоТипу(Files, СоответствиеИконки); ОбъектИконка = ОбъектИконка[Files][0]; ОбъектИконка.Удалить("name"); - + Параметры.Вставить("icon", ОбъектИконка); КонецЕсли; - + Если ЗначениеЗаполнено(Обложка) Тогда СоответствиеОбложки = Новый Соответствие; СоответствиеОбложки.Вставить("Cover", Обложка); @@ -189,13 +189,13 @@ Параметры.Вставить("properties", Свойства); Параметры.Вставить("archived" , Архивирована); - + ПреобразоватьИД(Страница); Ответ = OPI_Инструменты.Patch("https://api.notion.com/v1/pages/" + Страница, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -204,13 +204,13 @@ // Создать базу данных // Создает базу данных -// +// // Параметры: -// Токен - Строка - Токен - token +// Токен - Строка - Токен - token // Родитель - Строка - ID страницы родителя - page // Заголовок - Строка - Заголовок базы данных - title // Свойства - Структура Из Строка - Свойства базы данных - props -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Notion Функция СоздатьБазуДанных(Знач Токен, Знач Родитель, Знач Заголовок, Знач Свойства = "") Экспорт @@ -219,273 +219,273 @@ OPI_ПреобразованиеТипов.ПолучитьСтроку(Родитель); OPI_ПреобразованиеТипов.ПолучитьСтроку(Заголовок); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Свойства); - + // Пример структуры/соответствия свойств - + // Имя : title // Описание : rich_text - // В работе : checkbox + // В работе : checkbox // Количество : number // Дата : date // Статус : Соответствие // Активный : green // Неактивный : red // Архив : yellow - + // Все страницы, которые будут созданы как дочерние, должны иметь свойства базы-родителя Если Не ТипЗнч(Свойства) = Тип("Структура") И Не ТипЗнч(Свойства) = Тип("Соответствие") Тогда - Свойства = Новый Структура("Наименование", "title"); + Свойства = Новый Структура("Наименование", "title"); КонецЕсли; - Заголовки = СоздатьЗаголовкиЗапроса(Токен); + Заголовки = СоздатьЗаголовкиЗапроса(Токен); Параметры = Новый Структура; - + ДобавитьРодителяБазы(Родитель, Ложь, Параметры); ДобавитьЗаголовокБазы(Заголовок, Параметры); ДобавитьСвойстваБазы(Свойства, Параметры); Ответ = OPI_Инструменты.Post("https://api.notion.com/v1/databases", Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить базу данных // Получить данные о базе данных -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - ID базы данных - base -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Notion Функция ПолучитьБазуДанных(Знач Токен, Знач База) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(База); - + Заголовки = СоздатьЗаголовкиЗапроса(Токен); - ПреобразоватьИД(База); - + ПреобразоватьИД(База); + Ответ = OPI_Инструменты.Get("https://api.notion.com/v1/databases/" + База, , Заголовки); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции // Изменить свойства базы // Изменяет свойства существующей базы -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - ID целевой базы - base // Свойства - Соответствие из КлючИЗначение - Новые или изменяемые свойства базы данных - props // Заголовок - Строка - Новый заголовок базы - title // Описание - Строка - Новое описание базы - description -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Notion Функция ИзменитьСвойстваБазы(Знач Токен, Знач База, Знач Свойства = "", Знач Заголовок = "", Знач Описание = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(База); OPI_ПреобразованиеТипов.ПолучитьСтроку(Заголовок); OPI_ПреобразованиеТипов.ПолучитьСтроку(Описание); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Свойства); - + Параметры = Новый Структура; - Заголовки = СоздатьЗаголовкиЗапроса(Токен); - ПреобразоватьИД(База); - + Заголовки = СоздатьЗаголовкиЗапроса(Токен); + ПреобразоватьИД(База); + Если ЗначениеЗаполнено(Заголовок) Тогда ДобавитьЗаголовокБазы(Заголовок, Параметры); КонецЕсли; - + Если ЗначениеЗаполнено(Описание) Тогда ДобавитьОписаниеБазы(Описание, Параметры); КонецЕсли; - + Если ТипЗнч(Свойства) = Тип("Структура") Или ТипЗнч(Свойства) = Тип("Соответствие") Тогда ДобавитьСвойстваБазы(Свойства, Параметры); КонецЕсли; - + Ответ = OPI_Инструменты.Patch("https://api.notion.com/v1/databases/" + База, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции -#КонецОбласти +#КонецОбласти #Область РаботаСБлоками // Создать блок // Создает новый блок на основе существующего блока -// +// // Параметры: // Токен - Строка - Токен - token // Родитель - Строка - ID родительского блока или страницы - page // Блок - Строка,Соответствие Из КлючИЗначение - ID блока или сам блок образец - block // ВставитьПосле - Строка - ID блока, после которого необходимо встаивть новый - prev -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Notion Функция СоздатьБлок(Знач Токен, Знач Родитель, Знач Блок, Знач ВставитьПосле = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Родитель); OPI_ПреобразованиеТипов.ПолучитьСтроку(ВставитьПосле); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Блок); - + Если ТипЗнч(Блок) = Тип("Массив") Тогда - Блок = Блок[0]; + Блок = Блок[0]; КонецЕсли; - - Заголовки = СоздатьЗаголовкиЗапроса(Токен); + + Заголовки = СоздатьЗаголовкиЗапроса(Токен); ПреобразоватьИД(Родитель); - + Если ТипЗнч(Блок) = Тип("Строка") Тогда ПреобразоватьИД(Блок); - Блок = ВернутьБлок(Токен, Блок); + Блок = ВернутьБлок(Токен, Блок); КонецЕсли; - + МассивБлоков = Новый Массив; МассивБлоков.Добавить(Блок); - + Параметры = Новый Соответствие; Параметры.Вставить("children", МассивБлоков); - + Если ЗначениеЗаполнено(ВставитьПосле) Тогда Параметры.Вставить("after", ВставитьПосле); КонецЕсли; - + URL = "https://api.notion.com/v1/blocks/" + Родитель + "/children"; Ответ = OPI_Инструменты.Patch(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Вернуть блок // Возвращает структуру блока по ID -// +// // Параметры: // Токен - Строка - Токен - token // ИДБлока - Строка - ID блока - block // ТолькоОснова - Булево - Истина > служебные поля удаляются, остается только сам блок - core -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Notion Функция ВернутьБлок(Знач Токен, Знач ИДБлока, Знач ТолькоОснова = Истина) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(ИДБлока); OPI_ПреобразованиеТипов.ПолучитьБулево(ТолькоОснова); - + ПреобразоватьИД(ИДБлока); - + Заголовки = СоздатьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Get("https://api.notion.com/v1/blocks/" + ИДБлока, , Заголовки); - + Если ТолькоОснова Тогда - УдалитьЛишниеПоляБлока(Ответ); + УдалитьЛишниеПоляБлока(Ответ); КонецЕсли; - + Возврат Ответ; - + КонецФункции // Вернуть дочерние блоки // Созвращает список дочерних блоков блока-родителя -// +// // Параметры: // Токен - Строка - Токен - token // ИДБлока - Строка - ID блока родителя - block -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Notion Функция ВернутьДочерниеБлоки(Знач Токен, Знач ИДБлока) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(ИДБлока); - + ПреобразоватьИД(ИДБлока); - + Заголовки = СоздатьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Get("https://api.notion.com/v1/blocks/" + ИДБлока + "/children", , Заголовки); - + Возврат Ответ; - + КонецФункции // Удалить блок // Удаляет блок по ID -// +// // Параметры: // Токен - Строка - Токен - token // ИДБлока - Строка - ID блока - block -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Notion Функция УдалитьБлок(Знач Токен, Знач ИДБлока) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(ИДБлока); - + ПреобразоватьИД(ИДБлока); - + Заголовки = СоздатьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Delete("https://api.notion.com/v1/blocks/" + ИДБлока, , Заголовки); - + Возврат Ответ; - + КонецФункции - + #КонецОбласти #Область Пользователи // Список пользователей // Возвращает список пользователей рабочего пространства -// +// // Параметры: // Токен - Строка - Токен - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Notion Функция СписокПользователей(Знач Токен) Экспорт OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Заголовки = СоздатьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Get("https://api.notion.com/v1/users", , Заголовки); - + Возврат Ответ; - + КонецФункции // Получить данные пользователя // Получает данные пользователя по ID -// +// // Параметры: // Токен - Строка - Токен - token // ИДПользователя - Строка - ID целевого пользователя - user -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Notion Функция ПолучитьДанныеПользователя(Знач Токен, Знач ИДПользователя) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(ИДПользователя); - + ПреобразоватьИД(ИДПользователя); - + Заголовки = СоздатьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Get("https://api.notion.com/v1/users/" + ИДПользователя, , Заголовки); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -495,183 +495,183 @@ #Область СлужебныеПроцедурыИФункции Функция СоздатьЗаголовкиЗапроса(Знач Токен) - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Заголовки = Новый Соответствие; Заголовки.Вставить("Authorization" , "Bearer " + Токен); Заголовки.Вставить("Notion-Version", "2022-06-28"); - + Возврат Заголовки; - + КонецФункции Процедура ПреобразоватьИД(Идентификатор) - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Идентификатор); - + Идентификатор = СтрЗаменить(Идентификатор, "-", ""); - + КонецПроцедуры Процедура ДобавитьРодителяСтраницы(Знач Родитель, Знач РодительБаза, ОсновнаяСтруктура) - + OPI_ПреобразованиеТипов.ПолучитьСтроку(РодительБаза); - + ПреобразоватьИД(Родитель); - + ПолеИдентификатора = ?(РодительБаза, "database_id", "page_id"); СтруктураРодителя = Новый Структура(ПолеИдентификатора, Родитель); ОсновнаяСтруктура.Вставить("parent", СтруктураРодителя); - + КонецПроцедуры Процедура ДобавитьРодителяБазы(Знач Родитель, Знач РодительБаза, ОсновнаяСтруктура) - + OPI_ПреобразованиеТипов.ПолучитьСтроку(РодительБаза); - + ПреобразоватьИД(Родитель); - + ПолеИдентификатора = ?(РодительБаза, "database_id", "page_id"); - + СтруктураРодителя = Новый Структура(); СтруктураРодителя.Вставить("type" , ПолеИдентификатора); СтруктураРодителя.Вставить(ПолеИдентификатора, Родитель); ОсновнаяСтруктура.Вставить("parent", СтруктураРодителя); - + КонецПроцедуры -Процедура ДобавитьЗаголовокСтраницы(Знач Заголовок, ОсновнаяСтруктура) - +Процедура ДобавитьЗаголовокСтраницы(Знач Заголовок, ОсновнаяСтруктура) + OPI_ПреобразованиеТипов.ПолучитьСтроку(Заголовок); - + ПодчиненнаяСтруктура = Новый Структура; СтруктураДанных = Новый Структура; СтруктураТекста = Новый Структура; МассивДанных = Новый Массив; Title = "title"; - + СтруктураТекста.Вставить("content", Заголовок); СтруктураТекста.Вставить("link" , Неопределено); - + СтруктураДанных.Вставить("text", СтруктураТекста); СтруктураДанных.Вставить("type", "text"); - + МассивДанных.Добавить(СтруктураДанных); - + ПодчиненнаяСтруктура.Вставить("id" , Title); ПодчиненнаяСтруктура.Вставить("type" , Title); ПодчиненнаяСтруктура.Вставить(Title , МассивДанных); - + ОсновнаяСтруктура.Вставить(Title, ПодчиненнаяСтруктура); - + КонецПроцедуры Процедура ДобавитьЗаголовокБазы(Знач Заголовок, ОсновнаяСтруктура) - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Заголовок); - - Заголовок = ПреобразоватьЗаголовок(Заголовок); + + Заголовок = ПреобразоватьЗаголовок(Заголовок); ОсновнаяСтруктура.Вставить("title", Заголовок["title"]); - + КонецПроцедуры Процедура ДобавитьОписаниеБазы(Знач Описание, ОсновнаяСтруктура) - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Описание); - - Заголовок = ПреобразоватьЗаголовок(Описание); + + Заголовок = ПреобразоватьЗаголовок(Описание); ОсновнаяСтруктура.Вставить("description", Заголовок["title"]); - + КонецПроцедуры Процедура ДобавитьСвойстваБазы(Знач Свойства, ОсновнаяСтруктура) - + Если Свойства.Количество() = 0 Тогда ОсновнаяСтруктура.Вставить("properties", Новый Структура); - Возврат; + Возврат; КонецЕсли; - + СоответствиеПараметров = Новый Соответствие; - + Для Каждого Свойство Из Свойства Цикл - + Если ТипЗнч(Свойство.Значение) = Тип("Строка") Тогда - + СоответствиеПараметров.Вставить(Свойство.Ключ, Новый Структура(Свойство.Значение, Новый Структура)); - - ИначеЕсли ТипЗнч(Свойство.Значение) = Тип("Структура") - Или ТипЗнч(Свойство.Значение) = Тип("Соответствие") Тогда - + + ИначеЕсли ТипЗнч(Свойство.Значение) = Тип("Структура") + Или ТипЗнч(Свойство.Значение) = Тип("Соответствие") Тогда + ВыборЗначения = СформироватьЗначенияВыбора(Свойство.Значение); СоответствиеПараметров.Вставить(Свойство.Ключ, Новый Структура("select", ВыборЗначения)); - + Иначе - + СоответствиеПараметров.Вставить(Свойство.Ключ, Свойство.Значение); - + КонецЕсли; - + КонецЦикла; - + ОсновнаяСтруктура.Вставить("properties", СоответствиеПараметров); - + КонецПроцедуры Функция СформироватьЗначенияВыбора(Знач СтруктураВариантов) - + МассивВариантов = Новый Массив; - + Для Каждого Вариант Из СтруктураВариантов Цикл - + СоответствиеВарианта = Новый Соответствие; СоответствиеВарианта.Вставить("name" , Вариант.Ключ); СоответствиеВарианта.Вставить("color", Вариант.Значение); - + МассивВариантов.Добавить(СоответствиеВарианта); - + КонецЦикла; - + Возврат Новый Структура("options", МассивВариантов); - + КонецФункции Функция ЗаполнитьДанныеПоСхеме(Знач Схема, Знач Данные, Знач Токен, Знач ЭтоБаза = Истина) - + Если ЭтоБаза Тогда ДанныеСхемы = ПолучитьБазуДанных(Токен, Схема); Иначе - ДанныеСхемы = ПолучитьСтраницу(Токен, Схема); + ДанныеСхемы = ПолучитьСтраницу(Токен, Схема); КонецЕсли; - + ПоляБазы = ДанныеСхемы["properties"]; Свойства = Новый Соответствие; - + Если ЗначениеЗаполнено(ПоляБазы) Тогда - + Для Каждого Поле Из ПоляБазы Цикл - + ДанныеПоля = Поле.Значение; ТипПоля = ДанныеПоля["type"]; - + ЗаполняемыеДанные = Данные.Получить(Поле.Ключ); - + Если ЗаполняемыеДанные = Неопределено Тогда Продолжить; КонецЕсли; - + ПреобразованныеДанные = ПреобразоватьЗначениеПоТипу(ТипПоля, ЗаполняемыеДанные); - + Если ПреобразованныеДанные = Неопределено Тогда Продолжить; КонецЕсли; - - Свойства.Вставить(ДанныеПоля["id"], ПреобразованныеДанные); - + + Свойства.Вставить(ДанныеПоля["id"], ПреобразованныеДанные); + КонецЦикла; - + КонецЕсли; Возврат Свойства; @@ -679,7 +679,7 @@ КонецФункции Процедура УдалитьЛишниеПоляБлока(Знач Блок) - + МассивЛишних = Новый Массив; МассивЛишних.Добавить("request_id"); МассивЛишних.Добавить("archived"); @@ -690,22 +690,22 @@ МассивЛишних.Добавить("parrent"); МассивЛишних.Добавить("last_edited_by"); МассивЛишних.Добавить("id"); - + Для Каждого Поле Из МассивЛишних Цикл - + Если Не Блок.Получить(Поле) = Неопределено Тогда Блок.Удалить(Поле); КонецЕсли; - + КонецЦикла; - + КонецПроцедуры #Область ПреобразованиеТипов Функция ПреобразоватьЗначениеПоТипу(Знач Тип, Знач Значение) - - Если Тип = "title" Тогда + + Если Тип = "title" Тогда Возврат ПреобразоватьЗаголовок(Значение); ИначеЕсли Тип = "rich_text" Тогда Возврат ПреобразоватьТекст(Значение); @@ -733,42 +733,42 @@ Возврат ПреобразоватьПочту(Значение); ИначеЕсли Тип = "phone_number" Тогда Возврат ПреобразоватьТелефон(Значение); - Иначе + Иначе Возврат Неопределено; КонецЕсли; - + КонецФункции -Функция ПреобразоватьЗаголовок(Знач Заголовок) - +Функция ПреобразоватьЗаголовок(Знач Заголовок) + СтруктураДанных = Новый Структура; СтруктураТекста = Новый Структура; МассивДанных = Новый Массив; - + СтруктураТекста.Вставить("content", Заголовок); СтруктураТекста.Вставить("link" , Неопределено); - + СтруктураДанных.Вставить("type", "text"); СтруктураДанных.Вставить("text", СтруктураТекста); - + МассивДанных.Добавить(СтруктураДанных); Возврат Новый Структура("title", МассивДанных); - + КонецФункции Функция ПреобразоватьТекст(Знач Текст) - + МассивТекста = Новый Массив; СтруктураТекста = Новый Структура; - + СтруктураТекста.Вставить("type", "text"); СтруктураТекста.Вставить("text", Новый Структура("content", Текст)); - + МассивТекста.Добавить(СтруктураТекста); - + Возврат Новый Структура("rich_text", МассивТекста); - + КонецФункции Функция ПреобразоватьЧисло(Знач Число) @@ -776,101 +776,101 @@ КонецФункции Функция ПреобразоватьВариантВыбора(Знач Вариант) - + СтруктураВыбора = Новый Структура; СтруктураВыбора.Вставить("select", Новый Структура("name", Вариант)); - + Возврат СтруктураВыбора; - + КонецФункции Функция ПреобразоватьСтатус(Знач Статус) - + СтруктураСтатуса = Новый Структура; СтруктураСтатуса.Вставить("status", Новый Структура("name", Статус)); - + Возврат СтруктураСтатуса; - + КонецФункции Функция ПреобразоватьМножественныйВыбор(Знач МассивВариантов) - + МассивВариантовВыбора = Новый Массив; - + Для Каждого Вариант Из МассивВариантов Цикл МассивВариантовВыбора.Добавить(Новый Структура("name", Вариант)); КонецЦикла; - + Возврат Новый Структура("multi_select", МассивВариантовВыбора); - + КонецФункции Функция ПреобразоватьДату(Знач Дата) - + СтруктураДаты = Новый Структура; - - Если Дата = НачалоДня(Дата) Тогда + + Если Дата = НачалоДня(Дата) Тогда ФорматДаты = "ДФ=yyyy-MM-dd"; Иначе ФорматДаты = "ДФ=yyyy-MM-ddThh:mm:ssZ"; КонецЕсли; - + Дата = Формат(Дата, ФорматДаты); СтруктураДаты.Вставить("start", Дата); - + Возврат Новый Структура("date", СтруктураДаты); - + КонецФункции -Функция ПреобразоватьСвязь(Знач Идентификатор) - +Функция ПреобразоватьСвязь(Знач Идентификатор) + МассивСвязи = Новый Массив; МассивСвязи.Добавить(Новый Структура("id", Идентификатор)); - + Возврат Новый Структура("relation", МассивСвязи); - + КонецФункции Функция ПреобразоватьПользователей(Знач МассивИД) - + Если Не ТипЗнч(МассивИД) = Тип("Массив") Тогда - МассивИД_ = Новый Массив; + МассивИД_ = Новый Массив; МассивИД_.Добавить(МассивИД); - МассивИД = МассивИД_; + МассивИД = МассивИД_; КонецЕсли; - + МассивПользователей = Новый Массив; - + Для Каждого Идентификатор Из МассивИД Цикл - + СтруктураПользователя = Новый Структура; СтруктураПользователя.Вставить("object", "user"); СтруктураПользователя.Вставить("id" , Идентификатор); МассивПользователей.Добавить(СтруктураПользователя); - + КонецЦикла; - + Возврат Новый Структура("people", МассивПользователей); - + КонецФункции Функция ПреобразоватьФайлы(Знач СоответствиеФайлов) - + МассивФайлов = Новый Массив; - + Для Каждого Файл Из СоответствиеФайлов Цикл - + СтруктураФайла = Новый Структура; СтруктураФайла.Вставить("type" , "external"); СтруктураФайла.Вставить("name" , Файл.Ключ); СтруктураФайла.Вставить("external", Новый Структура("url", Файл.Значение)); - + МассивФайлов.Добавить(СтруктураФайла); - + КонецЦикла; Возврат Новый Структура("files", МассивФайлов); - + КонецФункции Функция ПреобразоватьБулево(Знач Булево) diff --git a/src/ru/OInt/core/Modules/OPI_Slack.os b/src/ru/OInt/core/Modules/OPI_Slack.os index 02bf5c92dc..eb69ab4215 100644 --- a/src/ru/OInt/core/Modules/OPI_Slack.os +++ b/src/ru/OInt/core/Modules/OPI_Slack.os @@ -43,57 +43,57 @@ // Получить информацию о боте // Получает основную информацию о боте -// +// // Параметры: // Токен - Строка - Токен бота - token -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьИнформациюОБоте(Знач Токен) Экспорт - + URL = "https://slack.com/api/auth.test"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Ответ = OPI_Инструменты.Get(URL, , Заголовки); - + Возврат Ответ; КонецФункции // Получить список рабочих областей // Получает список рабочих областей, в которых подключен бот -// +// // Параметры: // Токен - Строка - Токен бота - token // Курсор - Строка - Указатель из предыдущего запроса, если строк результата > 100 - cursor -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьСписокРабочихОбластей(Знач Токен, Знач Курсор = "") Экспорт - + URL = "https://slack.com/api/auth.teams.list"; Ответ = ПолучениеОбщихДанных(Токен, URL, Курсор); - + Возврат Ответ; КонецФункции // Получить список пользователей // Получает список пользователей рабочей области -// +// // Параметры: // Токен - Строка - Токен бота - token // Курсор - Строка - Указатель из предыдущего запроса, если строк результата > 100 - cursor -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьСписокПользователей(Знач Токен, Знач Курсор = "") Экспорт - + URL = "https://slack.com/api/users.list"; Ответ = ПолучениеОбщихДанных(Токен, URL, Курсор); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -102,68 +102,68 @@ // Отправить сообщение // Отправляет сообщение в выбранный час -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - Идентификатор канала - channel // Текст - Строка - Текст сообщения - text -// ДатаОтправки - Дата - Дата отправки для отложенного сообщения - date +// ДатаОтправки - Дата - Дата отправки для отложенного сообщения - date // Блоки - Массив Из Структура - Массив описаний блоков - blocks - JSON массива описаний блоков -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ОтправитьСообщение(Знач Токен, Знач Канал, Знач Текст = "", Знач ДатаОтправки = "", Знач Блоки = "") Экспорт - + Строка_ = "Строка"; - ЕстьДата = ЗначениеЗаполнено(ДатаОтправки); + ЕстьДата = ЗначениеЗаполнено(ДатаОтправки); Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Если ЗначениеЗаполнено(Блоки) И ТипЗнч(Блоки) = Тип(Строка_) Тогда OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Блоки); - + Если ТипЗнч(Блоки) = Тип("Массив") Тогда - + Для Н = 0 По Блоки.ВГраница() Цикл - OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Блоки[Н]); + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Блоки[Н]); КонецЦикла; - + КонецЕсли; КонецЕсли; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал, Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("text" , Текст, Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("blocks" , Блоки, "Массив" , Параметры); Если ЕстьДата Тогда - + URL = "https://slack.com/api/chat.scheduleMessage"; - OPI_Инструменты.ДобавитьПоле("post_at", ДатаОтправки, "Дата", Параметры); - + OPI_Инструменты.ДобавитьПоле("post_at", ДатаОтправки, "Дата", Параметры); + Иначе - + URL = "https://slack.com/api/chat.postMessage"; - + КонецЕсли; - + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Отправить эфемерное сообщение -// Отправляет сообщение, которое приходит в канал, но видно +// Отправляет сообщение, которое приходит в канал, но видно // только конкретному пользователю -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - Идентификатор канала - channel // Текст - Строка - Текст сообщения - text -// Пользователь - Строка - ID пользователя - user +// Пользователь - Строка - ID пользователя - user // Блоки - Массив Из Структура - Массив описаний блоков - blocks - JSON массива описаний блоков -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ОтправитьЭфемерноеСообщение(Знач Токен @@ -171,168 +171,168 @@ , Знач Текст = "" , Знач Пользователь = "" , Знач Блоки = "") Экспорт - + Строка_ = "Строка"; - + Если ЗначениеЗаполнено(Блоки) И Не ТипЗнч(Блоки) = Тип(Строка_) Тогда OPI_ПреобразованиеТипов.ПолучитьМассив(Блоки); КонецЕсли; - + Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("text" , Текст , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("user" , Пользователь, Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("blocks" , Блоки , "Коллекция", Параметры); - + URL = "https://slack.com/api/chat.postEphemeral"; - + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Изменить сообщение // Изменяет состав существующего сообщения -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - Идентификатор канала - channel // Отметка - Строка - Временная отметка сообщения - stamp // Текст - Строка - Новый текст сообщения - text // МассивБлоков - Массив Из Структура - Массив описаний блоков - blocks - JSON массива описаний блоков -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ИзменитьСообщение(Знач Токен, Знач Канал, Знач Отметка, Знач Текст = "", Знач МассивБлоков = "") Экспорт - + Строка_ = "Строка"; URL = "https://slack.com/api/chat.update"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("text" , Текст , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("ts" , Отметка , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("blocks" , МассивБлоков, "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Удалить сообщение // Удаляет сообщение канала по timestamp -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - Идентификатор канала - channel // Отметка - Строка - Временная отметка или ID сообщения - stamp // ЭтоОтложенное - Булево - Признак удаления отложенного сообщения - issheduled -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция УдалитьСообщение(Знач Токен, Знач Канал, Знач Отметка, Знач ЭтоОтложенное = Ложь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьБулево(ЭтоОтложенное); - + Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Если ЭтоОтложенное Тогда URL = "https://slack.com/api/chat.deleteScheduledMessage"; - ПолеОтметки = "scheduled_message_id"; + ПолеОтметки = "scheduled_message_id"; Иначе URL = "https://slack.com/api/chat.delete"; ПолеОтметки = "ts"; КонецЕсли; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel" , Канал , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле(ПолеОтметки, Отметка, "Строка", Параметры); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Получить список отложенных сообщений // Получает список отложенных сообщений канала -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - Идентификатор канала - channel // Курсор - Строка - Указатель из предыдущего запроса, если строк результата > 100 - cursor -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьСписокОтложенныхСообщений(Знач Токен, Знач Канал, Знач Курсор = "") Экспорт - + URL = "https://slack.com/api/chat.scheduledMessages.list"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("cursor" , Курсор, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Получить ссылку на сообщение // Получает постоянный UTL к сообщению канала -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - Идентификатор канала - channel // Отметка - Строка - Временная отметка или ID сообщения - stamp -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьСсылкуНаСообщение(Знач Токен, Знач Канал, Знач Отметка) Экспорт - + URL = "https://slack.com/api/chat.getPermalink"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel" , Канал , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("message_ts", Отметка, "Строка", Параметры); Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Получить список ответов на сообщение // Получает массив сообщений, которые являются ответом на указанное -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - Идентификатор канала - channel // Отметка - Строка - Временная отметка или ID сообщения - stamp // Курсор - Строка - Указатель из предыдущего запроса, если строк результата > 100 - cursor -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьСписокОтветовНаСообщение(Знач Токен, Знач Канал, Знач Отметка, Знач Курсор = "") Экспорт - + Строка_ = "Строка"; URL = "https://slack.com/api/conversations.replies"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("cursor" , Курсор , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("ts" , Отметка, Строка_, Параметры); - + Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции @@ -343,107 +343,107 @@ // Получить список каналов // Получает список доступных каналов -// +// // Параметры: // Токен - Строка - Токен бота - token -// ИсключатьАрхивированные - Булево - Признак исключения архивированных каналов - notarchived +// ИсключатьАрхивированные - Булево - Признак исключения архивированных каналов - notarchived // Курсор - Строка - Указатель из предыдущего запроса, если строк результата > 100 - cursor -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьСписокКаналов(Знач Токен, Знач ИсключатьАрхивированные = Ложь, Знач Курсор = "") Экспорт - + URL = "https://slack.com/api/conversations.list"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("exclude_archived", ИсключатьАрхивированные, "Булево", Параметры); OPI_Инструменты.ДобавитьПоле("cursor" , Курсор , "Строка", Параметры); Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить список пользователей канала // Получает список пользователей указанного канала -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - Идентификатор канала - channel // Курсор - Строка - Указатель из предыдущего запроса, если строк результата > 100 - cursor -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьСписокПользователейКанала(Знач Токен, Знач Канал, Знач Курсор = "") Экспорт - + URL = "https://slack.com/api/conversations.members"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("cursor" , Курсор, "Строка", Параметры); Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Создать канал // Создает новый канал -// +// // Параметры: // Токен - Строка - Токен бота - token // Название - Строка - Наименование канала - title // Приватный - Булево - Создать канал приватным - private -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция СоздатьКанал(Знач Токен, Знач Название, Знач Приватный = Ложь) Экспорт - + URL = "https://slack.com/api/conversations.create"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("name" , Название , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("is_private", Приватный, "Булево", Параметры); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Архивировать канал // Архивирует активный канал -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - ID канала - channel -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция АрхивироватьКанал(Знач Токен, Знач Канал) Экспорт - + URL = "https://slack.com/api/conversations.archive"; Ответ = УправлениеДиалогом(Токен, Канал, URL); Возврат Ответ; - + КонецФункции // Получить канал // Получает информацию о канале -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - ID канала - channel -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьКанал(Знач Токен, Знач Канал) Экспорт - + URL = "https://slack.com/api/conversations.info"; Ответ = УправлениеДиалогом(Токен, Канал, URL, "GET"); Возврат Ответ; @@ -452,15 +452,15 @@ // Получить историю канала // Получает информацию событиях канала -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - ID канала - channel -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьИсториюКанала(Знач Токен, Знач Канал) Экспорт - + URL = "https://slack.com/api/conversations.history"; Ответ = УправлениеДиалогом(Токен, Канал, URL, "GET"); Возврат Ответ; @@ -469,68 +469,68 @@ // Пригласить пользователей в канал // Добавляет указанных пользователей в канал -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - ID канала - channel // МассивПользователей - Массив Из Строка - Массив ID пользователей - users -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПригласитьПользователейВКанал(Знач Токен, Знач Канал, Знач МассивПользователей) Экспорт - + URL = "https://slack.com/api/conversations.invite"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивПользователей); МассивПользователей = СтрСоединить(МассивПользователей, ","); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("users" , МассивПользователей, "Строка", Параметры); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Выгнать пользователя из канала // Удаляет указанного пользователя из канала -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - ID канала - channel // Пользователь - Строка - ID пользователя - user -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ВыгнатьПользователяИзКанала(Знач Токен, Знач Канал, Знач Пользователь) Экспорт - + URL = "https://slack.com/api/conversations.kick"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("user" , Пользователь, "Строка", Параметры); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Вступить в канал // Добавляет текущего бота в канал -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - ID канала - channel -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ВступитьВКанал(Знач Токен, Знач Канал) Экспорт - + URL = "https://slack.com/api/conversations.join"; Ответ = УправлениеДиалогом(Токен, Канал, URL); Возврат Ответ; @@ -539,15 +539,15 @@ // Покинуть канал // Удаляет текущего бота из канала -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - ID канала - channel -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПокинутьКанал(Знач Токен, Знач Канал) Экспорт - + URL = "https://slack.com/api/conversations.leave"; Ответ = УправлениеДиалогом(Токен, Канал, URL); Возврат Ответ; @@ -556,75 +556,75 @@ // Установить тему канала // Устанавливает тему канала -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - ID канала - channel // Тема - Строка - Тема канала - theme -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция УстановитьТемуКанала(Знач Токен, Знач Канал, Знач Тема) Экспорт - + URL = "https://slack.com/api/conversations.setTopic"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("topic" , Тема , "Строка", Параметры); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Установить цель канала // Устанавливает цель (описание) канала -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - ID канала - channel // Цель - Строка - Цель канала - purpose -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция УстановитьЦельКанала(Знач Токен, Знач Канал, Знач Цель) Экспорт - + URL = "https://slack.com/api/conversations.setPurpose"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("purpose", Цель , "Строка", Параметры); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Переименовать канал // Изменяет название канала -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - ID канала - channel // Название - Строка - Новое название канала - title -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПереименоватьКанал(Знач Токен, Знач Канал, Знач Название) Экспорт - + URL = "https://slack.com/api/conversations.rename"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("name" , Название, "Строка", Параметры); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции @@ -635,45 +635,45 @@ // Открыть диалог // Открывает новый диалог с одним или несколькими пользователями -// +// // Параметры: // Токен - Строка - Токен бота - token // МассивПользователей - Массив из Строка - Массив ID пользователей - users -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ОткрытьДиалог(Знач Токен, Знач МассивПользователей) Экспорт - + URL = "https://slack.com/api/conversations.open"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивПользователей); МассивПользователей = СтрСоединить(МассивПользователей, ","); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("users", МассивПользователей, "Строка", Параметры); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Закрыть диалог // Закрывает существующий диалог -// +// // Параметры: // Токен - Строка - Токен бота - token // Диалог - Строка - ID диалога - conv -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ЗакрытьДиалог(Знач Токен, Знач Диалог) Экспорт - + URL = "https://slack.com/api/conversations.close"; Ответ = УправлениеДиалогом(Токен, Диалог, URL); Возврат Ответ; - + КонецФункции #КонецОбласти @@ -682,54 +682,54 @@ // Получить список файлов // Получает список файлов бота или канала -// +// // Параметры: // Токен - Строка - Токен бота - token -// Канал - Строка - Канал для отбора - channel +// Канал - Строка - Канал для отбора - channel // НомерСтраницы - Число, Строка - Номер страницы - page -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьСписокФайлов(Знач Токен, Знач Канал = "", Знач НомерСтраницы = 1) Экспорт - + URL = "https://slack.com/api/files.list"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("page" , НомерСтраницы, "Строка", Параметры); Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Загрузить файл // Загружает файл на сервера Slack -// +// // Параметры: // Токен - Строка - Токен бота - token // Файл - Строка,ДвоичныеДанные - Файл для загрузки - file // ИмяФайла - Строка - Имя файла с расширением - filename // Заголовок - Строка - Имя файла в Slack - title // Канал - Строка - ID канала - channel -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ЗагрузитьФайл(Знач Токен, Знач Файл, Знач ИмяФайла, Знач Заголовок, Знач Канал = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Файл); OPI_ПреобразованиеТипов.ПолучитьСтроку(ИмяФайла); OPI_ПреобразованиеТипов.ПолучитьСтроку(Заголовок); - + Строка_ = "Строка"; Upload_url = "upload_url"; File_id = "file_id"; URL = "https://slack.com/api/files.getUploadURLExternal"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); Размер = Файл.Размер(); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("filename", ИмяФайла, Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("length" , Размер , Строка_, Параметры); @@ -737,99 +737,99 @@ Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); URL = Ответ[Upload_url]; Идентификатор = Ответ[File_id]; - + Если Не ЗначениеЗаполнено(URL) Или Не ЗначениеЗаполнено(Идентификатор) Тогда Возврат Ответ; КонецЕсли; - + Файлы = Новый Соответствие; Файлы.Вставить(ИмяФайла, Файл); - + Ответ = OPI_Инструменты.PostMultipart(URL, , Файлы, , Заголовки); - URL = "https://slack.com/api/files.completeUploadExternal"; - ФайлСлак = Новый Структура("id, title", Идентификатор, Заголовок); - + URL = "https://slack.com/api/files.completeUploadExternal"; + ФайлСлак = Новый Структура("id, title", Идентификатор, Заголовок); + Параметры = Новый Структура; - OPI_Инструменты.ДобавитьПоле("filename" , ИмяФайла, Строка_, Параметры); - OPI_Инструменты.ДобавитьПоле("channel_id", Канал , Строка_, Параметры); + OPI_Инструменты.ДобавитьПоле("filename" , ИмяФайла, Строка_ , Параметры); + OPI_Инструменты.ДобавитьПоле("channel_id", Канал , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("files" , ФайлСлак, "Массив", Параметры); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить данные файла // Получает информацию о файле -// +// // Параметры: // Токен - Строка - Токен бота - token // ИдентификаторФайла - Строка - Идентификатор файла - fileid -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьДанныеФайла(Знач Токен, Знач ИдентификаторФайла) Экспорт - + URL = "https://slack.com/api/files.info"; Ответ = УправлениеФайлом(Токен, ИдентификаторФайла, URL, "GET"); - + Возврат Ответ; - + КонецФункции // Удалить файл // Удаляет файл на Slack -// +// // Параметры: // Токен - Строка - Токен бота - token // ИдентификаторФайла - Строка - Идентификатор файла - fileid -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция УдалитьФайл(Знач Токен, Знач ИдентификаторФайла) Экспорт - + URL = "https://slack.com/api/files.delete"; Ответ = УправлениеФайлом(Токен, ИдентификаторФайла, URL); - + Возврат Ответ; - + КонецФункции // Сделать файл публичным // Создает публичный URL для файла. Требует токен пользователя -// +// // Параметры: // Токен - Строка - Токен пользователя - token // ИдентификаторФайла - Строка - Идентификатор файла - fileid -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция СделатьФайлПубличным(Знач Токен, Знач ИдентификаторФайла) Экспорт - + URL = "https://slack.com/api/files.sharedPublicURL"; Ответ = УправлениеФайлом(Токен, ИдентификаторФайла, URL); - + Возврат Ответ; - + КонецФункции // Сделать файл приватным // Удаляет публичный URL у файла. Требует токен пользователя -// +// // Параметры: // Токен - Строка - Токен пользователя - token // ИдентификаторФайла - Строка - Идентификатор файла - fileid -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция СделатьФайлПриватным(Знач Токен, Знач ИдентификаторФайла) Экспорт - + URL = "https://slack.com/api/files.revokePublicURL"; Ответ = УправлениеФайлом(Токен, ИдентификаторФайла, URL); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -838,119 +838,119 @@ // Получить список внешних файлов // Получает список внешних файлов пользователя или канала -// +// // Параметры: // Токен - Строка - Токен бота - token -// Канал - Строка - Канал для отбора - channel +// Канал - Строка - Канал для отбора - channel // Курсор - Строка - Указатель из предыдущего запроса, если строк результата > 100 - cursor -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьСписокВнешнихФайлов(Знач Токен, Знач Канал = "", Знач Курсор = "") Экспорт - + URL = "https://slack.com/api/files.remote.list"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("cursor" , Курсор, "Строка", Параметры); Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить внешний файл // Получает информацию о внешнем файле -// +// // Параметры: // Токен - Строка - Токен бота - token // ИдентификаторФайла - Строка - Идентификатор файла - fileid -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьВнешнийФайл(Знач Токен, Знач ИдентификаторФайла) Экспорт - + URL = "https://slack.com/api/files.remote.info"; Ответ = УправлениеВнешнимФайлом(Токен, ИдентификаторФайла, URL); - + Возврат Ответ; - + КонецФункции // Добавить внешний файл // Добавляет новый внешний файл -// +// // Параметры: // Токен - Строка - Токен бота - token // URL - Строка - URL к внешнему файлу - url // Заголовок - Строка - Заголовок файла для Slack - title -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ДобавитьВнешнийФайл(Знач Токен, Знач URL, Знач Заголовок) Экспорт - + Строка_ = "Строка"; URL = "https://slack.com/api/files.remote.add"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); UID = Строка(Новый УникальныйИдентификатор()); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("external_url", URL , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("external_id" , UID , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("title" , Заголовок , Строка_, Параметры); Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Отправить внешний файл // Отправляет внейшний файл по списку каналов -// +// // Параметры: // Токен - Строка - Токен бота - token // ИдентификаторФайла - Строка - Идентификатор файла - fileid // МассивКаналов - Массив Из Строка - Массив каналов для отправки - channels -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ОтправитьВнешнийФайл(Знач Токен, Знач ИдентификаторФайла, Знач МассивКаналов) Экспорт - + URL = "https://slack.com/api/files.remote.share"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивКаналов); МассивКаналов = СтрСоединить(МассивКаналов, ","); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("file" , ИдентификаторФайла , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("channels", МассивКаналов , "Строка", Параметры); Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Удалить внешний файл // Удаляет внешний файл из Slack -// +// // Параметры: // Токен - Строка - Токен бота - token // ИдентификаторФайла - Строка - Идентификатор файла - fileid -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция УдалитьВнешнийФайл(Знач Токен, Знач ИдентификаторФайла) Экспорт - + URL = "https://slack.com/api/files.remote.remove"; Ответ = УправлениеВнешнимФайлом(Токен, ИдентификаторФайла, URL); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -959,24 +959,24 @@ // Сформировать блок картинку // Формирует блок с картинкой для добавления в массив блоков сообщения -// +// // Параметры: // URL - Строка - URL картинки - picture // АльтернативныйТекст - Строка - Альтернативный текст картинки - alt -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - Блок картинки Функция СформироватьБлокКартинку(Знач URL, Знач АльтернативныйТекст = "") Экспорт - + Строка_ = "Строка"; - + Блок = Новый Соответствие; OPI_Инструменты.ДобавитьПоле("type" , "image" , Строка_, Блок); OPI_Инструменты.ДобавитьПоле("image_url", URL , Строка_, Блок); OPI_Инструменты.ДобавитьПоле("alt_text" , АльтернативныйТекст , Строка_, Блок); - + Возврат Блок; - + КонецФункции #КонецОбласти @@ -988,43 +988,43 @@ Функция ПолучитьЗаголовокАвторизации(Знач Токен) OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Заголовки = Новый Соответствие; Заголовки.Вставить("Authorization", "Bearer " + Токен); Возврат Заголовки; - + КонецФункции Функция УправлениеДиалогом(Знач Токен, Знач Канал, Знач URL, Знач ВидЗапроса = "POST") - + Заголовки = ПолучитьЗаголовокАвторизации(Токен); ВидЗапроса = вРег(ВидЗапроса); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал, "Строка", Параметры); Если ВидЗапроса = "POST" Тогда - Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); Иначе - Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); + Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); КонецЕсли; - + Возврат Ответ; - + КонецФункции Функция УправлениеФайлом(Знач Токен, Знач ИдентификаторФайла, Знач URL, Знач ВидЗапроса = "POST") - - Заголовки = ПолучитьЗаголовокАвторизации(Токен); + + Заголовки = ПолучитьЗаголовокАвторизации(Токен); ВидЗапроса = вРег(ВидЗапроса); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("file", ИдентификаторФайла , "Строка", Параметры); Если ВидЗапроса = "POST" Тогда - Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); Иначе - Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); + Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); КонецЕсли; Возврат Ответ; @@ -1032,29 +1032,29 @@ КонецФункции Функция ПолучениеОбщихДанных(Знач Токен, Знач URL, Знач Курсор) - + Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("cursor", Курсор, "Строка", Параметры); - + Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции Функция УправлениеВнешнимФайлом(Знач Токен, Знач ИдентификаторФайла, Знач URL) - + Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("file", ИдентификаторФайла , "Строка", Параметры); Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции #КонецОбласти diff --git a/src/ru/OInt/core/Modules/OPI_Telegram.os b/src/ru/OInt/core/Modules/OPI_Telegram.os index bb7e113cdb..e6de0a2334 100644 --- a/src/ru/OInt/core/Modules/OPI_Telegram.os +++ b/src/ru/OInt/core/Modules/OPI_Telegram.os @@ -47,19 +47,19 @@ // Получить информацию о боте // Выполняет запрос /getMe, возвращающий базовую информацию о боте: имя, id, возможность добавлять бота в группы и т.д. -// +// // Параметры: // Токен - Строка - Токен бота - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ПолучитьИнформациюБота(Знач Токен) Экспорт OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + URL = "api.telegram.org/bot" + Токен + "/getMe"; Ответ = OPI_Инструменты.Get(URL); - + Возврат Ответ; КонецФункции @@ -71,114 +71,114 @@ // Токен - Строка - Токен бота - token // Таймаут - Строка,Число - Время ожидания новых событий - timeout // Смещение - Строка,Число - Смещение в списке получаемых сообщений - offset -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ПолучитьОбновления(Знач Токен, Знач Таймаут = 0, Знач Смещение = "") Экспорт OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + URL = "api.telegram.org/bot" + Токен + "/getUpdates"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("timeout", Таймаут , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("offset" , Смещение, "Строка", Параметры); - + Ответ = OPI_Инструменты.Get(URL, Параметры); Возврат Ответ; КонецФункции // Установить Webhook -// Устанавливает URL обработчика событий бота для работы в режиме Webhook -// +// Устанавливает URL обработчика событий бота для работы в режиме Webhook +// // Параметры: // Токен - Строка - Токен бота - token // URL - Строка - Адрес обработки запросов от Telegram (с https:) - url -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция УстановитьWebhook(Знач Токен, Знач URL) Экспорт OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("url", URL, "Строка", Параметры); URL = "api.telegram.org/bot" + Токен + "/setWebHook"; Ответ = OPI_Инструменты.Get(URL, Параметры); - + Возврат Ответ; КонецФункции // Удалить Webhook // Удаляет URL обработчика событий бота для работы в режиме Webhook -// +// // Параметры: // Токен - Строка - Токен бота - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция УдалитьWebhook(Знач Токен) Экспорт OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + URL = "api.telegram.org/bot" + Токен + "/deleteWebHook"; Ответ = OPI_Инструменты.Get(URL); - + Возврат Ответ; КонецФункции // Скачать файл // Скачивает файл с серверов Telegram -// +// // Параметры: // Токен - Строка - Токен - token // IDФайла - Строка - ID файла для скачивания - fileid -// +// // Возвращаемое значение: // ДвоичныеДанные - данные файла Функция СкачатьФайл(Знач Токен, Знач IDФайла) Экспорт Result = "result"; - - OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - OPI_ПреобразованиеТипов.ПолучитьСтроку(IDФайла); - + + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDФайла); + Параметры = Новый Структура("file_id", IDФайла); URL = "api.telegram.org/bot" + Токен + "/getFile"; Ответ = OPI_Инструменты.Get(URL, Параметры); - + Путь = Ответ[Result]["file_path"]; - + Если Не ЗначениеЗаполнено(Путь) Тогда Возврат Ответ; КонецЕсли; - + URL = "api.telegram.org/file/bot" + Токен + "/" + Путь; Ответ = OPI_Инструменты.Get(URL, Параметры); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции // ОбработатьДанные Telegram Mini App // Обрабатывает данные TMA и опредеяет их достоверность -// +// // Параметры: // СтрокаДанных - Строка - querry из Telegram.WebApp.initData // Токен - Строка - Токен бота -// +// // Возвращаемое значение: // Соответствие из Строка - Соответствие данных с результатом проверки в поле passed Функция ОбработатьДанныеTMA(Знач СтрокаДанных, Знач Токен) Экспорт OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(СтрокаДанных); - + СтрокаДанных = РаскодироватьСтроку(СтрокаДанных, СпособКодированияСтроки.КодировкаURL); СтруктураДанных = OPI_Инструменты.ПараметрыЗапросаВСоответствие(СтрокаДанных); КлючСтрокой = "WebAppData"; @@ -221,9 +221,9 @@ Финал = ПолучитьHexСтрокуИзДвоичныхДанных(Подпись); Если Финал = вРег(Хэш) Тогда - Ответ = Истина; + Ответ = Истина; Иначе - Ответ = Ложь; + Ответ = Ложь; КонецЕсли; СоответствиеВозврата.Вставить("passed", Ответ); @@ -238,7 +238,7 @@ // Отправить текстовое сообщение // Отправляет текстовое сообщение в чат или канал -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата или IDЧата*IDТемы - chat @@ -246,7 +246,7 @@ // Клавиатура - Строка - См. СформироватьКлавиатуруПоМассивуКнопок - keyboard - JSON клавиатуры или путь к .json // Разметка - Строка - Вид обработки текста (HTML, Markdown, MarkdownV2) - parsemode // IDВходящего - Строка,Число - ID сообщения на которое надо ответить - reply -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ОтправитьТекстовоеСообщение(Знач Токен @@ -256,19 +256,19 @@ , Знач Разметка = "Markdown" , Знач IDВходящего = 0) Экспорт - OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_Инструменты.ЗаменитьСпецСимволы(Текст, Разметка); - + Строка_ = "Строка"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("parse_mode" , Разметка , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("text" , Текст , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("reply_markup" , Клавиатура , "СтрокаФайла", Параметры); OPI_Инструменты.ДобавитьПоле("reply_to_message_id", IDВходящего, Строка_ , Параметры); - + ДобавитьИдентификаторЧата(IDЧата, Параметры); - + URL = "api.telegram.org/bot" + Токен + "/sendMessage"; Ответ = OPI_Инструменты.Get(URL, Параметры); @@ -278,7 +278,7 @@ // Отправить картинку // Отправляет картинку в чат или канал -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата или IDЧата*IDТемы - chat @@ -286,7 +286,7 @@ // Картинка - ДвоичныеДанные,Строка - Файл картинки - picture // Клавиатура - Строка - См. СформироватьКлавиатуруПоМассивуКнопок - keyboard - JSON клавиатуры или путь к .json // Разметка - Строка - Вид обработки текста (HTML, Markdown, MarkdownV2) - parsemode -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ОтправитьКартинку(Знач Токен @@ -302,7 +302,7 @@ // Отправить видео // Отправляет видео в чат или канал -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата или IDЧата*IDТемы - chat @@ -310,7 +310,7 @@ // Видео - ДвоичныеДанные,Строка - Файл видео - video // Клавиатура - Строка - См. СформироватьКлавиатуруПоМассивуКнопок - keyboard - JSON клавиатуры или путь к .json // Разметка - Строка - Вид обработки текста (HTML, Markdown, MarkdownV2) - parsemode -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ОтправитьВидео(Знач Токен @@ -326,7 +326,7 @@ // Отправить аудио // Отправляет аудиофайл в чат или канал -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата или IDЧата*IDТемы - chat @@ -334,7 +334,7 @@ // Аудио - ДвоичныеДанные,Строка - Файл аудио - audio // Клавиатура - Строка - См. СформироватьКлавиатуруПоМассивуКнопок - keyboard - JSON клавиатуры или путь к .json // Разметка - Строка - Вид обработки текста (HTML, Markdown, MarkdownV2) - parsemode -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ОтправитьАудио(Знач Токен @@ -350,7 +350,7 @@ // Отправить документ // Отправляет документ в чат или канал -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата или IDЧата*IDТемы - chat @@ -359,7 +359,7 @@ // Клавиатура - Строка - См. СформироватьКлавиатуруПоМассивуКнопок - keyboard - JSON клавиатуры или путь к .json // Разметка - Строка - Вид обработки текста (HTML, Markdown, MarkdownV2) - parsemode // ИмяФайла - Строка - Отображаемое имя файла c расширением, если необходимо - filename -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ОтправитьДокумент(Знач Токен @@ -376,7 +376,7 @@ // Отправить гифку // Отправляет гифку в чат или канал -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата или IDЧата*IDТемы - chat @@ -384,7 +384,7 @@ // Гифка - ДвоичныеДанные,Строка - Файл гифки - gif // Клавиатура - Строка - См. СформироватьКлавиатуруПоМассивуКнопок - keyboard - JSON клавиатуры или путь к .json // Разметка - Строка - Вид обработки текста (HTML, Markdown, MarkdownV2) - parsemode -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ОтправитьГифку(Знач Токен @@ -400,10 +400,10 @@ // Отправить группу медиафайлов // Отправляет набор файлов в чат или канал. Варианты типов медиа: audio, document, photo, video -// +// // Примечание: // Соответствие файлов: Ключ - Файл, Значение - один из типов медиа -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата или IDЧата*IDТемы - chat @@ -411,7 +411,7 @@ // СоответствиеФайлов - Соответствие из Строка - Коллекция файлов - media - JSON файлов или путь к .json // Клавиатура - Строка - См. СформироватьКлавиатуруПоМассивуКнопок - keyboard - JSON клавиатуры или путь к .json // Разметка - Строка - Вид обработки текста (HTML, Markdown, MarkdownV2) - parsemode -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ОтправитьМедиагруппу(Знач Токен @@ -420,27 +420,27 @@ , Знач СоответствиеФайлов , Знач Клавиатура = "" , Знач Разметка = "Markdown") Экспорт - + // СоответствиеФайлов // Ключ - Файл, Значение - Тип // Типы: audio, document, photo, video // Нельзя замешивать разные типы! Строка_ = "Строка"; - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDЧата); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(СоответствиеФайлов); - + OPI_Инструменты.ЗаменитьСпецсимволы(Текст, Разметка); URL = "api.telegram.org/bot" + Токен + "/sendMediaGroup"; Медиа = Новый Массив; Параметры = Новый Структура; - + ДобавитьИдентификаторЧата(IDЧата, Параметры); ПреобразоватьФайлыВМедиа(СоответствиеФайлов, Текст, Медиа); - + OPI_Инструменты.ДобавитьПоле("parse_mode" , Разметка , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("caption" , Текст , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("media" , Медиа , Строка_ , Параметры); @@ -454,14 +454,14 @@ // Отправить местоположение // Отправляет местоположение по географической широте и долготе в чат или канал -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата или IDЧата*IDТемы - chat // Широта - Строка,Число - Географическая широта - lat // Долгота - Строка,Число - Географическая долгота - long // Клавиатура - Строка - См. СформироватьКлавиатуруПоМассивуКнопок - keyboard - JSON клавиатуры или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ОтправитьМестоположение(Знач Токен, Знач IDЧата, Знач Широта, Знач Долгота, Знач Клавиатура = "") Экспорт @@ -469,15 +469,15 @@ Строка_ = "Строка"; OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDЧата); - + URL = "api.telegram.org/bot" + Токен + "/sendLocation"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("parse_mode" , "Markdown" , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("latitude" , Широта , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("longitude" , Долгота , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("reply_markup", Клавиатура , "СтрокаФайла", Параметры); - + ДобавитьИдентификаторЧата(IDЧата, Параметры); Ответ = OPI_Инструменты.Get(URL, Параметры); @@ -488,7 +488,7 @@ // Отправить контакт // Отправляет контакт с именем и номером телефона -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата или IDЧата*IDТемы - chat @@ -496,7 +496,7 @@ // Фамилия - Строка - Фамилия контакта - surname // Телефон - Строка - Телефон контакта - phone // Клавиатура - Строка - См. СформироватьКлавиатуруПоМассивуКнопок - keyboard - JSON клавиатуры или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ОтправитьКонтакт(Знач Токен, Знач IDЧата, Знач Имя, Знач Фамилия, Знач Телефон, Знач Клавиатура = "") Экспорт @@ -504,7 +504,7 @@ Строка_ = "Строка"; OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDЧата); - + URL = "api.telegram.org/bot" + Токен + "/sendContact"; Параметры = Новый Структура; @@ -513,7 +513,7 @@ OPI_Инструменты.ДобавитьПоле("last_name" , Фамилия , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("phone_number", Телефон , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("reply_markup", Клавиатура, "СтрокаФайла", Параметры); - + ДобавитьИдентификаторЧата(IDЧата, Параметры); Ответ = OPI_Инструменты.Get(URL, Параметры); @@ -524,14 +524,14 @@ // Отправить опрос // Отправляет опрос с вариантами ответа -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата или IDЧата*IDТемы - chat // Вопрос - Строка - Вопрос опроса - question // МассивОтветов - Массив из Строка - Массив вариантов ответа - options // Анонимный - Булево - Анонимность опроса - anonymous -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ОтправитьОпрос(Знач Токен, Знач IDЧата, Знач Вопрос, Знач МассивОтветов, Знач Анонимный = Истина) Экспорт @@ -541,15 +541,15 @@ OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивОтветов); OPI_ПреобразованиеТипов.ПолучитьБулево(Анонимный); - + URL = "api.telegram.org/bot" + Токен + "/sendPoll"; Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("parse_mode", "Markdown" , "Строка" , Параметры); OPI_Инструменты.ДобавитьПоле("question" , Вопрос , "Строка" , Параметры); OPI_Инструменты.ДобавитьПоле("options" , МассивОтветов, "СтрокаФайла", Параметры); - - Параметры.Вставить("is_anonymous", ?(Анонимный, 1, 0)); + + Параметры.Вставить("is_anonymous", ?(Анонимный, 1, 0)); ДобавитьИдентификаторЧата(IDЧата, Параметры); Ответ = OPI_Инструменты.Get(URL, Параметры); @@ -560,13 +560,13 @@ // Переслать сообщение // Пересылает сообщение между чатами или в рамках одного чата -// +// // Параметры: // Токен - Строка - Токен бота - token // IDОригинала - Строка,Число - ID оригинального сообщения - message // ОткудаID - Строка,Число - ID чата оригинального сообщения - from // КудаID - Строка,Число - ID целевого чата или IDЧата*IDТемы - to -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ПереслатьСообщение(Знач Токен, Знач IDОригинала, Знач ОткудаID, Знач КудаID) Экспорт @@ -575,15 +575,15 @@ OPI_ПреобразованиеТипов.ПолучитьСтроку(IDОригинала); OPI_ПреобразованиеТипов.ПолучитьСтроку(ОткудаID); OPI_ПреобразованиеТипов.ПолучитьСтроку(КудаID); - + URL = "api.telegram.org/bot" + Токен + "/forwardMessage"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("from_chat_id", ОткудаID , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("message_id" , IDОригинала, "Строка", Параметры); ДобавитьИдентификаторЧата(КудаID, Параметры); - + Ответ = OPI_Инструменты.Get(URL, Параметры); Возврат Ответ; @@ -592,12 +592,12 @@ // Сформировать клавиатуру по массиву кнопок // Формирует простую JSON клавиатуру из массив кнопок для сообщения или нижней панели -// +// // Параметры: -// МассивКнопок - Массив из Строка - Массив кнопок - buttons +// МассивКнопок - Массив из Строка - Массив кнопок - buttons // ПодСообщением - Булево - Клавиатура под сообщением или на нижней панели - under // ОднаПодОдной - Булево - Истина > кнопки выводятся в столбик, Ложь > в строку - column -// +// // Возвращаемое значение: // Строка - JSON клавиатуры Функция СформироватьКлавиатуруПоМассивуКнопок(Знач МассивКнопок @@ -607,7 +607,7 @@ OPI_ПреобразованиеТипов.ПолучитьБулево(ПодСообщением); OPI_ПреобразованиеТипов.ПолучитьБулево(ОднаПодОдной); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивКнопок); - + Если ОднаПодОдной Тогда Строки = СоздатьВысокуюКлавиатуру(МассивКнопок); Иначе @@ -615,7 +615,7 @@ КонецЕсли; Если ПодСообщением Тогда - СтруктураПараметра = Новый Структура("inline_keyboard,rows", Строки, 1); + СтруктураПараметра = Новый Структура("inline_keyboard,rows" , Строки, 1); Иначе СтруктураПараметра = Новый Структура("keyboard,resize_keyboard", Строки, Истина); КонецЕсли; @@ -632,19 +632,19 @@ // Бан // Банит пользователя в выбранном чате -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата или IDЧата*IDТемы - chat // IDПользователя - Строка,Число - ID целевого пользователя - user -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция Бан(Знач Токен, Знач IDЧата, Знач IDПользователя) Экспорт Строка_ = "Строка"; OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + URL = "api.telegram.org/bot" + Токен + "/banChatMember"; Параметры = Новый Структура; @@ -660,22 +660,22 @@ // Разбан // Разбанивает забаненного ранее пользователя -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата или IDЧата*IDТемы - chat // IDПользователя - Строка,Число - ID целевого пользователя - user -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция Разбан(Знач Токен, Знач IDЧата, Знач IDПользователя) Экспорт Строка_ = "Строка"; OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + URL = "api.telegram.org/bot" + Токен + "/unbanChatMember"; - Параметры = Новый Структура; + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("parse_mode" , "Markdown" , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("chat_id" , IDЧата , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("user_id" , IDПользователя, Строка_ , Параметры); @@ -689,14 +689,14 @@ // Создать ссылку-приглашение // Создает ссылку для вступления в закрытый чат -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата или IDЧата*IDТемы - chat // Заголовок - Строка - Заголовок приглашения - title // ДатаИстечения - Дата - Дата окончания жизни ссылки (безсрочно, если не указано) - expire // ЛимитПользователей - Число - Лимит пользователей (бесконечно, если не указано) - limit -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция СоздатьСсылкуПриглашение(Знач Токен @@ -707,16 +707,16 @@ Строка_ = "Строка"; OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + URL = "api.telegram.org/bot" + Токен + "/createChatInviteLink"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("parse_mode" , "Markdown" , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("chat_id" , IDЧата , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("name" , Заголовок , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("member_limit" , ЛимитПользователей, Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("expire_date" , ДатаИстечения , "Дата" , Параметры); - + Ответ = OPI_Инструменты.Get(URL, Параметры); Возврат Ответ; @@ -725,21 +725,21 @@ // Закрепить сообщение // Закрепляет сообщение в шапке чата -// +// // Параметры: // Токен - Строка - Токен - token // IDЧата - Строка,Число - ID целевого чата - chat // IDСообщения - Строка,Число - ID целевого сообщения - message -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ЗакрепитьСообщение(Знач Токен, Знач IDЧата, Знач IDСообщения) Экспорт - + Строка_ = "Строка"; OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + URL = "api.telegram.org/bot" + Токен + "/pinChatMessage"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("parse_mode" , "Markdown" , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("chat_id" , IDЧата , Строка_ , Параметры); @@ -754,21 +754,21 @@ // Открепить сообщение // Открепляет сообщение в шапке чата -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата - chat // IDСообщения - Строка,Число - ID целевого сообщения - message -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ОткрепитьСообщение(Знач Токен, Знач IDЧата, Знач IDСообщения) Экспорт - + Строка_ = "Строка"; OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + URL = "api.telegram.org/bot" + Токен + "/unpinChatMessage"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("parse_mode", "Markdown" , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("chat_id" , IDЧата , Строка_, Параметры); @@ -782,19 +782,19 @@ // Получить число участников // Получает общее число участников чата -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата - chat -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ПолучитьЧислоУчастников(Знач Токен, Знач IDЧата) Экспорт OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + URL = "api.telegram.org/bot" + Токен + "/getChatMemberCount"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("parse_mode", "Markdown" , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("chat_id" , IDЧата , "Строка", Параметры); @@ -807,24 +807,24 @@ // Удалить сообщение // Удаляет указанное сообщение из чата или канала -// +// // Параметры: // Токен - Строка - Токен - token // IDЧата - Строка,Число - ID целевого чата - chat // IDСообщения - Строка,Число - ID удаляемого сообщения - message -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция УдалитьСообщение(Знач Токен, Знач IDЧата, Знач IDСообщения) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + URL = "api.telegram.org/bot" + Токен + "/deleteMessage"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("message_id", IDСообщения, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("chat_id" , IDЧата , "Строка", Параметры); - + Ответ = OPI_Инструменты.Get(URL, Параметры); Возврат Ответ; @@ -836,206 +836,206 @@ // Получить список иконок-аватаров // Получает соответствие ID Emoji для установки в качестве иконок тем форума -// +// // Параметры: // Токен - Строка - Токен - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - Ключ > ID, Значение > Emoji Функция ПолучитьСписокИконокАватаров(Знач Токен) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Result = "result"; - URL = "api.telegram.org/bot" + Токен + "/getForumTopicIconStickers"; - Ответ = OPI_Инструменты.Get(URL); + URL = "api.telegram.org/bot" + Токен + "/getForumTopicIconStickers"; + Ответ = OPI_Инструменты.Get(URL); Иконки = Ответ[Result]; - + Если Не ЗначениеЗаполнено(Иконки) Тогда Возврат Ответ; - КонецЕсли; - + КонецЕсли; + Коллекция = Новый Соответствие; - + Для Каждого Иконка Из Иконки Цикл Коллекция.Вставить(Иконка["custom_emoji_id"], Иконка["emoji"]); КонецЦикла; - + Возврат Коллекция; КонецФункции // Создать тему форума // Создает новую тему в группе с включенным функционалом тем -// +// // Параметры: // Токен - Строка - Токен - token // IDЧата - Строка,Число - ID чата создания темы - forum // Заголовок - Строка - Заголовок темы - title // IDИконки - Строка - См. ПолучитьСписокИконокАватаров - icon -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция СоздатьТемуФорума(Знач Токен, Знач IDЧата, Знач Заголовок, Знач IDИконки = "") Экспорт - + Возврат УправлениеТемойФорума(Токен, IDЧата, Заголовок, IDИконки); - + КонецФункции // Изменить тему форума // Создает новую тему в группе с включенным функционалом тем -// +// // Параметры: // Токен - Строка - Токен - token // IDЧата - Строка,Число - ID чата создания темы - forum // IDТемы - Строка,Число - ID темы - topic // Заголовок - Строка - Новый заголовок - title // IDИконки - Строка - См. ПолучитьСписокИконокАватаров - icon -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ИзменитьТемуФорума(Знач Токен , Знач IDЧата , Знач IDТемы , Знач Заголовок = Неопределено - , Знач IDИконки = Неопределено) Экспорт - + , Знач IDИконки = Неопределено) Экспорт + Возврат УправлениеТемойФорума(Токен, IDЧата, Заголовок, IDИконки, IDТемы); КонецФункции // Закрыть тему форума // Закрывает тему для новых сообщений -// +// // Параметры: // Токен - Строка - Токен - token // IDЧата - Строка,Число - ID чата темы - forum // IDТемы - Строка,Число - ID темы - topic -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ЗакрытьТемуФорума(Знач Токен, Знач IDЧата, Знач IDТемы = "") Экспорт - - Возврат УправлениеСостояниемТемыФорума(Токен, IDЧата, 2, IDТемы); - + + Возврат УправлениеСостояниемТемыФорума(Токен, IDЧата, 2, IDТемы); + КонецФункции // Открыть тему форума // Повторно открывает ранее закрытую тему форума -// +// // Параметры: // Токен - Строка - Токен - token // IDЧата - Строка,Число - ID чата темы - forum // IDТемы - Строка,Число - ID темы - topic -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ОткрытьТемуФорума(Знач Токен, Знач IDЧата, Знач IDТемы = "") Экспорт - - Возврат УправлениеСостояниемТемыФорума(Токен, IDЧата, 1, IDТемы); - + + Возврат УправлениеСостояниемТемыФорума(Токен, IDЧата, 1, IDТемы); + КонецФункции // Удалить тему форума // Удаляет тему форума -// +// // Параметры: // Токен - Строка - Токен - token // IDЧата - Строка,Число - ID чата темы - forum // IDТемы - Строка,Число - ID темы - topic -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция УдалитьТемуФорума(Знач Токен, Знач IDЧата, Знач IDТемы) Экспорт - - Возврат УправлениеСостояниемТемыФорума(Токен, IDЧата, 3, IDТемы); - + + Возврат УправлениеСостояниемТемыФорума(Токен, IDЧата, 3, IDТемы); + КонецФункции // Скрыть главную тему форума // Скрывает главную тему форума -// +// // Параметры: // Токен - Строка - Токен - token // IDЧата - Строка,Число - ID чата темы - forum -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция СкрытьГлавнуюТемуФорума(Знач Токен, Знач IDЧата) Экспорт - + Возврат УправлениеВидимостьюГлавнойТемыФорума(Токен, IDЧата, Истина); - + КонецФункции // Показать главную тему форума // Показывает ранее скрытую главную тему форума -// +// // Параметры: // Токен - Строка - Токен - token // IDЧата - Строка,Число - ID чата темы - forum -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ПоказатьГлавнуюТемуФорума(Знач Токен, Знач IDЧата) Экспорт - + Возврат УправлениеВидимостьюГлавнойТемыФорума(Токен, IDЧата, Ложь); - + КонецФункции // Изменить имя главной темы форума // Изменяет имя главной темы форума -// +// // Параметры: // Токен - Строка - Токен - token // IDЧата - Строка,Число - ID чата темы - forum // Заголовок - Строка - Новое имя главной темы - title -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ИзменитьИмяГлавнойТемыФорума(Знач Токен, Знач IDЧата, Знач Заголовок) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + URL = "api.telegram.org/bot" + Токен + "/editGeneralForumTopic"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("chat_id", IDЧата , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("name" , Заголовок, "Строка", Параметры); - + Ответ = OPI_Инструменты.Get(URL, Параметры); - + Возврат Ответ; КонецФункции // Очистить список закрепленных сообщений темы // Очищает список закрепленных сообщений в теме форума -// +// // Параметры: // Токен - Строка - Токен - token // IDЧата - Строка,Число - ID чата темы - forum // IDТемы - Строка,Число - ID темы. Главная, если не заполнено - topic -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ОчиститьСписокЗакрепленныхСообщенийТемы(Знач Токен, Знач IDЧата, Знач IDТемы = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDЧата); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDТемы); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("chat_id" , IDЧата, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("message_thread_id", IDТемы, "Строка", Параметры); - + Если ЗначениеЗаполнено(IDТемы) Тогда Метод = "/unpinAllForumTopicMessages"; Иначе Метод = "/unpinAllGeneralForumTopicMessages"; КонецЕсли; - + URL = "api.telegram.org/bot" + Токен + Метод; Ответ = OPI_Инструменты.Get(URL, Параметры); - + Возврат Ответ; КонецФункции @@ -1061,20 +1061,20 @@ OPI_ПреобразованиеТипов.ПолучитьСтроку(Текст); OPI_Инструменты.ЗаменитьСпецсимволы(Текст, Разметка); - + Если Не ЗначениеЗаполнено(ИмяФайла) Тогда ИмяФайла = ПреобразоватьДанныеФайла(Файл, Вид, ""); Иначе OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Файл); КонецЕсли; - + ИмяФайла = Вид + "|" + ИмяФайла; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("parse_mode" , Разметка , "Строка" , Параметры); OPI_Инструменты.ДобавитьПоле("caption" , Текст , "Строка" , Параметры); OPI_Инструменты.ДобавитьПоле("reply_markup", Клавиатура, "СтрокаФайла", Параметры); - + ДобавитьИдентификаторЧата(IDЧата, Параметры); СоответствиеФайлов = Новый Соответствие; @@ -1091,55 +1091,55 @@ Функция УправлениеТемойФорума(Знач Токен , Знач IDЧата , Знач Заголовок = Неопределено - , Знач IDИконки = Неопределено - , Знач IDТемы = "") - + , Знач IDИконки = Неопределено + , Знач IDТемы = "") + Строка_ = "Строка"; OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("name" , Заголовок, Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("chat_id" , IDЧата , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("icon_custom_emoji_id", IDИконки , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("message_thread_id" , IDТемы , Строка_, Параметры); - + Если ЗначениеЗаполнено(IDТемы) Тогда - Метод = "/editForumTopic"; - Иначе - Метод = "/createForumTopic"; + Метод = "/editForumTopic"; + Иначе + Метод = "/createForumTopic"; КонецЕсли; - + Ответ = OPI_Инструменты.Get("api.telegram.org/bot" + Токен + Метод, Параметры); - + Возврат Ответ; КонецФункции -Функция УправлениеСостояниемТемыФорума(Знач Токен, Знач IDЧата, Знач Статус, Знач IDТемы = "") - +Функция УправлениеСостояниемТемыФорума(Знач Токен, Знач IDЧата, Знач Статус, Знач IDТемы = "") + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Если ЗначениеЗаполнено(IDТемы) Тогда Форум = "Forum"; Иначе Форум = "GeneralForum"; КонецЕсли; - + Метод = ОпределитьМетодУправленияФорумом(Статус, Форум); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("chat_id" , IDЧата, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("message_thread_id", IDТемы, "Строка", Параметры); - + URL = "api.telegram.org/bot" + Токен + Метод; Ответ = OPI_Инструменты.Get(URL, Параметры); Возврат Ответ; - + КонецФункции Функция УправлениеВидимостьюГлавнойТемыФорума(Знач Токен, Знач IDЧата, Знач Скрыть) - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьБулево(Скрыть); @@ -1148,41 +1148,41 @@ Иначе Метод = "/unhideGeneralForumTopic"; КонецЕсли; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("chat_id", IDЧата, "Строка", Параметры); - + URL = "api.telegram.org/bot" + Токен + Метод; Ответ = OPI_Инструменты.Get(URL, Параметры); - + Возврат Ответ; -КонецФункции +КонецФункции + +Функция ОпределитьМетодУправленияФорумом(Знач Статус, Знач Форум) -Функция ОпределитьМетодУправленияФорумом(Знач Статус, Знач Форум) - Открыть = 1; Закрыть = 2; Удалить = 3; - - Если Статус = Открыть Тогда - Метод = "/reopen" + Форум + "Topic"; + + Если Статус = Открыть Тогда + Метод = "/reopen" + Форум + "Topic"; ИначеЕсли Статус = Закрыть Тогда - Метод = "/close" + Форум + "Topic"; + Метод = "/close" + Форум + "Topic"; ИначеЕсли Статус = Удалить Тогда - Метод = "/deleteForumTopic"; - Иначе + Метод = "/deleteForumTopic"; + Иначе ВызватьИсключение "Некорректный статус управления форумом"; КонецЕсли; - + Возврат Метод; КонецФункции Функция СоздатьВысокуюКлавиатуру(Знач МассивКнопок) - + Строки = Новый Массив; - + Для Каждого Кнопка Из МассивКнопок Цикл Кнопки = Новый Массив; Кнопка = OPI_Инструменты.ЧислоВСтроку(Кнопка); @@ -1191,82 +1191,82 @@ КонецЦикла; Возврат Строки; - + КонецФункции Функция СоздатьДлиннуюКлавиатуру(Знач МассивКнопок) - + Строки = Новый Массив; Кнопки = Новый Массив; - + Для Каждого Кнопка Из МассивКнопок Цикл Кнопка = OPI_Инструменты.ЧислоВСтроку(Кнопка); Кнопки.Добавить(Новый Структура("text,callback_data", Кнопка, Кнопка)); КонецЦикла; - + Строки.Добавить(Кнопки); - + Возврат Строки; КонецФункции Функция ОпределитьМетодОтправки(Знач Вид) - - Если Вид = "photo" Тогда - Метод = "/sendPhoto"; + + Если Вид = "photo" Тогда + Метод = "/sendPhoto"; ИначеЕсли Вид = "video" Тогда - Метод = "/sendVideo"; + Метод = "/sendVideo"; ИначеЕсли Вид = "audio" Тогда - Метод = "/sendAudio"; + Метод = "/sendAudio"; ИначеЕсли Вид = "animation" Тогда - Метод = "/sendAnimation"; + Метод = "/sendAnimation"; Иначе - Метод = "/sendDocument"; + Метод = "/sendDocument"; КонецЕсли; Возврат Метод; - + КонецФункции Функция ПреобразоватьДанныеФайла(Файл, Вид, Счетчик) - + ИмяФайла = ""; - + Если ТипЗнч(Файл) = Тип("Строка") И Вид = "document" Тогда - + ТекущийФайл = Новый Файл(Файл); ИмяФайла = ТекущийФайл.Имя; - + КонецЕсли; - + Если Не ЗначениеЗаполнено(ИмяФайла) Тогда ИмяФайла = Вид + Строка(Счетчик); - - Если Вид = "animation" Тогда - ИмяФайла = ИмяФайла + ".gif"; + + Если Вид = "animation" Тогда + ИмяФайла = ИмяФайла + ".gif"; КонецЕсли; - + КонецЕсли; - + OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Файл); - + Возврат ИмяФайла; - + КонецФункции Процедура ПреобразоватьФайлыВМедиа(СоответствиеФайлов, Текст, Медиа) - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(СоответствиеФайлов); OPI_ПреобразованиеТипов.ПолучитьСтроку(Текст); - + Если ТипЗнч(СоответствиеФайлов) <> Тип("Соответствие") Тогда ВызватьИсключение("Не удалось получить информацию из json медиа!"); Возврат; КонецЕсли; - + ВременноеСоответствие = Новый Соответствие; Счетчик = 0; - + Для Каждого ТекущийФайл Из СоответствиеФайлов Цикл ТекущиеДанные = ТекущийФайл.Ключ; @@ -1291,24 +1291,24 @@ КонецЦикла; Медиа = OPI_Инструменты.JSONСтрокой(Медиа); - СоответствиеФайлов = ВременноеСоответствие; - + СоответствиеФайлов = ВременноеСоответствие; + КонецПроцедуры Процедура ДобавитьИдентификаторЧата(Знач IDЧата, Параметры) - + IDЧата = OPI_Инструменты.ЧислоВСтроку(IDЧата); МассивЧата = СтрРазделить(IDЧата, "*", Ложь); - + Если МассивЧата.Количество() > 1 Тогда - + IDЧата = МассивЧата[0]; IDТемы = МассивЧата[1]; - + Параметры.Вставить("message_thread_id", IDТемы); - + КонецЕсли; - + Параметры.Вставить("chat_id", IDЧата); КонецПроцедуры diff --git a/src/ru/OInt/core/Modules/OPI_Twitter.os b/src/ru/OInt/core/Modules/OPI_Twitter.os index 9374496202..0b1542911b 100644 --- a/src/ru/OInt/core/Modules/OPI_Twitter.os +++ b/src/ru/OInt/core/Modules/OPI_Twitter.os @@ -48,18 +48,18 @@ // Получить ссылку для авторизации // Формирует ссылку для авторизации через браузер -// +// // Параметры: // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Строка - URL для перехода в браузере Функция ПолучитьСсылкуАвторизации(Параметры = "") Экспорт - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); - + ПараметрыURL = Новый Структура; - + ПараметрыURL.Вставить("response_type" , "code"); ПараметрыURL.Вставить("client_id" , Параметры_["client_id"]); ПараметрыURL.Вставить("redirect_uri" , Параметры_["redirect_uri"]); @@ -67,27 +67,27 @@ ПараметрыURL.Вставить("state" , "state"); ПараметрыURL.Вставить("code_challenge" , "challenge"); ПараметрыURL.Вставить("code_challenge_method", "plain"); - + ПараметрыURL = OPI_Инструменты.ПараметрыЗапросаВСтроку(ПараметрыURL); - Линк = "https://twitter.com/i/oauth2/authorize" + ПараметрыURL; - + Линк = "https://twitter.com/i/oauth2/authorize" + ПараметрыURL; + Возврат Линк; - + КонецФункции // Получить токен // Получает токен по коду, полученному при авторизации по ссылке из ПолучитьСсылкуАвторизации -// +// // Параметры: // Код - Строка - Код, полученный из авторизации См.ПолучитьСсылкуАвторизации - code // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Twitter Функция ПолучитьТокен(Знач Код, Знач Параметры = "") Экспорт OPI_ПреобразованиеТипов.ПолучитьСтроку(Код); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); ПараметрыЗапроса = Новый Структура; @@ -96,35 +96,35 @@ ПараметрыЗапроса.Вставить("client_id" , Параметры_["client_id"]); ПараметрыЗапроса.Вставить("redirect_uri" , Параметры_["redirect_uri"]); ПараметрыЗапроса.Вставить("code_verifier", "challenge"); - + Ответ = OPI_Инструменты.Post("https://api.twitter.com/2/oauth2/token" , ПараметрыЗапроса, , Ложь); - + Возврат Ответ; - + КонецФункции -// Обновить токен +// Обновить токен // Обновляет v2 токен при помощи refresh_token -// +// // Параметры: // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Twitter Функция ОбновитьТокен(Знач Параметры = "") Экспорт - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Refresh = "refresh_token"; - + ПараметрыЗапроса = Новый Структура; ПараметрыЗапроса.Вставить(Refresh , Параметры_[Refresh]); ПараметрыЗапроса.Вставить("grant_type" , Refresh); ПараметрыЗапроса.Вставить("client_id" , Параметры_["client_id"]); - + Ответ = OPI_Инструменты.Post("https://api.twitter.com/2/oauth2/token" , ПараметрыЗапроса, , Ложь); - + Возврат Ответ; КонецФункции @@ -133,23 +133,23 @@ // Метод для вставки в http-сервис, адрес которого указывается в redirect_uri // Вызывает метод получения токена, так как для получения токена из кода, приходящего // на redirect_uri после авторизации через браузер есть всего 30 секунд -// +// // Параметры: // Запрос - HTTPСервисЗапрос - Запрос, приходящий на http-сервис -// +// // Возвращаемое значение: // HTTPОтвет, Произвольный, ДвоичныеДанные - Результат чтения JSON ответа сервера Функция ОбработкаВходящегоЗапросаПослеАвторизации(Запрос) Экспорт - - Код = Запрос.ПараметрыЗапроса["code"]; + + Код = Запрос.ПараметрыЗапроса["code"]; ОтветТокен = ПолучитьТокен(Код); - + // BSLLS:CommentedCode-off // Предпочтительное хранение токенов // Константы.TwitterRefresh.Установить(ОтветТокен["refresh_token"]); // Константы.TwitterToken.Установить(ОтветТокен["access_token"]); // BSLLS:CommentedCode-on - + Возврат ОтветТокен; КонецФункции @@ -160,189 +160,189 @@ // !NOCLI // Создать произвольный твит -// +// // Параметры: // Текст - Строка - Текст твита // МассивМедиа - Массив из Строка,ДвоичныеДанные - Массив двоичных данных или путей к файлам // МассивВариантовОпроса - Массив из Строка - Массив вариантов опроса, если необходимо // ДлительностьОпроса - Строка,Число - Длительность опроса, если необходимо (опрос без длительности не создается) // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Twitter Функция СоздатьПроизвольныйТвит(Знач Текст = "" , Знач МассивМедиа = "" , Знач МассивВариантовОпроса = "" , Знач ДлительностьОпроса = "" - , Знач Параметры = "") Экспорт - + , Знач Параметры = "") Экспорт + OPI_ПреобразованиеТипов.ПолучитьСтроку(Текст); OPI_ПреобразованиеТипов.ПолучитьСтроку(ДлительностьОпроса); - + Если ЗначениеЗаполнено(МассивМедиа) Тогда OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивМедиа); КонецЕсли; - + Если ЗначениеЗаполнено(МассивВариантовОпроса) Тогда OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивВариантовОпроса); КонецЕсли; - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); URL = "https://api.twitter.com/2/tweets"; - Массив = "Массив"; + Массив = "Массив"; Поля = Новый Соответствие; - + Если ЗначениеЗаполнено(Текст) Тогда Поля.Вставить("text", Текст); КонецЕсли; - + Если ТипЗнч(МассивВариантовОпроса) = Тип(Массив) И ЗначениеЗаполнено(ДлительностьОпроса) Тогда - + ДлительностьОпроса = Число(ДлительностьОпроса); - + Если МассивВариантовОпроса.Количество() > 0 Тогда - + СтруктураВарианта = Новый Структура("options,duration_minutes", МассивВариантовОпроса, ДлительностьОпроса); Поля.Вставить("poll", СтруктураВарианта); - + КонецЕсли; - + КонецЕсли; - + Если ТипЗнч(МассивМедиа) = Тип(Массив) Тогда Если МассивМедиа.Количество() > 0 Тогда Поля.Вставить("media", Новый Структура("media_ids", МассивМедиа)); КонецЕсли; КонецЕсли; - + Авторизация = СоздатьЗаголовокАвторизацииV2(Параметры_); Ответ = OPI_Инструменты.Post(URL, Поля, Авторизация); Возврат Ответ; - + КонецФункции // Создать текстовый твит // Создает твит без вложений -// +// // Параметры: // Текст - Строка - Текст твита - text // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Twitter Функция СоздатьТекстовыйТвит(Знач Текст, Знач Параметры = "") Экспорт - Возврат СоздатьПроизвольныйТвит(Текст, , , , Параметры); + Возврат СоздатьПроизвольныйТвит(Текст, , , , Параметры); КонецФункции // Создать твит картинки // Создает твит с картинкой вложением -// +// // Параметры: // Текст - Строка - Текст твита - text // МассивКартинок - Массив из Строка,ДвоичныеДанные - Массив файлов картинок - pictures // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Twitter Функция СоздатьТвитКартинки(Знач Текст, Знач МассивКартинок, Знач Параметры = "") Экспорт - + МассивМедиа = ЗагрузитьМассивВложений(МассивКартинок, "photo", Параметры); - Возврат СоздатьПроизвольныйТвит(Текст, МассивМедиа, , , Параметры); - + Возврат СоздатьПроизвольныйТвит(Текст, МассивМедиа, , , Параметры); + КонецФункции // Создать твит гифки // Создает твит с вложением-гифкой -// +// // Параметры: // Текст - Строка - Текст твита - text // МассивГифок - Массив из Строка,ДвоичныеДанные - Массив файлов гифок - gifs // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Twitter Функция СоздатьТвитГифки(Знач Текст, Знач МассивГифок, Знач Параметры = "") Экспорт - + МассивМедиа = ЗагрузитьМассивВложений(МассивГифок, "animated_gif", Параметры); - Возврат СоздатьПроизвольныйТвит(Текст, МассивМедиа, , , Параметры); - + Возврат СоздатьПроизвольныйТвит(Текст, МассивМедиа, , , Параметры); + КонецФункции // Создать твит видео // Создает твит с видеовложением -// +// // Параметры: // Текст - Строка - Текст твита - text // МассивВидео - Массив из Строка,ДвоичныеДанные - Массив файлов видео - videos // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Twitter Функция СоздатьТвитВидео(Знач Текст, Знач МассивВидео, Знач Параметры = "") Экспорт - + МассивМедиа = ЗагрузитьМассивВложений(МассивВидео, "video", Параметры); Возврат СоздатьПроизвольныйТвит(Текст, МассивМедиа, , , Параметры); - + КонецФункции // Создать твит опрос // Создает твит с опросом -// +// // Параметры: // Текст - Строка - Текст твита - text // МассивВариантов - Массив из Строка - Массив вариантов опроса - options // Длительность - Строка,Число - Длительность опроса - duration // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Twitter Функция СоздатьТвитОпрос(Знач Текст, Знач МассивВариантов, Знач Длительность, Знач Параметры = "") Экспорт - - Возврат СоздатьПроизвольныйТвит(Текст, , МассивВариантов, Длительность, Параметры); - + + Возврат СоздатьПроизвольныйТвит(Текст, , МассивВариантов, Длительность, Параметры); + КонецФункции // Загрузить массив вложений !NOCLI // Загружает файлы на сервер и возвращает их ID -// +// // Параметры: // МассивФайлов - Массив из Строка, ДвоичныеДанные - Массив файлов // ТипВложений - Строка - Тип вложений // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Массив Из Строка - Массив ID медиа Функция ЗагрузитьМассивВложений(Знач МассивФайлов, Знач ТипВложений, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(ТипВложений); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивФайлов); - + МассивМедиа = Новый Массив; Параметры_ = ПолучитьСтандартныеПараметры(Параметры); MIS = "media_id_string"; - + Если ЗначениеЗаполнено(МассивФайлов) Тогда - + Для Каждого ФайлОтправки Из МассивФайлов Цикл - + OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(ФайлОтправки); - + Ответ = ЗагрузитьМедиафайл(ФайлОтправки, ТипВложений, Параметры_); IDМедиа = Ответ[MIS]; - + Если Не ЗначениеЗаполнено(IDМедиа) Тогда Возврат Ответ; КонецЕсли; - + МассивМедиа.Добавить(IDМедиа); - + КонецЦикла; - + КонецЕсли; - + Возврат МассивМедиа; - + КонецФункции #КонецОбласти @@ -351,70 +351,70 @@ #Область СлужебныеПроцедурыИФункции -Функция ЗагрузитьМедиафайл(Знач Файл, Знач Тип, Знач Параметры) - +Функция ЗагрузитьМедиафайл(Знач Файл, Знач Тип, Знач Параметры) + OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Файл); - - ВидЗапроса = "POST"; + + ВидЗапроса = "POST"; Параметры_ = ПолучитьСтандартныеПараметры(Параметры); URL = "https://upload.twitter.com/1.1/media/upload.json"; - - Если Тип = "photo" Тогда - + + Если Тип = "photo" Тогда + Поля = Новый Структура; Поля.Вставить("media_data" , Base64Строка(Файл)); Поля.Вставить("media_category", Тип); - - Авторизация = СоздатьЗаголовокАвторизацииV1(Параметры_, Поля, ВидЗапроса, URL); + + Авторизация = СоздатьЗаголовокАвторизацииV1(Параметры_, Поля, ВидЗапроса, URL); Ответ = OPI_Инструменты.Post(URL, Поля, Авторизация, Ложь); - + Иначе - + Ответ = ЗагрузитьМедиаЧастями(Файл, Тип, ВидЗапроса, URL, Параметры_); - + КонецЕсли; - + Возврат Ответ; - + КонецФункции Функция ЗагрузитьМедиаЧастями(Знач Файл, Знач Тип, Знач ВидЗапроса, Знач URL, Параметры) - + Единица = 1024; Количество = 4; MediaKey = "media_key"; MIS = "media_id_string"; Command = "command"; Размер = Файл.Размер(); - + СоответствиеMIME = Новый Соответствие; СоответствиеMIME.Вставить("photo" , "image/jpeg"); СоответствиеMIME.Вставить("video" , "video/mp4"); СоответствиеMIME.Вставить("animated_gif", "image/gif"); - + РазмерЧасти = Количество * Единица * Единица; МассивЧтения = РазделитьДвоичныеДанные(Файл, РазмерЧасти); - + Поля = Новый Структура; Поля.Вставить(Command , "INIT"); Поля.Вставить("total_bytes" , OPI_Инструменты.ЧислоВСтроку(Размер)); Поля.Вставить("media_type" , СоответствиеMIME.Получить(Тип)); Поля.Вставить("media_category" , Тип); - + Авторизация = СоздатьЗаголовокАвторизацииV1(Параметры, Поля, ВидЗапроса, URL); ОтветИнициализации = OPI_Инструменты.Post(URL, Поля, Авторизация, Ложь); KeyИнициализации = ОтветИнициализации[MediaKey]; IDИнициализации = ОтветИнициализации[MIS]; - + Если Не ЗначениеЗаполнено(KeyИнициализации) Или Не ЗначениеЗаполнено(IDИнициализации) Тогда - Возврат ОтветИнициализации; + Возврат ОтветИнициализации; КонецЕсли; - + Счетчик = 0; - + Для Каждого Часть Из МассивЧтения Цикл - + Поля = Новый Структура; Поля.Вставить(Command , "APPEND"); Поля.Вставить("media_key" , KeyИнициализации); @@ -422,111 +422,111 @@ Поля.Вставить("media" , Часть); Авторизация = СоздатьЗаголовокАвторизацииV1(Параметры, Новый Структура, ВидЗапроса, URL); - + OPI_Инструменты.PostMultipart(URL, Поля, , , Авторизация); - + Счетчик = Счетчик + 1; - + КонецЦикла; - + Поля = Новый Структура; Поля.Вставить(Command , "FINALIZE"); Поля.Вставить("media_id", IDИнициализации); - + СтатусОбработки = ПолучитьСтатусОбработки(Параметры, Поля, URL); - + Если Не ТипЗнч(СтатусОбработки) = Тип("Строка") Тогда Возврат СтатусОбработки; КонецЕсли; - + Ответ = ОжидатьЗавершенияОбработки(СтатусОбработки, IDИнициализации, URL, Параметры); - + Возврат Ответ; - + КонецФункции Функция ОжидатьЗавершенияОбработки(Знач СтатусОбработки, Знач IDИнициализации, Знач URL, Знач Параметры) - + ProcessingInfo = "processing_info"; Command = "command"; Поля = Новый Структура; - + Поля.Вставить(Command , "STATUS"); Поля.Вставить("media_id", IDИнициализации); Пока Строка(СтатусОбработки) = "pending" Или Строка(СтатусОбработки) = "in_progress" Цикл - - Авторизация = СоздатьЗаголовокАвторизацииV1(Параметры, Поля, "GET", URL); - Ответ = OPI_Инструменты.Get(URL, Поля, Авторизация); + + Авторизация = СоздатьЗаголовокАвторизацииV1(Параметры, Поля, "GET", URL); + Ответ = OPI_Инструменты.Get(URL, Поля, Авторизация); Информация = Ответ[ProcessingInfo]; Если Не ЗначениеЗаполнено(Информация) Тогда Возврат Ответ; КонецЕсли; - + СтатусОбработки = Информация["state"]; - + Если Не ЗначениеЗаполнено(СтатусОбработки) Тогда Возврат Ответ; КонецЕсли; - + КонецЦикла; - + Если СтатусОбработки = "failed" Тогда ВызватьИсключение "Твиттер не смог обработать загруженное вами видео"; КонецЕсли; - + Возврат Ответ; - + КонецФункции Функция ПолучитьСтандартныеПараметры(Знач Параметры = "") - + // Здесь собрано определение данных, необходимых для работы. // Для Twitter это довольно значительный набор, что обсуловлено наличием сразу 2-х API, // которые, при этом, созданы не для разныз задач, но просто являются версиями друг друга. // Актуальной версией API является v2 и она требует получения временных токенов. Несмотря на то, // что Twitter настаивает на использовании этой актуальной версии, они как-то умудрились не перенести - // механизм загрузки файлов и некоторые другие из старой версии - v1.1. Поэтому что-то нужно делать + // механизм загрузки файлов и некоторые другие из старой версии - v1.1. Поэтому что-то нужно делать // на версии 1.1, а что-то на 2: вплоть до того что они убрали возможность постить твиты из v1.1, // но только через нее в твит можно добавить картинку. При этом способы авторизации и токены у них разные - + // Мировая гигокорпорация Илона Маска, кстати, напоминаю ;) - - // P.S Далее часто упоминается "страница настроек Twitter Developer" - это + + // P.S Далее часто упоминается "страница настроек Twitter Developer" - это // https://developer.twitter.com/en/portal/dashboard и выбор конкретного проекта из списка (значек c ключем) - - Параметры_ = Новый Соответствие; + + Параметры_ = Новый Соответствие; Разрешения = "tweet.read tweet.write tweet.moderate.write users.read " + "follows.read follows.write offline.access space.read mute.read " + "mute.write like.read like.write list.read list.write block.read " - + "block.write bookmark.read bookmark.write"; - + + "block.write bookmark.read bookmark.write"; + // Данные для API v2 - + // redirect_uri - URL вашего http-сервиса (или другого обработчика запросов) для авторизации // scope - набор разрешений для получаемого ключа. Может быть любой, но offline.access обязателен // client_id - Из OAuth 2.0 Client ID and Client Secret страницы настроек Twitter Developer // client_secret - Из OAuth 2.0 Client ID and Client Secret страницы настроек Twitter Developer // access_token - ПолучитьСсылкуАвторизации() -> Браузер -> code придет на redirect_uri -> ПолучитьТокен(code) // refresh_token - Приходит вместе с access_token и используется для его обновления (время жизни access_token - 2 ч) - // Обновление происходит методом ОбновитьТокен с новыми access_token и refresh_token. - // При следующем обновлении нужно использовать уже новый refresh_token, так что захардкодить - // не получится (access_token тоже не получится) - + // Обновление происходит методом ОбновитьТокен с новыми access_token и refresh_token. + // При следующем обновлении нужно использовать уже новый refresh_token, так что захардкодить + // не получится (access_token тоже не получится) + // |--> ОбновитьТокен() ->|access_token --> Используется в т-нии 2-х часов для запросов // | |refresh_token --| // |--------[через 2 ч.]-------------------| - + // Данные для API v1.1 - - // oauth_token - Из Authentication Tokens -> Access Token and Secret страницы настроек Twitter Developer + + // oauth_token - Из Authentication Tokens -> Access Token and Secret страницы настроек Twitter Developer // oauth_token_secret - Из Authentication Tokens -> Access Token and Secret страницы настроек Twitter Developer // oauth_consumer_key - Из Consumer Keys -> Access Token and Secret страницы настроек Twitter Developer // oauth_consumer_secret - Из Consumer Keys -> Access Token and Secret страницы настроек Twitter Developer - + // Эти токены обновлять не надо - + Параметры_.Вставить("redirect_uri" , ""); Параметры_.Вставить("scope" , Разрешения); Параметры_.Вставить("client_id" , ""); @@ -537,9 +537,9 @@ Параметры_.Вставить("oauth_token_secret" , ""); Параметры_.Вставить("oauth_consumer_key" , ""); Параметры_.Вставить("oauth_consumer_secret", ""); - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Параметры); - + Если ТипЗнч(Параметры) = Тип("Структура") Или ТипЗнч(Параметры) = Тип("Соответствие") Тогда Для Каждого ПереданныйПараметр Из Параметры Цикл Параметры_.Вставить(ПереданныйПараметр.Ключ, OPI_Инструменты.ЧислоВСтроку(ПереданныйПараметр.Значение)); @@ -551,7 +551,7 @@ КонецФункции Функция СоздатьЗаголовокАвторизацииV1(Знач Параметры, Знач Поля, Знач ВидЗапроса, Знач URL) - + ТекущаяДата = OPI_Инструменты.ПолучитьТекущуюДату(); ЗаголовокАвторизации = ""; МетодХэширования = "HMAC-SHA1"; @@ -565,123 +565,123 @@ ТаблицаПараметров = Новый ТаблицаЗначений; ТаблицаПараметров.Колонки.Добавить("Ключ"); ТаблицаПараметров.Колонки.Добавить("Значение"); - - Для Каждого Поле Из Поля Цикл - - НоваяСтрока = ТаблицаПараметров.Добавить(); + + Для Каждого Поле Из Поля Цикл + + НоваяСтрока = ТаблицаПараметров.Добавить(); НоваяСтрока.Ключ = Поле.Ключ; НоваяСтрока.Значение = Поле.Значение; - + КонецЦикла; - - НоваяСтрока = ТаблицаПараметров.Добавить(); + + НоваяСтрока = ТаблицаПараметров.Добавить(); НоваяСтрока.Ключ = OCK; НоваяСтрока.Значение = Параметры[OCK]; - - НоваяСтрока = ТаблицаПараметров.Добавить(); + + НоваяСтрока = ТаблицаПараметров.Добавить(); НоваяСтрока.Ключ = OTK; НоваяСтрока.Значение = Параметры[OTK]; - - НоваяСтрока = ТаблицаПараметров.Добавить(); + + НоваяСтрока = ТаблицаПараметров.Добавить(); НоваяСтрока.Ключ = "oauth_version"; НоваяСтрока.Значение = ВерсияАпи; - - НоваяСтрока = ТаблицаПараметров.Добавить(); + + НоваяСтрока = ТаблицаПараметров.Добавить(); НоваяСтрока.Ключ = "oauth_signature_method"; НоваяСтрока.Значение = МетодХэширования; - НоваяСтрока = ТаблицаПараметров.Добавить(); + НоваяСтрока = ТаблицаПараметров.Добавить(); НоваяСтрока.Ключ = "oauth_timestamp"; НоваяСтрока.Значение = ТекущаяДатаUNIX; - НоваяСтрока = ТаблицаПараметров.Добавить(); + НоваяСтрока = ТаблицаПараметров.Добавить(); НоваяСтрока.Ключ = "oauth_nonce"; НоваяСтрока.Значение = ТекущаяДатаUNIX; Для Каждого СтрокаТаблицы Из ТаблицаПараметров Цикл - + СтрокаТаблицы.Ключ = КодироватьСтроку(СтрокаТаблицы.Ключ, СпособКодированияСтроки.КодировкаURL); СтрокаТаблицы.Значение = КодироватьСтроку(СтрокаТаблицы.Значение, СпособКодированияСтроки.КодировкаURL); - + КонецЦикла; - + ТаблицаПараметров.Сортировать("Ключ"); - + Для Каждого СтрокаТаблицы Из ТаблицаПараметров Цикл - - СтрокаСигнатуры = СтрокаСигнатуры - + СтрокаТаблицы.Ключ - + "=" + + СтрокаСигнатуры = СтрокаСигнатуры + + СтрокаТаблицы.Ключ + + " =" + СтрокаТаблицы.Значение + "&"; - + КонецЦикла; - + СтрокаСигнатуры = Лев(СтрокаСигнатуры, СтрДлина(СтрокаСигнатуры) - 1); - СтрокаСигнатуры = вРег(ВидЗапроса) - + "&" - + КодироватьСтроку(URL, СпособКодированияСтроки.КодировкаURL) + СтрокаСигнатуры = вРег(ВидЗапроса) + + "&" + + КодироватьСтроку(URL , СпособКодированияСтроки.КодировкаURL) + "&" + КодироватьСтроку(СтрокаСигнатуры, СпособКодированияСтроки.КодировкаURL); - + Подпись = КодироватьСтроку(Параметры["oauth_consumer_secret"], СпособКодированияСтроки.КодировкаURL) - + "&" + + "&" + КодироватьСтроку(Параметры["oauth_token_secret"], СпособКодированияСтроки.КодировкаURL); - + Сигнатура = OPI_Криптография.HMAC(ПолучитьДвоичныеДанныеИзСтроки(Подпись) , ПолучитьДвоичныеДанныеИзСтроки(СтрокаСигнатуры) , ХешФункция.SHA1 , 64); - + Сигнатура = КодироватьСтроку(Base64Строка(Сигнатура), СпособКодированияСтроки.КодировкаURL); - - Разделитель = ""","; - ЗаголовокАвторизации = ЗаголовокАвторизации + + Разделитель = ""","; + ЗаголовокАвторизации = ЗаголовокАвторизации + "OAuth " - + "oauth_consumer_key=""" + Параметры[OCK] + Разделитель - + "oauth_token=""" + Параметры[OTK] + Разделитель + + "oauth_consumer_key =""" + Параметры[OCK] + Разделитель + + "oauth_token =""" + Параметры[OTK] + Разделитель + "oauth_signature_method=""" + МетодХэширования + Разделитель - + "oauth_timestamp=""" + ТекущаяДатаUNIX + Разделитель - + "oauth_nonce=""" + ТекущаяДатаUNIX + Разделитель - + "oauth_version=""" + ВерсияАпи + Разделитель - + "oauth_signature=""" + Сигнатура; - + + "oauth_timestamp =""" + ТекущаяДатаUNIX + Разделитель + + "oauth_nonce =""" + ТекущаяДатаUNIX + Разделитель + + "oauth_version =""" + ВерсияАпи + Разделитель + + "oauth_signature =""" + Сигнатура; + СоответствиеЗаголовка = Новый Соответствие; СоответствиеЗаголовка.Вставить("authorization", ЗаголовокАвторизации); - + Возврат СоответствиеЗаголовка; - + КонецФункции Функция СоздатьЗаголовокАвторизацииV2(Знач Параметры) - + СоответствиеВозврата = Новый Соответствие; СоответствиеВозврата.Вставить("Authorization", "Bearer " + Параметры["access_token"]); - + Возврат СоответствиеВозврата; - + КонецФункции Функция ПолучитьСтатусОбработки(Знач Параметры, Знач Поля, Знач URL) ProcessingInfo = "processing_info"; - Авторизация = СоздатьЗаголовокАвторизацииV1(Параметры, Поля, "POST", URL); - - Ответ = OPI_Инструменты.Post(URL, Поля, Авторизация, Ложь); + Авторизация = СоздатьЗаголовокАвторизацииV1(Параметры, Поля, "POST", URL); + + Ответ = OPI_Инструменты.Post(URL, Поля, Авторизация, Ложь); Информация = Ответ[ProcessingInfo]; - + Если Не ЗначениеЗаполнено(Информация) Тогда Возврат Ответ; КонецЕсли; - + СтатусОбработки = Информация["state"]; - + Если Не ЗначениеЗаполнено(СтатусОбработки) Тогда Возврат Ответ; Иначе Возврат СтатусОбработки; - КонецЕсли; - + КонецЕсли; + КонецФункции #КонецОбласти diff --git a/src/ru/OInt/core/Modules/OPI_VK.os b/src/ru/OInt/core/Modules/OPI_VK.os index 221fa3e4d3..94c4aaf3e6 100644 --- a/src/ru/OInt/core/Modules/OPI_VK.os +++ b/src/ru/OInt/core/Modules/OPI_VK.os @@ -22,7 +22,7 @@ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. +// SOFTWARE. // https://github.com/Bayselonarrend/OpenIntegrations // Если в не знаете с чего начать, то стоит найти метод ПолучитьСтандартныеПараметры() @@ -51,37 +51,37 @@ // Создать ссылку получения токена // Получение ссылки для интерактивного получения токена (access_token), который необходим // для дальнейших действий -// +// // Параметры: // app_id - Строка,Число - app_id из настроек приложения - app -// +// // Возвращаемое значение: -// Строка - URL, по которому необходимо перейти в браузере +// Строка - URL, по которому необходимо перейти в браузере Функция СоздатьСсылкуПолученияТокена(Знач App_id) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(App_id); - + // access_token нужно будет забрать из параметра в строке адреса браузера Возврат "https://oauth.vk.com/authorize?client_id=" + App_id + "&scope=offline,wall,groups,photos,stats,stories,ads,market,video" + "&v=5.131&response_type=token&redirect_uri=https://api.vk.com/blank.html"; - + КонецФункции - + #КонецОбласти #Область РаботаСГруппой // Создать пост // Создает пост с картинками -// +// // Параметры: // Текст - Строка - Текст поста - text -// МассивКартинок - Массив из Строка,ДвоичныеДанные - Массив картинок - pictures +// МассивКартинок - Массив из Строка,ДвоичныеДанные - Массив картинок - pictures // Реклама - Булево - Признак ""Это реклама"" - ad // СсылкаПодЗаписью - Строка - Ссылка (URL) под записью - url // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция СоздатьПост(Знач Текст @@ -89,49 +89,49 @@ , Знач Реклама = Ложь , Знач СсылкаПодЗаписью = "" , Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивКартинок); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); - МассивВложений = Новый Массив; - + МассивВложений = Новый Массив; + Для Каждого КартинкаПоста Из МассивКартинок Цикл - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); ОтветСоответствие = ПолучитьСоответствиеКартинки(КартинкаПоста, Параметры_, "Пост"); - + OwnerId = ОтветСоответствие.Получить("owner_id"); ObjectId = ОтветСоответствие.Получить("id"); - + Если Не ЗначениеЗаполнено(OwnerId) Или Не ЗначениеЗаполнено(ObjectId) Тогда Возврат ОтветСоответствие; КонецЕсли; - + OwnerId = OPI_Инструменты.ЧислоВСтроку(OwnerId); ObjectId = OPI_Инструменты.ЧислоВСтроку(ObjectId); - - ФотоID = "photo" + OwnerId + "_" + ObjectId; + + ФотоID = "photo" + OwnerId + "_" + ObjectId; МассивВложений.Добавить(ФотоID); - + КонецЦикла; Ответ = СоздатьСоставнойПост(Текст, МассивВложений, Реклама, СсылкаПодЗаписью, Параметры); - + Возврат Ответ; - + КонецФункции // Создать составной пост // Создает пост на основе массива идетификаторов объектов (картинок, видео и др.) -// +// // Параметры: // Текст - Строка - Текст поста - text -// Объекты - Массив из Строка - Массив идентификаторов вида photo123_123 - objects +// Объекты - Массив из Строка - Массив идентификаторов вида photo123_123 - objects // Реклама - Булево - Признак ""Это реклама"" - ad // СсылкаПодЗаписью - Строка - Ссылка (URL) под записью - url // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция СоздатьСоставнойПост(Знач Текст @@ -139,24 +139,24 @@ , Знач Реклама = Ложь , Знач СсылкаПодЗаписью = "" , Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Текст); - OPI_ПреобразованиеТипов.ПолучитьСтроку(СсылкаПодЗаписью); + OPI_ПреобразованиеТипов.ПолучитьСтроку(СсылкаПодЗаписью); OPI_ПреобразованиеТипов.ПолучитьБулево(Реклама); - + Параметры = ПолучитьСтандартныеПараметры(Параметры); - СтрокаВложений = СтрСоединить(Объекты, ","); + СтрокаВложений = СтрСоединить(Объекты, ","); СтрокаВложений = СтрокаВложений + СсылкаПодЗаписью; - + Параметры.Вставить("message" , Текст); Параметры.Вставить("attachments" , СтрокаВложений); Параметры.Вставить("mark_as_ads" , ?(Реклама, 1, 0)); Параметры.Вставить("close_comments" , ?(Реклама, 1, 0)); Ответ = OPI_Инструменты.Get("api.vk.com/method/wall.post", Параметры); - + Возврат Ответ; - + КонецФункции // Удалить пост @@ -165,20 +165,20 @@ // Параметры: // IDПоста - Строка,Число - ID поста - post // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция УдалитьПост(Знач IDПоста, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDПоста); - - Параметры_ = ПолучитьСтандартныеПараметры(Параметры); + + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("post_id", IDПоста); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/wall.delete", Параметры_); - + Возврат Ответ; - + КонецФункции // Создать опрос @@ -189,72 +189,72 @@ // МассивОтветов - Массив из Строка - Массив вариантов ответа - options // Картинка - Строка,ДвоичныеДанные - Картинка опроса - picture // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция СоздатьОпрос(Знач Вопрос, Знач МассивОтветов, Знач Картинка = "", Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Вопрос); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивОтветов); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Response_ = "response"; Если ЗначениеЗаполнено(Картинка) Тогда - + Ответ = ЗагрузитьФотоНаСервер(Картинка, Параметры_, "Опрос"); - + Фото = Ответ.Получить(Response_); - + Если ЗначениеЗаполнено(Фото) Тогда - + IDФото = Фото["id"]; - + Если Не ЗначениеЗаполнено(IDФото) Тогда Возврат Ответ; КонецЕсли; - + Иначе Возврат Ответ; КонецЕсли; - + КонецЕсли; - + Параметры_.Вставить("is_anonymous", 1); Параметры_.Вставить("is_multiple" , 0); - + Ответы = СтрСоединить(МассивОтветов, ""","""); - Ответы = "[""" + Ответы + """]"; - + Ответы = "[""" + Ответы + """]"; + Параметры_.Вставить("add_answers", Ответы); Параметры_.Вставить("photo_id" , OPI_Инструменты.ЧислоВСтроку(IDФото)); Параметры_.Вставить("question" , Вопрос); - + Опрос = OPI_Инструменты.Get("api.vk.com/method/polls.create", Параметры_); ОпросСоответствие = Опрос.Получить(Response_); - + Если Не ЗначениеЗаполнено(ОпросСоответствие) Тогда Возврат Опрос; КонецЕсли; - + OwnerId = ОпросСоответствие.Получить("owner_id"); ObjectId = ОпросСоответствие.Получить("id"); - + Если Не ЗначениеЗаполнено(OwnerId) Или Не ЗначениеЗаполнено(ObjectId) Тогда Возврат Опрос; КонецЕсли; - + ОпросID = "poll" + OPI_Инструменты.ЧислоВСтроку(OwnerId) - + "_" + + "_" + OPI_Инструменты.ЧислоВСтроку(ObjectId); - + Параметры_.Вставить("attachments", ОпросID); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/wall.post", Параметры_); - + Возврат Ответ; - + КонецФункции // Создать альбом @@ -264,24 +264,24 @@ // Наименование - Строка - Наименование альбома - title // Описание - Строка - Описание альбома - description // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция СоздатьАльбом(Знач Наименование, Знач Описание = "", Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Наименование); OPI_ПреобразованиеТипов.ПолучитьСтроку(Описание); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); - + Параметры_.Вставить("title" , Наименование); Параметры_.Вставить("description" , Описание); Параметры_.Вставить("upload_by_admins_only", 1); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/photos.createAlbum", Параметры_); - + Возврат Ответ; - + КонецФункции // Удалить альбом @@ -290,20 +290,20 @@ // Параметры: // IDАльбома - Строка,Число - ID альбома - album // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция УдалитьАльбом(Знач IDАльбома, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDАльбома); - - Параметры_ = ПолучитьСтандартныеПараметры(Параметры); + + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("album_id", OPI_Инструменты.ЧислоВСтроку(IDАльбома)); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/photos.deleteAlbum", Параметры_); - + Возврат Ответ; - + КонецФункции // Создать историю @@ -313,187 +313,187 @@ // Картинка - Строка,ДвоичныеДанные - Фон истории - picture // URL - Строка - URL для кнопки под историей - url // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция СоздатьИсторию(Знач Картинка, Знач URL = "", Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(URL); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("link_text" , "more"); Параметры_.Вставить("link_url" , URL); Параметры_.Вставить("add_to_news", "1"); - - Ответ = ЗагрузитьФотоНаСервер(Картинка, Параметры_, "История"); + + Ответ = ЗагрузитьФотоНаСервер(Картинка, Параметры_, "История"); Возврат Ответ; - + КонецФункции // Сохранить картинку в альбом // Сохраняет картинку в альбом сообщества // // Параметры: -// IDАльбома - Строка,Число - ID альбома - album +// IDАльбома - Строка,Число - ID альбома - album // Картинка - ДвоичныеДанные,Строка - Файл картинки - picture // Описание - Строка - Описание картинки - description // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция СохранитьКартинкуВАльбом(Знач IDАльбома, Знач Картинка, Знач Описание = "", Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDАльбома); OPI_ПреобразованиеТипов.ПолучитьСтроку(Описание); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); - + Параметры_.Вставить("album_id", IDАльбома); Параметры_.Вставить("caption" , Описание); - + Возврат ЗагрузитьФотоНаСервер(Картинка, Параметры_, "Альбом"); - + КонецФункции // Удалить картинку // Удалить картинку из альбома // // Параметры: -// IDКартинки - Строка,Число - ID картинки - pictureid +// IDКартинки - Строка,Число - ID картинки - pictureid // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция УдалитьКартинку(Знач IDКартинки, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDКартинки); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("photo_id", IDКартинки); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/photos.delete", Параметры_); - + Возврат Ответ; - + КонецФункции // Загрузить видео на сервер // Загружает видео в группу с возможностью его дальнейшего использования -// +// // Параметры: // Видео - Строка, ДвоичныеДанные - Файл видео - file // Наименование - Строка - Наименование видео - title // Описание - Строка - Описание видео - description // Альбом - Строка - ID альбома, если необходимо - album // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ЗагрузитьВидеоНаСервер(Знач Видео , Знач Наименование , Знач Описание = "" , Знач Альбом = "" , Знач Параметры = "") Экспорт - + Строка_ = "Строка"; Параметры = ПолучитьСтандартныеПараметры(Параметры); - + OPI_Инструменты.ДобавитьПоле("name" , Наименование, Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("description", Описание , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("album_id" , Альбом , Строка_, Параметры); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/video.save", Параметры); - + Результат = Ответ["response"]; - + Если Не ЗначениеЗаполнено(Результат) Тогда Возврат Ответ; КонецЕсли; - + URL = Результат["upload_url"]; - + Если Не ЗначениеЗаполнено(URL) Тогда Возврат Ответ; КонецЕсли; - + СоответствиеФайлов = Новый Соответствие; OPI_Инструменты.ДобавитьПоле("video_file.mp4", Видео, "ДвоичныеДанные", СоответствиеФайлов); - + РазмерДанных = СоответствиеФайлов["video_file.mp4"].Размер(); РазмерДанных = OPI_Инструменты.ЧислоВСтроку(РазмерДанных); - + Ответ = OPI_Инструменты.PostMultipart(URL, , СоответствиеФайлов, "video/mp4"); - + Возврат Ответ; - + КонецФункции // Загрузить фото на сервер // Загружает фото на сервер для его дальнейшего использования -// +// // Параметры: // Картинка - Строка, ДвоичныеДанные - Файл картинки - file // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json // Вид - Строка - Вид загрузки (Пост, Товар, История, Опрос, Прочее) - type -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ЗагрузитьФотоНаСервер(Знач Картинка, Знач Параметры = "", Знач Вид = "Пост") Экспорт - + Параметры = ПолучитьСтандартныеПараметры(Параметры); Метод = ОпределитьМетодЗагрузкиИзображений(Вид); Файлы = Новый Соответствие; - + Response_ = "response"; URL = "api.vk.com/method/"; Загрузка = URL + Метод["Загрузка"]; Сохранение = URL + Метод["Сохранение"]; - - Если ТипЗнч(Картинка) = Тип("Строка") Тогда + + Если ТипЗнч(Картинка) = Тип("Строка") Тогда КлючКартинка = СтрЗаменить(Картинка, ".", "___"); OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Картинка); Иначе КлючКартинка = "image___jpeg"; КонецЕсли; - + Файлы.Вставить(КлючКартинка, Картинка); - + Для Н = 1 По 5 Цикл - - Ответ = OPI_Инструменты.Get(Загрузка, Параметры); + + Ответ = OPI_Инструменты.Get(Загрузка, Параметры); Результат = Ответ[Response_]; - + Если ЗначениеЗаполнено(Результат) Тогда - + URL = Результат["upload_url"]; - + Если Не ЗначениеЗаполнено(URL) Тогда Возврат Ответ; КонецЕсли; - + Иначе Возврат Ответ; КонецЕсли; - + Параметры.Вставить("upload_url", URL); Ответ = OPI_Инструменты.PostMultipart(URL, Параметры, Файлы); - + Если ТипЗнч(Ответ) = Тип("Соответствие") Тогда Прервать; КонецЕсли; - + КонецЦикла; - + Если ТипЗнч(Ответ) <> Тип("Соответствие") Тогда Возврат ПолучитьСтрокуИзДвоичныхДанных(Ответ); КонецЕсли; ЗаполнитьПараметрыЗагрузкиФото(Метод, Ответ, Параметры); - + Ответ = OPI_Инструменты.Get(Сохранение, Параметры); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -507,22 +507,22 @@ // Наименование - Строка - Наименование обсуждения - title // ТекстПервогоСообщения - Строка - Текст первого сообщения - text // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция СоздатьОбсуждение(Знач Наименование, Знач ТекстПервогоСообщения, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Наименование); OPI_ПреобразованиеТипов.ПолучитьСтроку(ТекстПервогоСообщения); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("title", Наименование); Параметры_.Вставить("text" , ТекстПервогоСообщения); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/board.addTopic", Параметры_); - + Возврат Ответ; - + КонецФункции // Закрыть обсуждение @@ -532,20 +532,20 @@ // IDОбсуждения - Строка,Число - ID обсуждения - topic // УдалитьПолностью - Булево - Удалить полностью (Истина) или закрыть - remove // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ЗакрытьОбсуждение(Знач IDОбсуждения, Знач УдалитьПолностью = Ложь, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDОбсуждения); OPI_ПреобразованиеТипов.ПолучитьБулево(УдалитьПолностью); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("topic_id", IDОбсуждения); - - Метод = ?(УдалитьПолностью, "deleteTopic", "closeTopic"); + + Метод = ?(УдалитьПолностью, "deleteTopic", "closeTopic"); Ответ = OPI_Инструменты.Get("api.vk.com/method/board." + Метод, Параметры_); - + Возврат Ответ; КонецФункции @@ -556,18 +556,18 @@ // Параметры: // IDОбсуждения - Строка,Число - ID обсуждения - topic // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ОткрытьОбсуждение(Знач IDОбсуждения, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDОбсуждения); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("topic_id", IDОбсуждения); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/board.openTopic", Параметры_); - + Возврат Ответ; КонецФункции @@ -579,20 +579,20 @@ // IDОбсуждения - Строка,Число - ID обсуждения - topic // Текст - Строка - Текст сообщения - text // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция НаписатьВОбсуждение(Знач IDОбсуждения, Знач Текст, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDОбсуждения); OPI_ПреобразованиеТипов.ПолучитьСтроку(Текст); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("topic_id", IDОбсуждения); Параметры_.Вставить("message" , Текст); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/board.createComment", Параметры_); - + Возврат Ответ; КонецФункции @@ -608,26 +608,26 @@ // IDПоста - Строка,Число - ID поста - post // IDСтены - Строка,Число - ID стены расположения поста - wall // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ПоставитьЛайк(Знач IDПоста, Знач IDСтены = "", Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDПоста); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDСтены); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); IDСтены = ?(ЗначениеЗаполнено(IDСтены), IDСтены, Параметры_["owner_id"]); ОбъектВК = "wall" + IDСтены + "_" + OPI_Инструменты.ЧислоВСтроку(IDПоста); - + Параметры_.Вставить("type" , "post"); Параметры_.Вставить("object" , ОбъектВК); Параметры_.Вставить("item_id" , OPI_Инструменты.ЧислоВСтроку(IDПоста)); Параметры_.Вставить("owner_id" , OPI_Инструменты.ЧислоВСтроку(IDСтены)); Параметры_.Вставить("from_group" , 0); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/likes.add", Параметры_); - + Возврат Ответ; КонецФункции @@ -641,7 +641,7 @@ // ЦелеваяСтена - Строка,Число - ID целевой стены или группы - to // Рекламный - Булево - Признак рекламного поста - ad // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция СделатьРепост(Знач IDПоста @@ -649,25 +649,25 @@ , Знач ЦелеваяСтена = "" , Знач Рекламный = Ложь , Знач Параметры = "") Экспорт - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); GroupId = Параметры_["group_id"]; - + OPI_ПреобразованиеТипов.ПолучитьСтроку(GroupId); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDПоста); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDСтены); OPI_ПреобразованиеТипов.ПолучитьСтроку(ЦелеваяСтена); OPI_ПреобразованиеТипов.ПолучитьБулево(Рекламный); - - Источник = ?(ЗначениеЗаполнено(IDСтены), IDСтены, GroupId); + + Источник = ?(ЗначениеЗаполнено(IDСтены), IDСтены, GroupId); Приемник = ?(ЗначениеЗаполнено(ЦелеваяСтена), ЦелеваяСтена, GroupId); Параметры_.Вставить("object" , "wall" + Источник + "_" + OPI_Инструменты.ЧислоВСтроку(IDПоста)); Параметры_.Вставить("group_id" , СтрЗаменить(Приемник, "-", "")); - Параметры_.Вставить("mark_as_ads" , ?(Рекламный, 1, 0)); - + Параметры_.Вставить("mark_as_ads" , ?(Рекламный , 1 , 0)); + Ответ = OPI_Инструменты.Get("api.vk.com/method/wall.repost", Параметры_); - + Возврат Ответ; КонецФункции @@ -681,7 +681,7 @@ // Communitytoken - Строка - Токен бота чата сообщества, котрый можно получить в настройках - ct // Клавиатура - Строка - JSON клавиатуры. См.СформироватьКлавиатуру - keyboard // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция НаписатьСообщение(Знач Текст @@ -689,27 +689,27 @@ , Знач Communitytoken , Знач Клавиатура = "" , Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Текст); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDПользователя); OPI_ПреобразованиеТипов.ПолучитьСтроку(Communitytoken); OPI_ПреобразованиеТипов.ПолучитьСтроку(Клавиатура); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("access_token", Communitytoken); - + Параметры_.Вставить("user_id" , IDПользователя); Параметры_.Вставить("peer_id" , IDПользователя); - Параметры_.Вставить("parse_mode" , "Markdown"); + Параметры_.Вставить("parse_mode" , "Markdown"); Параметры_.Вставить("random_id" , 0); Параметры_.Вставить("message" , Текст); - + Если ЗначениеЗаполнено(Клавиатура) Тогда Параметры_.Вставить("keyboard", Клавиатура); КонецЕсли; - + Ответ = OPI_Инструменты.Get("api.vk.com/method/messages.send", Параметры_); - + Возврат Ответ; КонецФункции @@ -722,28 +722,28 @@ // IDСтены - Строка,Число - ID стены расположения поста - wall // Текст - Строка - Текст комментария - text // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция НаписатьКомментарий(Знач IDПоста, Знач IDСтены, Знач Текст, Знач Параметры = "") Экспорт Параметры_ = ПолучитьСтандартныеПараметры(Параметры); GroupId = Параметры_["group_id"]; - + OPI_ПреобразованиеТипов.ПолучитьСтроку(GroupId); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDПоста); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDСтены); OPI_ПреобразованиеТипов.ПолучитьСтроку(Текст); - - Параметры_.Вставить("owner_id" , IDСтены); + + Параметры_.Вставить("owner_id" , IDСтены); Параметры_.Вставить("from_group" , GroupId); Параметры_.Вставить("post_id" , IDПоста); Параметры_.Вставить("message" , Текст); - + Параметры_.Удалить("group_id"); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/wall.createComment", Параметры_); - + Возврат Ответ; КонецФункции @@ -754,35 +754,35 @@ // Параметры: // URL - Строка - URL для сокращения - url // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: -// Строка - Сокращенный URL +// Строка - Сокращенный URL Функция СократитьСсылку(Знач URL, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(URL); - + Response_ = "response"; Параметры_ = Новый Структура; - Параметры_ = ПолучитьСтандартныеПараметры(Параметры); + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("url", URL); - + Ответ = OPI_Инструменты.Get("https://api.vk.com/method/utils.getShortLink", Параметры_); Результат = Ответ[Response_]; - + Если ЗначениеЗаполнено(Результат) Тогда - + URL = Результат["short_url"]; - + Если ЗначениеЗаполнено(URL) Тогда Возврат URL; Иначе Возврат Ответ; КонецЕсли; - + Иначе Возврат Ответ; КонецЕсли; - + КонецФункции #КонецОбласти @@ -796,27 +796,27 @@ // ДатаНачала - Дата - Дата начала периода - datefrom // ДатаОкончания - Дата - Дата окончания периода - dateto // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ПолучитьСтатистику(Знач ДатаНачала, Знач ДатаОкончания, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьДату(ДатаНачала); OPI_ПреобразованиеТипов.ПолучитьДату(ДатаОкончания); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); - + ДатаНачала = OPI_Инструменты.UNIXTime(ДатаНачала); ДатаОкончания = OPI_Инструменты.UNIXTime(ДатаОкончания); - + Параметры_.Вставить("timestamp_from", ДатаНачала); Параметры_.Вставить("timestamp_to" , ДатаОкончания); Параметры_.Вставить("stats_groups" , "visitors, reach, activity"); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/stats.get", Параметры_); - + Возврат Ответ; - + КонецФункции // Получить статистику по постам @@ -825,47 +825,47 @@ // Параметры: // МассивИДПостов - Массив из Строка,Число - Массив ID постов - posts // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Массив из Произвольный - Массив данных статистики по постам Функция ПолучитьСтатистикуПостов(Знач МассивИДПостов, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивИДПостов); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); МассивОтветов = Новый Массив; МассивНабора = Новый Массив; МаксимумПостов = 30; Response_ = "response"; - + Для Каждого Пост Из МассивИДПостов Цикл - + МассивНабора.Добавить(OPI_Инструменты.ЧислоВСтроку(Пост)); - + Если МассивНабора.Количество() = МаксимумПостов Тогда - + СтрокаНомеров = СтрСоединить(МассивНабора, ","); Параметры_.Вставить("post_ids", СтрокаНомеров); - + Статистика = OPI_Инструменты.Get("api.vk.com/method/stats.getPostReach", Параметры_); МассивСтатистики = Статистика[Response_]; - + Для Каждого ЭлементСтатистики Из МассивСтатистики Цикл МассивОтветов.Добавить(ЭлементСтатистики); КонецЦикла; - + МассивНабора = Новый Массив; - + КонецЕсли; - + КонецЦикла; - + СтрокаНомеров = СтрСоединить(МассивНабора, ","); Параметры_.Вставить("post_ids", СтрокаНомеров); - + Статистика = OPI_Инструменты.Get("api.vk.com/method/stats.getPostReach", Параметры_); МассивСтатистики = Статистика[Response_]; - + Если ТипЗнч(МассивСтатистики) = Тип("Массив") Тогда Для Каждого ЭлементСтатистики Из МассивСтатистики Цикл МассивОтветов.Добавить(ЭлементСтатистики); @@ -873,9 +873,9 @@ КонецЕсли; Возврат МассивОтветов; - + КонецФункции - + #КонецОбласти #Область РаботаСРекламнымКабинетом @@ -887,24 +887,24 @@ // IDКабинета - Строка,Число - ID рекламного кабинета - cabinet // Наименование - Строка - Наименование кампании - title // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция СоздатьРекламнуюКампанию(Знач IDКабинета, Знач Наименование, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDКабинета); OPI_ПреобразованиеТипов.ПолучитьСтроку(Наименование); - + ТекущаяДата = OPI_Инструменты.ПолучитьТекущуюДату(); КонечнаяДата = ДобавитьМесяц(ТекущаяДата, 24); - - Параметры_ = ПолучитьСтандартныеПараметры(Параметры); + + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("account_id", IDКабинета); - + МассивСтруктур = Новый Массив; ДатаСтарт = OPI_Инструменты.UNIXTime(ТекущаяДата); ДатаСтоп = OPI_Инструменты.UNIXTime(КонечнаяДата); - + СтруктураКампании = Новый Структура; СтруктураКампании.Вставить("type" , "promoted_posts"); СтруктураКампании.Вставить("name" , Наименование); @@ -913,17 +913,17 @@ СтруктураКампании.Вставить("start_time" , ДатаСтарт); СтруктураКампании.Вставить("stop_time" , ДатаСтоп); СтруктураКампании.Вставить("status" , 1); - + МассивСтруктур.Добавить(СтруктураКампании); - + JSONДата = OPI_Инструменты.JSONСтрокой(МассивСтруктур); - + Параметры_.Вставить("data", JSONДата); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/ads.createCampaigns", Параметры_); - + Возврат Ответ; - + КонецФункции // Создать рекламное объявление @@ -936,7 +936,7 @@ // IDПоста - Строка,Число - ID поста, используемого в качетсве рекламы - post // IDКабинета - Строка,Число - ID рекламного кабинета - cabinet // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция СоздатьРекламноеОбъявление(Знач НомерКампании @@ -945,20 +945,20 @@ , Знач IDПоста , Знач IDКабинета , Знач Параметры = "") Экспорт - - Параметры_ = ПолучитьСтандартныеПараметры(Параметры); + + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); GroupId = Параметры_["group_id"]; - + OPI_ПреобразованиеТипов.ПолучитьСтроку(GroupId); OPI_ПреобразованиеТипов.ПолучитьСтроку(НомерКампании); OPI_ПреобразованиеТипов.ПолучитьСтроку(ДневнойЛимит); OPI_ПреобразованиеТипов.ПолучитьСтроку(НомерКатегории); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDПоста); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDКабинета); - + Линк = "https://vk.com/wall-" + GroupId + "_" + IDПоста; - - МассивСтруктур = Новый Массив; + + МассивСтруктур = Новый Массив; СтруктураКампании = Новый Структура; СтруктураКампании.Вставить("campaign_id" , НомерКампании); СтруктураКампании.Вставить("ad_format" , 9); @@ -976,18 +976,18 @@ СтруктураКампании.Вставить("status" , 1); СтруктураКампании.Вставить("name" , "Объявление"); СтруктураКампании.Вставить("link_url" , Линк); - + МассивСтруктур.Добавить(СтруктураКампании); - + OPI_ПреобразованиеТипов.ПолучитьСтроку(МассивСтруктур, Истина); - + Параметры_.Вставить("data" , МассивСтруктур); Параметры_.Вставить("account_id" , IDКабинета); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/ads.createAds", Параметры_); - + Возврат Ответ; - + КонецФункции // Приостановить рекламное объявление @@ -995,36 +995,36 @@ // // Параметры: // IDКабинета - Строка,Число - ID рекламного кабинета - cabinet -// IDОбъявления - Строка,Число - ID объявления - adv +// IDОбъявления - Строка,Число - ID объявления - adv // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ПриостановитьРекламноеОбъявление(Знач IDКабинета, Знач IDОбъявления, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDКабинета); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDОбъявления); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("account_id", IDКабинета); - - МассивСтруктур = Новый Массив; + + МассивСтруктур = Новый Массив; СтруктураКампании = Новый Структура; - + СтруктураКампании.Вставить("ad_id" , IDОбъявления); СтруктураКампании.Вставить("status" , 0); - + МассивСтруктур.Добавить(СтруктураКампании); - + OPI_ПреобразованиеТипов.ПолучитьСтроку(МассивСтруктур, Истина); - + Параметры_.Вставить("data", МассивСтруктур); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/ads.updateAds", Параметры_); - + Возврат Ответ; - + КонецФункции // Получить список рекламных категорий @@ -1032,14 +1032,14 @@ // // Параметры: // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ПолучитьСписокРекламныхКатегорий(Знач Параметры = "") Экспорт - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Ответ = OPI_Инструменты.Get("api.vk.com/method/ads.getCategories", Параметры_); - + Возврат Ответ; КонецФункции @@ -1053,52 +1053,52 @@ // // Параметры: // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из Строка - Ключ - ID, Значение - Имя Функция ПолучитьСписокКатегорийТоваров(Знач Параметры = "") Экспорт - + Response_ = "response"; Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Ответ = OPI_Инструменты.Get("api.vk.com/method/market.getCategories", Параметры_); Результат = Ответ[Response_]; - + Если ЗначениеЗаполнено(Результат) Тогда - + Количество = Результат["count"]; - + Если Не ЗначениеЗаполнено(Количество) Тогда Возврат Ответ; КонецЕсли; - + Иначе Возврат Ответ; КонецЕсли; - + Параметры_.Вставить("count", Количество); - Ответ = OPI_Инструменты.Get("api.vk.com/method/market.getCategories", Параметры_); - Результат = Ответ[Response_]; - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.getCategories", Параметры_); + Результат = Ответ[Response_]; + Если ЗначениеЗаполнено(Результат) Тогда - + Категории = Результат["items"]; - + Если Не ЗначениеЗаполнено(Категории) Тогда Возврат Ответ; КонецЕсли; - + Иначе Возврат Ответ; КонецЕсли; - + СоответствиеКатегорий = Новый Соответствие; - - Для Каждого Категория Из Категории Цикл + + Для Каждого Категория Из Категории Цикл СоответствиеКатегорий.Вставить(Категория["id"], Категория["name"]); КонецЦикла; - + Возврат СоответствиеКатегорий; - + КонецФункции // Получить список товаров @@ -1107,60 +1107,60 @@ // Параметры: // Подборка - Строка,Число - ID подборки, если нужен отбор - sel // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - Массив соответствий товаров Функция ПолучитьСписокТоваров(Знач Подборка = "", Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Подборка); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("count" , 200); Параметры_.Вставить("extended" , 1); Параметры_.Вставить("with_disabled", 1); - + Если ЗначениеЗаполнено(Подборка) Тогда - Параметры_.Вставить("album_id", Подборка); + Параметры_.Вставить("album_id", Подборка); КонецЕсли; - + МассивТоваров = Новый Массив; ПолучитьСписокТоваровРекурсивно(МассивТоваров, Параметры_); - + Возврат МассивТоваров; - + КонецФункции // Получить товары по ID // Получает информацию о товарах по массиву ID // // Параметры: -// Товары - Строка, Массив Из Строка - Массив ID товаров - items +// Товары - Строка, Массив Из Строка - Массив ID товаров - items // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ПолучитьТоварыПоИД(Знач Товары, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Товары); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); СтрокаТоваров = ""; Owner = "owner_id"; - - Для Каждого Товар Из Товары Цикл + + Для Каждого Товар Из Товары Цикл ТекущийТовар = Параметры_[Owner] + "_" + Товар; ТекущийТовар = OPI_Инструменты.ЧислоВСтроку(ТекущийТовар); СтрокаТоваров = СтрокаТоваров + ТекущийТовар + ","; КонецЦикла; - + СтрокаТоваров = Лев(СтрокаТоваров, СтрДлина(СтрокаТоваров) - 1); Параметры_.Вставить("item_ids", СтрокаТоваров); Параметры_.Вставить("extended", 1); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.getById", Параметры_); - + Возврат Ответ; - + КонецФункции // Добавить товар @@ -1170,13 +1170,13 @@ // ОписаниеТовара - Соответствие Из КлючИЗначение - См.ПолучитьОписаниеТовара - product - JSON описание товара или путь // Подборка - Строка - ID подборка для помещения товара, если необходимо - sel // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK -Функция ДобавитьТовар(Знач ОписаниеТовара, Знач Подборка = "", Знач Параметры = "") Экспорт - - Возврат УправлениеТоваром(ОписаниеТовара, , Подборка, Параметры); - +Функция ДобавитьТовар(Знач ОписаниеТовара, Знач Подборка = "", Знач Параметры = "") Экспорт + + Возврат УправлениеТоваром(ОписаниеТовара, , Подборка, Параметры); + КонецФункции // Изменить товар @@ -1185,15 +1185,15 @@ // Параметры: // Товар - Число,Строка - Идентификатор изменяемого товара - item // ОписаниеТовара - Соответствие Из КлючИЗначение - См.ПолучитьОписаниеТовара - product - JSON описание товара или путь -// Подборка - Строка - Идентификатор новой подборки, если необходимо - sel +// Подборка - Строка - Идентификатор новой подборки, если необходимо - sel // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ИзменитьТовар(Знач Товар, Знач ОписаниеТовара, Знач Подборка = "", Знач Параметры = "") Экспорт - - Возврат УправлениеТоваром(ОписаниеТовара, Товар, Подборка, Параметры); - + + Возврат УправлениеТоваром(ОписаниеТовара, Товар, Подборка, Параметры); + КонецФункции // Удалить товар @@ -1202,20 +1202,20 @@ // Параметры: // Товар - Строка,Число - ID товара - item // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция УдалитьТовар(Знач Товар, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Товар); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("item_id", Товар); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.delete", Параметры_); - + Возврат Ответ; - + КонецФункции // Сгруппировать товары @@ -1225,37 +1225,37 @@ // МассивТоваров - Массив Из Строка - Массив ID товаров - items // СуществующаяГруппа - Строка - ID существующей группы, если необходимо - sellgroup // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция СгруппироватьТовары(Знач МассивТоваров, Знач СуществующаяГруппа = "", Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(СуществующаяГруппа); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивТоваров); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); МассивТоваров_ = Новый Массив; - + Для Каждого Товар Из МассивТоваров Цикл МассивТоваров_.Добавить(OPI_Инструменты.ЧислоВСтроку(Товар)); КонецЦикла; - + Товары = СтрСоединить(МассивТоваров_, ","); - + Параметры_.Вставить("item_ids", Товары); - + Если ЗначениеЗаполнено(СуществующаяГруппа) Тогда Параметры_.Вставить("item_group_id", СуществующаяГруппа); КонецЕсли; - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.groupItems", Параметры_); - + Возврат Ответ; КонецФункции // Получить описание товара. !NOCLI -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - Пустое описание товара: // *Имя - Строка - Имя товара @@ -1275,27 +1275,27 @@ // *SKU - Строка - SKU // *ДоступныйОстаток - Число - Остаток. -1 - не ограничено Функция ПолучитьОписаниеТовара() Экспорт - + Товар = Новый Соответствие(); Товар.Вставить("Имя" , "Новый товар"); // Имя товара Товар.Вставить("Описание" , "Описание товара"); // Описание товара Товар.Вставить("Категория" , "20173"); // См ПолучитьСписокКатегорийТоваров() Товар.Вставить("Цена" , 1); // Цена. - Товар.Вставить("СтараяЦена" , Неопределено); // Для отражения изменения цены + Товар.Вставить("СтараяЦена" , Неопределено); // Для отражения изменения цены Товар.Вставить("ОсновноеФото" , Неопределено); // ДД или путь к осн. фото Товар.Вставить("URL" , Неопределено); // Ссылка на страницу магазина Товар.Вставить("ДополнительныеФото" , Новый Массив); // Массив путей или ДД для доп. фото Товар.Вставить("ЗначенияСвойств" , Новый Массив); // Значения свойств (варианты). Максимум 2 - Товар.Вставить("ГлавныйВГруппе" , Ложь); // Сделать главным в своей группе + Товар.Вставить("ГлавныйВГруппе" , Ложь); // Сделать главным в своей группе Товар.Вставить("Ширина" , Неопределено); // В миллиметрах Товар.Вставить("Высота" , Неопределено); // В миллиметрах Товар.Вставить("Глубина" , Неопределено); // В миллиметрах Товар.Вставить("Вес" , Неопределено); // В граммах Товар.Вставить("SKU" , Неопределено); // Артикул Товар.Вставить("ДоступныйОстаток" , 1); - + Возврат Товар; - + КонецФункции #КонецОбласти @@ -1307,19 +1307,19 @@ // // Параметры: // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - Массив соответствий подборок Функция ПолучитьСписокПодборок(Знач Параметры = "") Экспорт - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("count", 100); - + МассивАльбомов = Новый Массив; ПолучитьСписокАльбомовРекурсивно(МассивАльбомов, Параметры_); - + Возврат МассивАльбомов; - + КонецФункции // Получить подборки по ID @@ -1328,29 +1328,29 @@ // Параметры: // Подборки - Строка, Массив Из Строка - ID подборок - sels // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ПолучитьПодборкиПоИД(Знач Подборки, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Подборки); - - Параметры_ = ПолучитьСтандартныеПараметры(Параметры); + + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Подборки_ = Новый Массив; СтрокаПодборок = ""; - + Для Каждого Подборка Из Подборки Цикл - Подборки_.Добавить(OPI_Инструменты.ЧислоВСтроку(Подборка)); - КонецЦикла; - + Подборки_.Добавить(OPI_Инструменты.ЧислоВСтроку(Подборка)); + КонецЦикла; + СтрокаПодборок = СтрСоединить(Подборки_, ","); - + Параметры_.Вставить("album_ids", СтрокаПодборок); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.getAlbumById", Параметры_); - + Возврат Ответ; - + КонецФункции // Создать подборку товаров @@ -1362,7 +1362,7 @@ // Основная - Булево - Основная - main // Скрытая - Булево - Скрытая - hidden // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция СоздатьПодборкуТоваров(Знач Название @@ -1370,9 +1370,9 @@ , Знач Основная = Ложь , Знач Скрытая = Ложь , Знач Параметры = "") Экспорт - + Возврат УправлениеПодборкой(Название, Картинка, , Основная, Скрытая, Параметры); - + КонецФункции // Изменить подборку товаров @@ -1385,7 +1385,7 @@ // Основная - Булево - Основная - main // Скрытая - Булево - Скрытая - hidden // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ИзменитьПодборкуТоваров(Знач Название @@ -1394,9 +1394,9 @@ , Знач Основная = Ложь , Знач Скрытая = Ложь , Знач Параметры = "") Экспорт - + Возврат УправлениеПодборкой(Название, Картинка, Подборка, Основная, Скрытая, Параметры); - + КонецФункции // Добавить товар в подборку @@ -1406,56 +1406,56 @@ // МассивТоваров - Массив из Строка, Число - Массив товаров или товар - items // Подборка - Строка - ID подборки - sel // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ДобавитьТоварВПодборку(Знач МассивТоваров, Знач Подборка, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивТоваров); OPI_ПреобразованиеТипов.ПолучитьСтроку(Подборка); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); МассивТоваров_ = Новый Массив; - + Для Каждого Товар Из МассивТоваров Цикл - МассивТоваров_.Добавить(OPI_Инструменты.ЧислоВСтроку(Товар)); - КонецЦикла; - + МассивТоваров_.Добавить(OPI_Инструменты.ЧислоВСтроку(Товар)); + КонецЦикла; + СписокТоваров = СтрСоединить(МассивТоваров_, ","); - + Параметры_.Вставить("item_ids" , СписокТоваров); Параметры_.Вставить("album_ids", Подборка); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.addToAlbum", Параметры_); - + Возврат Ответ; - + КонецФункции // Удалить товар из подборки // Удаляет ранее добавленный товар из подборки -// +// // Параметры: // Товар - Строка - ID товара - item // Подборка - Строка - ID подборки - sel // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция УдалитьТоварИзПодборки(Знач Товар, Знач Подборка, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Товар); OPI_ПреобразованиеТипов.ПолучитьСтроку(Подборка); Параметры_ = ПолучитьСтандартныеПараметры(Параметры); - + Параметры_.Вставить("item_id" , Товар); Параметры_.Вставить("album_ids", Подборка); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.removeFromAlbum", Параметры_); - + Возврат Ответ; - + КонецФункции // Удалить подборку @@ -1464,20 +1464,20 @@ // Параметры: // Подборка - Строка - ID подборки - sel // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция УдалитьПодборку(Знач Подборка, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Подборка); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("album_id", Подборка); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.deleteAlbum", Параметры_); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -1486,167 +1486,167 @@ // Получить список свойств // Получает список свойств товаров группы -// +// // Параметры: // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ПолучитьСписокСвойств(Знач Параметры = "") Экспорт - + Response_ = "response"; Параметры_ = ПолучитьСтандартныеПараметры(Параметры); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.getProperties", Параметры_); Свойства = Ответ[Response_]["items"]; - + Возврат Свойства; - + КонецФункции // Создать свойство товара // Создает новое свойство для использования в товарах -// +// // Параметры: // Название - Строка - Название свойства - title // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция СоздатьСвойствоТовара(Знач Название, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Название); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("title", Название); - - Ответ = OPI_Инструменты.Get("api.vk.com/method/market.addProperty", Параметры_); - + + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.addProperty", Параметры_); + Возврат Ответ; КонецФункции // Изменить свойство товара // Изменяет существующее свойство товара -// +// // Параметры: // Название - Строка - Новое название - title // Свойство - Строка,Число - ID свойства - prop // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ИзменитьСвойствоТовара(Знач Название, Знач Свойство, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Название); OPI_ПреобразованиеТипов.ПолучитьСтроку(Свойство); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("title" , Название); Параметры_.Вставить("property_id", Свойство); Параметры_.Вставить("type" , "text"); - - Ответ = OPI_Инструменты.Get("api.vk.com/method/market.editProperty", Параметры_); - + + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.editProperty", Параметры_); + Возврат Ответ; КонецФункции // Удалить свойство товара // Удаляет существующее свойство товара -// +// // Параметры: // Свойство - Строка,Число - ID свойства - prop // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция УдалитьСвойствоТовара(Знач Свойство, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Свойство); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("property_id", Свойство); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.deleteProperty", Параметры_); - + Возврат Ответ; - + КонецФункции // Добавить вариант свойства товара // Добавляет вариант для существующего свойства -// +// // Параметры: // Значение - Строка - Значение свойства - value // Свойство - Строка,Число - ID свойства, куда добавляется вариант - prop // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ДобавитьВариантСвойстваТовара(Знач Значение, Знач Свойство, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Свойство); OPI_ПреобразованиеТипов.ПолучитьСтроку(Значение); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("property_id", Свойство); Параметры_.Вставить("title" , Значение); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.addPropertyVariant", Параметры_); - + Возврат Ответ; - + КонецФункции // Изменить вариант свойства товара // Изменяет значение варианта существующего свойства товара -// +// // Параметры: // Значение - Строка - Новое значение свойства - value // Свойство - Строка,Число - ID свойства - prop // Вариант - Строка,Число - ID варианта - option // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ИзменитьВариантСвойстваТовара(Знач Значение, Знач Свойство, Знач Вариант, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Значение); OPI_ПреобразованиеТипов.ПолучитьСтроку(Свойство); OPI_ПреобразованиеТипов.ПолучитьСтроку(Вариант); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("property_id", Свойство); Параметры_.Вставить("variant_id" , Вариант); Параметры_.Вставить("title" , Значение); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.editPropertyVariant", Параметры_); - + Возврат Ответ; - + КонецФункции // Удалить вариант свойства товара // Удаляет ранее созданный вариант свойства -// +// // Параметры: // Вариант - Строка,Число - ID варианта - option // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция УдалитьВариантСвойстваТовара(Знач Вариант, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Вариант); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("variant_id", Вариант); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.deletePropertyVariant", Параметры_); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -1655,22 +1655,22 @@ // Получить список заказов // Возвращает список заказов сообщества -// +// // Параметры: // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ПолучитьСписокЗаказов(Знач Параметры = "") Экспорт - + Параметры = ПолучитьСтандартныеПараметры(Параметры); Параметры.Вставить("count", 50); - + МассивЗаказов = Новый Массив; ПолучитьСписокЗаказовРекурсивно(МассивЗаказов, Параметры); - + Возврат МассивЗаказов; - + КонецФункции #КонецОбласти @@ -1679,40 +1679,40 @@ // Сформировать клавиатуру // Формирует клавиатуру по массиву кнопок -// +// // Параметры: // МассивКнопок - Массив из Строка - Массив заголовков кнопок - buttons -// +// // Возвращаемое значение: // Строка - JSON клавиатуры Функция СформироватьКлавиатуру(Знач МассивКнопок) Экспорт - - OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивКнопок); - + + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивКнопок); + Клавиатура = Новый Структура; МассивКлавиатуры = Новый Массив; МассивБлока = Новый Массив; - + Для Каждого Действие Из МассивКнопок Цикл - + Кнопка = Новый Структура; - Выражение = Новый Структура; - + Выражение = Новый Структура; + Выражение.Вставить("type" , "text"); Выражение.Вставить("label", Действие); - + Кнопка.Вставить("action", Выражение); МассивБлока.Добавить(Кнопка); - + КонецЦикла; - + МассивКлавиатуры.Добавить(МассивБлока); - - Клавиатура.Вставить("buttons" , МассивКлавиатуры); + + Клавиатура.Вставить("buttons" , МассивКлавиатуры); Клавиатура.Вставить("one_time", Ложь); - + Возврат OPI_Инструменты.JSONСтрокой(Клавиатура); - + КонецФункции #КонецОбласти @@ -1722,29 +1722,29 @@ #Область СлужебныеПроцедурыИФункции Функция ПолучитьСтандартныеПараметры(Знач Параметры = "") - + // Здесь собрано определение данных для работы с VK API // Вы можете переопределять их, передавая в качестве параметра // Совпадающие поля будут перезаписаны с приоритетом параметра функции - + Параметры_ = Новый Структура; - + // access_token - можно получить в браузере по URL из функции СоздатьСсылкуПолученияТокена() // from_group - действия будут выполняться от лица группы // owner_id - id группы с "-" в начале. Можно найти в настройках группы ВК или в ее URL, если не был // установлен свой // app_id - id приложения, которое необходимо создать в профиле на странице для разработчиков // group_id - owner_id, но без "-" - + Параметры_.Вставить("access_token" , ""); Параметры_.Вставить("from_group" , "1"); Параметры_.Вставить("owner_id" , ""); Параметры_.Вставить("v" , "5.131"); Параметры_.Вставить("app_id" , ""); Параметры_.Вставить("group_id" , ""); - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Параметры); - + Если ТипЗнч(Параметры) = Тип("Структура") Или ТипЗнч(Параметры) = Тип("Соответствие") Тогда Для Каждого ПереданныйПараметр Из Параметры Цикл Параметры_.Вставить(ПереданныйПараметр.Ключ, OPI_Инструменты.ЧислоВСтроку(ПереданныйПараметр.Значение)); @@ -1756,32 +1756,32 @@ КонецФункции Функция ПолучитьИДКартинки(Знач Картинка, Знач Параметры, Знач Вид) - - Response_ = "response"; + + Response_ = "response"; Ответ = ЗагрузитьФотоНаСервер(Картинка, Параметры, Вид); Результат = Ответ[Response_]; Если ЗначениеЗаполнено(Результат) Тогда ИДФото = Результат["photo_id"]; - + Если Не ЗначениеЗаполнено(ИДФото) Тогда - Возврат Ответ; + Возврат Ответ; КонецЕсли; - + Иначе Возврат Ответ; КонецЕсли; - + ИДФото = OPI_Инструменты.ЧислоВСтроку(ИДФото); Возврат ИДФото; - + КонецФункции Функция ПолучитьСоответствиеКартинки(Знач Картинка, Знач Параметры, Знач Вид) - - Ответ = ЗагрузитьФотоНаСервер(Картинка, Параметры, Вид); + + Ответ = ЗагрузитьФотоНаСервер(Картинка, Параметры, Вид); ОтветМассив = Ответ.Получить("response"); - + Если Не ЗначениеЗаполнено(ОтветМассив) Или Не ТипЗнч(ОтветМассив) = Тип("Массив") Тогда Возврат Ответ; Иначе @@ -1791,140 +1791,140 @@ ОтветСоответствие = ОтветМассив[0]; КонецЕсли; КонецЕсли; - + Возврат ОтветСоответствие; - + КонецФункции Функция ПолучитьМассивПодборок(Знач Подборки, Знач Параметры = "") - - Response_ = "response"; - Подборки = ПолучитьПодборкиПоИД(Подборки, Параметры); + + Response_ = "response"; + Подборки = ПолучитьПодборкиПоИД(Подборки, Параметры); Результат = Подборки[Response_]; - + Если ЗначениеЗаполнено(Результат) Тогда - + МассивПодборок = Результат["items"]; - + Если Не ЗначениеЗаполнено(МассивПодборок) Тогда - Возврат Подборки; + Возврат Подборки; КонецЕсли; - + Иначе Возврат Подборки; КонецЕсли; - + Возврат МассивПодборок; - + КонецФункции Функция ОпределитьМетодЗагрузкиИзображений(Знач Вид) - + СоответствиеМетодов = Новый Соответствие; Загрузка = "Загрузка"; Сохранение = "Сохранение"; Способ = "Способ"; Фото = "Фото"; - + Если Вид = "Пост" Тогда - + СоответствиеМетодов.Вставить(Загрузка , "photos.getWallUploadServer"); СоответствиеМетодов.Вставить(Сохранение, "photos.saveWallPhoto"); СоответствиеМетодов.Вставить(Фото , "photo"); СоответствиеМетодов.Вставить(Способ , 1); - + ИначеЕсли Вид = "Товар" Тогда - + СоответствиеМетодов.Вставить(Загрузка , "market.getProductPhotoUploadServer"); СоответствиеМетодов.Вставить(Сохранение, "market.saveProductPhoto"); СоответствиеМетодов.Вставить(Способ , 2); - + ИначеЕсли Вид = "История" Тогда - + СоответствиеМетодов.Вставить(Загрузка , "stories.getPhotoUploadServer"); СоответствиеМетодов.Вставить(Сохранение, "stories.save"); СоответствиеМетодов.Вставить(Способ , 3); - + ИначеЕсли Вид = "Опрос" Тогда - + СоответствиеМетодов.Вставить(Загрузка , "polls.getPhotoUploadServer"); СоответствиеМетодов.Вставить(Сохранение, "polls.savePhoto"); СоответствиеМетодов.Вставить(Фото , "photo"); СоответствиеМетодов.Вставить(Способ , 1); - + Иначе - + СоответствиеМетодов.Вставить(Загрузка , "photos.getUploadServer"); СоответствиеМетодов.Вставить(Сохранение, "photos.save"); СоответствиеМетодов.Вставить(Фото , "photos_list"); СоответствиеМетодов.Вставить(Способ , 1); - + КонецЕсли; - + Возврат СоответствиеМетодов; - + КонецФункции Функция ПолучитьСоответствиеПараметровТовара() - + Поля = Новый Соответствие(); - Поля.Вставить("Имя" , "name"); - Поля.Вставить("Описание" , "description"); - Поля.Вставить("Категория" , "category_id"); - Поля.Вставить("Цена" , "price"); - Поля.Вставить("СтараяЦена" , "old_price"); + Поля.Вставить("Имя" , "name"); + Поля.Вставить("Описание" , "description"); + Поля.Вставить("Категория" , "category_id"); + Поля.Вставить("Цена" , "price"); + Поля.Вставить("СтараяЦена" , "old_price"); Поля.Вставить("URL" , "url"); - Поля.Вставить("ГлавныйВГруппе" , "is_main_variant"); - Поля.Вставить("Ширина" , "dimension_width"); - Поля.Вставить("Высота" , "dimension_height"); - Поля.Вставить("Глубина" , "dimension_length"); - Поля.Вставить("Вес" , "weight"); - Поля.Вставить("SKU" , "sku"); + Поля.Вставить("ГлавныйВГруппе" , "is_main_variant"); + Поля.Вставить("Ширина" , "dimension_width"); + Поля.Вставить("Высота" , "dimension_height"); + Поля.Вставить("Глубина" , "dimension_length"); + Поля.Вставить("Вес" , "weight"); + Поля.Вставить("SKU" , "sku"); Поля.Вставить("ДоступныйОстаток" , "stock_amount"); - + Возврат Поля; КонецФункции Функция УправлениеТоваром(Знач ОписаниеТовара, Знач ИДТовара = "", Знач Подборка = "", Знач Параметры = "") - + OPI_ПреобразованиеТипов.ПолучитьСтроку(ИДТовара); OPI_ПреобразованиеТипов.ПолучитьСтроку(Подборка); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(ОписаниеТовара); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("v", "5.199"); - + Response_ = "response"; - + ЗаполнитьПоляЗапросаТовара(ОписаниеТовара, Параметры_); - - Если ЗначениеЗаполнено(ИДТовара) Тогда + + Если ЗначениеЗаполнено(ИДТовара) Тогда Параметры_.Вставить("item_id", ИДТовара); - Метод = "edit"; - Иначе + Метод = "edit"; + Иначе Метод = "add"; КонецЕсли; - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market." + Метод, Параметры_); Результат = Ответ[Response_]; - - Если Не ЗначениеЗаполнено(ИДТовара) И ЗначениеЗаполнено(Результат) Тогда - + + Если Не ЗначениеЗаполнено(ИДТовара) И ЗначениеЗаполнено(Результат) Тогда + ИДТовара = Результат["market_item_id"]; - + Если Не ЗначениеЗаполнено(ИДТовара) Тогда - Возврат Ответ; + Возврат Ответ; КонецЕсли; - + Иначе Возврат Ответ; КонецЕсли; - + Если ЗначениеЗаполнено(Подборка) И ЗначениеЗаполнено(ИДТовара) Тогда ДобавитьТоварВПодборку(ИДТовара, Подборка, Параметры_); КонецЕсли; - + Возврат Ответ; КонецФункции @@ -1935,263 +1935,263 @@ , Знач Основная = Ложь , Знач Скрытая = Ложь , Знач Параметры = "") - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Название); OPI_ПреобразованиеТипов.ПолучитьСтроку(ИДПодборки); OPI_ПреобразованиеТипов.ПолучитьБулево(Основная); OPI_ПреобразованиеТипов.ПолучитьБулево(Скрытая); - - Параметры_ = ПолучитьСтандартныеПараметры(Параметры); + + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Ответ = ДобавитьПараметрКартинки(Картинка, ИДПодборки, Параметры_); - + Если ЗначениеЗаполнено(Ответ) Тогда Возврат Ответ; КонецЕсли; - + Параметры_.Вставить("title" , Название); Параметры_.Вставить("main_album" , ?(Основная, 1, 0)); - Параметры_.Вставить("is_hidden" , ?(Скрытая, 1, 0)); - - Если ЗначениеЗаполнено(ИДПодборки) Тогда + Параметры_.Вставить("is_hidden" , ?(Скрытая , 1, 0)); + + Если ЗначениеЗаполнено(ИДПодборки) Тогда Параметры_.Вставить("album_id", ИДПодборки); - Метод = "editAlbum"; - Иначе + Метод = "editAlbum"; + Иначе Метод = "addAlbum"; КонецЕсли; - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market." + Метод, Параметры_); - + Возврат Ответ; КонецФункции Функция ДобавитьПараметрКартинки(Знач Картинка, Знач ИДПодборки, Параметры) - + PhotoID_ = "photo_id"; - + Если ЗначениеЗаполнено(Картинка) Тогда - + ИДФото = ПолучитьИДКартинки(Картинка, Параметры, "Товар"); - + Если Не ТипЗнч(ИДФото) = Тип("Строка") Тогда - Возврат ИДФото; + Возврат ИДФото; КонецЕсли; - + Параметры.Вставить(PhotoID_, ИДФото); - + Иначе - + Если ЗначениеЗаполнено(ИДПодборки) Тогда - + Подборки = ПолучитьМассивПодборок(ИДПодборки, Параметры); - + Если Не ТипЗнч(Подборки) = Тип("Массив") Тогда - Возврат Подборки; + Возврат Подборки; КонецЕсли; - - Если Не Подборки.Количество() = 0 Тогда + + Если Не Подборки.Количество() = 0 Тогда ИДФото = Подборки[0]["photo"]["id"]; OPI_ПреобразованиеТипов.ПолучитьСтроку(ИДФото); Параметры.Вставить(PhotoID_, ИДФото); КонецЕсли; - + КонецЕсли; - + КонецЕсли; - + Возврат ""; - + КонецФункции Процедура ЗаполнитьПараметрыЗагрузкиФото(Знач Метод, Знач Ответ, Параметры) - + Response_ = "response"; Способ = Метод["Способ"]; СтандартныйСпособ = 1; НовыйСпособ = 2; Если Способ = СтандартныйСпособ Тогда - + Hash = "hash"; Serv = "server"; Aid = "aid"; Фото = Метод["Фото"]; - + Параметры.Вставить(Hash, Ответ[Hash]); Параметры.Вставить(Фото, Ответ[Фото]); - + СерверФото = Ответ.Получить(Serv); - + Если ЗначениеЗаполнено(СерверФото) Тогда СерверФото = OPI_Инструменты.ЧислоВСтроку(СерверФото); - Параметры.Вставить(Serv, СерверФото); + Параметры.Вставить(Serv, СерверФото); КонецЕсли; - + Идентификатор = Ответ.Получить(Aid); - + Если ЗначениеЗаполнено(Идентификатор) Тогда Идентификатор = OPI_Инструменты.ЧислоВСтроку(Идентификатор); - Параметры.Вставить(Aid , Идентификатор); + Параметры.Вставить(Aid , Идентификатор); КонецЕсли; - + ИначеЕсли Способ = НовыйСпособ Тогда - + ОтветСтрокой = OPI_Инструменты.JSONСтрокой(Ответ); Параметры.Вставить("upload_response", ОтветСтрокой); - + Иначе - + Параметры.Вставить("upload_results", Ответ[Response_]["upload_result"]); - + КонецЕсли; КонецПроцедуры Процедура ЗаполнитьПоляЗапросаТовара(Знач ОписаниеТовара, Параметры) - + Response_ = "response"; ОсновноеФото = ОписаниеТовара["ОсновноеФото"]; ДопФото = ОписаниеТовара["ДополнительныеФото"]; Свойства = ОписаниеТовара["ЗначенияСвойств"]; - + Если ЗначениеЗаполнено(ОсновноеФото) Тогда - + Ответ = ЗагрузитьФотоНаСервер(ОсновноеФото, Параметры, "Товар"); Результат = Ответ[Response_]; - + Если ЗначениеЗаполнено(Результат) Тогда ИДФото = Результат["photo_id"]; - + Если Не ЗначениеЗаполнено(ИДФото) Тогда - Возврат; + Возврат; КонецЕсли; - + Иначе Возврат; КонецЕсли; - + ИДФото = OPI_Инструменты.ЧислоВСтроку(ИДФото); - Параметры.Вставить("main_photo_id", ИДФото); - + Параметры.Вставить("main_photo_id", ИДФото); + КонецЕсли; - - Если ТипЗнч(Свойства) = Тип("Массив") Тогда - + + Если ТипЗнч(Свойства) = Тип("Массив") Тогда + Свойства_ = Новый Массив; - + Для Каждого Свойство Из Свойства Цикл - Свойства_.Добавить(OPI_Инструменты.ЧислоВСтроку(Свойство)); + Свойства_.Добавить(OPI_Инструменты.ЧислоВСтроку(Свойство)); КонецЦикла; - - Свойства = СтрСоединить(Свойства_, ","); - + + Свойства = СтрСоединить(Свойства_, ","); + КонецЕсли; - + Если ЗначениеЗаполнено(Свойства) Тогда - Параметры.Вставить("variant_ids", OPI_Инструменты.ЧислоВСтроку(Свойства)); + Параметры.Вставить("variant_ids", OPI_Инструменты.ЧислоВСтроку(Свойства)); КонецЕсли; - + ДобавитьДополнительныеФотоТовара(ДопФото, Параметры); - + Для Каждого Поле Из ПолучитьСоответствиеПараметровТовара() Цикл - + Значение = ОписаниеТовара[Поле.Ключ]; - + Если Значение <> Неопределено Тогда Параметры.Вставить(Поле.Значение, ОписаниеТовара[Поле.Ключ]); КонецЕсли; - + КонецЦикла; КонецПроцедуры Процедура ДобавитьДополнительныеФотоТовара(Знач МассивФото, Параметры) - + Если ТипЗнч(МассивФото) = Тип("Массив") Тогда Если МассивФото.Количество() > 0 Тогда - + СтрокаФотографий = ""; - + Для Каждого Фото Из МассивФото Цикл - + ИДФото = ПолучитьИДКартинки(Фото, Параметры, "Товар"); - + Если Не ТипЗнч(ИДФото) = Тип("Строка") Тогда - Возврат; + Возврат; КонецЕсли; - СтрокаФотографий = СтрокаФотографий + ИДФото + ","; - + СтрокаФотографий = СтрокаФотографий + ИДФото + ","; + КонецЦикла; - + СтрокаФотографий = Лев(СтрокаФотографий, СтрДлина(СтрокаФотографий) - 1); Параметры.Вставить("photo_ids", СтрокаФотографий); КонецЕсли; КонецЕсли; - + КонецПроцедуры Процедура ПолучитьСписокТоваровРекурсивно(МассивТоваров, Параметры, Сдвиг = 0) - + Response_ = "response"; МаксимумВЗапросе = 200; Ответ = OPI_Инструменты.Get("api.vk.com/method/market.get", Параметры); Товары = Ответ[Response_]["items"]; - + Если Товары.Количество() = 0 Тогда Возврат; - КонецЕсли; - + КонецЕсли; + Для Каждого Товар Из Товары Цикл МассивТоваров.Добавить(Товар); КонецЦикла; - + Сдвиг = Сдвиг + МаксимумВЗапросе; Параметры.Вставить("offset", Сдвиг); ПолучитьСписокТоваровРекурсивно(МассивТоваров, Параметры, Сдвиг); - + КонецПроцедуры Процедура ПолучитьСписокАльбомовРекурсивно(МассивАльбомов, Параметры, Сдвиг = 0) - + Response_ = "response"; МаксимумВЗапросе = 100; Ответ = OPI_Инструменты.Get("api.vk.com/method/market.getAlbums", Параметры); Альбомы = Ответ[Response_]["items"]; - + Если Альбомы.Количество() = 0 Тогда Возврат; - КонецЕсли; - + КонецЕсли; + Для Каждого Альбом Из Альбомы Цикл МассивАльбомов.Добавить(Альбом); КонецЦикла; - + Сдвиг = Сдвиг + МаксимумВЗапросе; Параметры.Вставить("offset", Сдвиг); ПолучитьСписокАльбомовРекурсивно(МассивАльбомов, Параметры, Сдвиг); - + КонецПроцедуры Процедура ПолучитьСписокЗаказовРекурсивно(МассивЗаказов, Параметры, Сдвиг = 0) - + Response_ = "response"; МаксимумВЗапросе = 50; Ответ = OPI_Инструменты.Get("api.vk.com/method/market.getGroupOrders", Параметры); Заказы = Ответ[Response_]["items"]; - + Если Заказы.Количество() = 0 Тогда Возврат; - КонецЕсли; - + КонецЕсли; + Для Каждого Заказ Из Заказы Цикл МассивЗаказов.Добавить(Заказ); КонецЦикла; - + Сдвиг = Сдвиг + МаксимумВЗапросе; Параметры.Вставить("offset", Сдвиг); ПолучитьСписокЗаказовРекурсивно(МассивЗаказов, Параметры, Сдвиг); - + КонецПроцедуры #КонецОбласти diff --git a/src/ru/OInt/core/Modules/OPI_Viber.os b/src/ru/OInt/core/Modules/OPI_Viber.os index 2549a86649..f512811048 100644 --- a/src/ru/OInt/core/Modules/OPI_Viber.os +++ b/src/ru/OInt/core/Modules/OPI_Viber.os @@ -23,7 +23,7 @@ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. - + // https://github.com/Bayselonarrend/OpenIntegrations // BSLLS:LatinAndCyrillicSymbolInWord-off @@ -46,55 +46,55 @@ // который будет возвращать 200 и подлинный SSL сертификат. Если есть сертификат и база опубликована // на сервере - можно использовать http-сервис. Туда же будет приходить и информация о новых сообщениях // Viber периодически стучит по адресу Webhook, так что если он будет неактивен, то все перестанет работать -// +// // Параметры: // Токен - Строка - Токен Viber - token // URL - Строка - URL для установки Webhook - url -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Viber Функция УстановитьWebhook(Знач Токен, Знач URL) Экспорт - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("url" , URL , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("auth_token" , Токен, "Строка", Параметры); - + Возврат OPI_Инструменты.Post("https://chatapi.viber.com/pa/set_webhook", Параметры); - + КонецФункции // Получить информацию о канале // Тут можно получить ID пользователей канала. ID для бота необходимо получать из прилетов на Webhook // ID пользователя из информации о канале не подойдет для отправки сообщений через бота - они разные -// +// // Параметры: // Токен - Строка - Токен - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Viber Функция ПолучитьИнформациюОКанале(Знач Токен) Экспорт - - URL = "https://chatapi.viber.com/pa/get_account_info"; + + URL = "https://chatapi.viber.com/pa/get_account_info"; Возврат OPI_Инструменты.Get(URL, , ТокенВЗаголовки(Токен)); - + КонецФункции // Получить данные пользователя // Получает информацию о пользователе по ID -// +// // Параметры: // Токен - Строка - Токен - token // IDПользователя - Строка, Число - ID пользователя Viber - user -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Viber Функция ПолучитьДанныеПользователя(Знач Токен, Знач IDПользователя) Экспорт - + URL = "https://chatapi.viber.com/pa/get_user_details"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("id", IDПользователя, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры, ТокенВЗаголовки(Токен)); Возврат Ответ; @@ -103,22 +103,22 @@ // Получить онлайн пользователей // Получает статус пользователя или нескольких пользователей по ID -// +// // Параметры: // Токен - Строка - Токен Viber - token // IDПользователей - Строка,Число,Массив из Строка,Число - ID пользователей(я) Viber - users -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Viber Функция ПолучитьОнлайнПользователей(Знач Токен, Знач IDПользователей) Экспорт - + URL = "https://chatapi.viber.com/pa/get_online"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("ids", IDПользователей, "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры, ТокенВЗаголовки(Токен)); - + Возврат Ответ; КонецФункции @@ -129,14 +129,14 @@ // Отправить текстовое сообщение // Отправляет текстовое сообщение в чат или канал -// +// // Параметры: // Токен - Строка - Токен - token // Текст - Строка - Текст сообщения - text // IDПользователя - Строка,Число - ID пользователя. Для канала > администратора, для бота > получателя - user // ОтправкаВКанал - Булево - Отправка в канал или в чат бота - ischannel // Клавиатура - Структура из Строка - См. СформироватьКлавиатуруИзМассиваКнопок - keyboard -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Viber Функция ОтправитьТекстовоеСообщение(Знач Токен @@ -144,40 +144,40 @@ , Знач IDПользователя , Знач ОтправкаВКанал , Знач Клавиатура = "") Экспорт - - Возврат ОтправитьСообщение(Токен, "text", IDПользователя, ОтправкаВКанал, , Текст, Клавиатура); - + + Возврат ОтправитьСообщение(Токен, "text", IDПользователя, ОтправкаВКанал, , Текст, Клавиатура); + КонецФункции // Отправить картинку // Отправляет картинку в чат или канал -// +// // Параметры: // Токен - Строка - Токен - token // URL - Строка - URL картинки - picture // IDПользователя - Строка,Число - ID пользователя. Для канала > администратора, для бота > получателя - user // ОтправкаВКанал - булево - Отправка в канал или в чат бота - ischannel // Описание - Строка - Аннотация к картинке - description -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Viber Функция ОтправитьКартинку(Знач Токен, Знач URL, Знач IDПользователя, Знач ОтправкаВКанал, Знач Описание = "") Экспорт - + Возврат ОтправитьСообщение(Токен, "picture", IDПользователя, ОтправкаВКанал, URL, Описание); - + КонецФункции // Отправить файл // Отправляет файл (документ) в чат или канал -// +// // Параметры: // Токен - Строка - Токен - token -// URL - Строка - URL файла - file -// IDПользователя - Строка,Число - ID пользователя. Для канала > администратора, для бота > получателя - user +// URL - Строка - URL файла - file +// IDПользователя - Строка,Число - ID пользователя. Для канала > администратора, для бота > получателя - user // ОтправкаВКанал - Булево - Отправка в канал или в чат бота - ischannel // Расширение - Строка - Расширение файла - ext // Размер - Число - Размер файла. Если не заполнен > определяется автоматически скачиванием файла - size -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Viber Функция ОтправитьФайл(Знач Токен @@ -186,36 +186,36 @@ , Знач ОтправкаВКанал , Знач Расширение , Знач Размер = "") Экспорт - + Если Не ЗначениеЗаполнено(Размер) Тогда - + Ответ = OPI_Инструменты.Get(URL); Размер = Ответ.Размер(); - + КонецЕсли; - + Строка_ = "Строка"; Расширение = СтрЗаменить(Расширение, ".", ""); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("URL" , URL , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("Размер" , Размер , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("Расширение", Расширение, Строка_, Параметры); - + Возврат ОтправитьСообщение(Токен, "file", IDПользователя, ОтправкаВКанал, Параметры); - + КонецФункции // Отправить контакт // Отправляет контакт с номером телефона в чат или канал -// +// // Параметры: // Токен - Строка - Токен - token // ИмяКонтакта - Строка - Имя контакта - name // НомерТелефона - Строка - Номер телефона - phone -// IDПользователя - Строка,Число - ID пользователя. Для канала > администратора, для бота > получателя - user +// IDПользователя - Строка,Число - ID пользователя. Для канала > администратора, для бота > получателя - user // ОтправкаВКанал - Булево - Отправка в канал или в чат бота - ischannel -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Viber Функция ОтправитьКонтакт(Знач Токен @@ -223,91 +223,91 @@ , Знач НомерТелефона , Знач IDПользователя , Знач ОтправкаВКанал) Экспорт - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("name" , ИмяКонтакта , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("phone_number", НомерТелефона, "Строка", Параметры); - - Возврат ОтправитьСообщение(Токен, "contact", IDПользователя, ОтправкаВКанал, Параметры); - + + Возврат ОтправитьСообщение(Токен, "contact", IDПользователя, ОтправкаВКанал, Параметры); + КонецФункции // Отправить локацию // Отправляет географические координаты в чат или канал -// +// // Параметры: // Токен - Строка - Токен - token // Широта - Строка,Число - Географическая широта - lat // Долгота - Строка,Число - Географическая долгота - long -// IDПользователя - Строка,Число - ID пользователя. Для канала > администратора, для бота > получателя - user +// IDПользователя - Строка,Число - ID пользователя. Для канала > администратора, для бота > получателя - user // ОтправкаВКанал - Булево - Отправка в канал или в чат бота - ischannel -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Viber Функция ОтправитьЛокацию(Знач Токен, Знач Широта, Знач Долгота, Знач IDПользователя, Знач ОтправкаВКанал) Экспорт - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("lat", Широта , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("lon", Долгота, "Строка", Параметры); - + Возврат ОтправитьСообщение(Токен, "location", IDПользователя, ОтправкаВКанал, Параметры); - + КонецФункции // Отправить ссылку // Отправляет URL с предпросмотром в чат или канал -// +// // Параметры: // Токен - Строка - Токен - token // URL - Строка - Отправляемая ссылка - url -// IDПользователя - Строка,Число - ID пользователя. Для канала > администратора, для бота > получателя - user +// IDПользователя - Строка,Число - ID пользователя. Для канала > администратора, для бота > получателя - user // ОтправкаВКанал - Булево - Отправка в канал или в чат бота - ischannel -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Viber Функция ОтправитьСсылку(Знач Токен, Знач URL, Знач IDПользователя, Знач ОтправкаВКанал) Экспорт - + Возврат ОтправитьСообщение(Токен, "url", IDПользователя, ОтправкаВКанал, URL); - + КонецФункции // Сформировать клавиатуру из массива кнопок // Возвращает структура клавиатуры для сообщений -// +// // Параметры: // МассивКнопок - Массив из Строка - Массив кнопок - buttons // ЦветКнопок - Строка - HEX цвет кнопок с # в начале - color -// +// // Возвращаемое значение: // Структура - Сформировать клавиатуру из массива кнопок: -// * Buttons - Массив из Структура - Массив сформированных кнопок -// * Type - Строка - Тип клавиатуры +// * Buttons - Массив из Структура - Массив сформированных кнопок +// * Type - Строка - Тип клавиатуры Функция СформироватьКлавиатуруИзМассиваКнопок(Знач МассивКнопок, Знач ЦветКнопок = "#2db9b9") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(ЦветКнопок); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивКнопок); - + МассивСтруктурКнопок = Новый Массив; СтруктураКлавиатуры = Новый Структура; - + Для Каждого ТекстКнопки Из МассивКнопок Цикл - + СтруктураКнопки = Новый Структура; СтруктураКнопки.Вставить("ActionType", "reply"); СтруктураКнопки.Вставить("ActionBody", ТекстКнопки); СтруктураКнопки.Вставить("Text" , ТекстКнопки); СтруктураКнопки.Вставить("BgColor" , ЦветКнопок); СтруктураКнопки.Вставить("Coloumns" , 3); - + МассивСтруктурКнопок.Добавить(СтруктураКнопки); - + КонецЦикла; - + СтруктураКлавиатуры.Вставить("Buttons", МассивСтруктурКнопок); СтруктураКлавиатуры.Вставить("Type" , "keyboard"); - + Возврат СтруктураКлавиатуры; - + КонецФункции #КонецОбласти @@ -317,7 +317,7 @@ #Область СлужебныеПроцедурыИФункции // Отправить сообщение. -// +// // Параметры: // Токен - Строка - Токен // Тип - Строка - Тип отправляемого сообщения @@ -328,8 +328,8 @@ // * Размер - Число, Строка - Размер файла в случае отправке // * Расширение - Строка - Расширение файла в случае отправки // Текст - Строка - Текст сообщения -// Клавиатура - Структура из Строка - Клавиатура, если нужна, см. СформироватьКлавиатуруИзМассиваКнопок -// +// Клавиатура - Структура из Строка - Клавиатура, если нужна, см. СформироватьКлавиатуруИзМассиваКнопок +// // Возвращаемое значение: // Произвольный, HTTPОтвет - Отправить сообщение Функция ОтправитьСообщение(Знач Токен @@ -339,28 +339,28 @@ , Знач Значение = "" , Знач Текст = "" , Знач Клавиатура = "") - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Тип); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDПользователя); OPI_ПреобразованиеТипов.ПолучитьСтроку(Текст); OPI_ПреобразованиеТипов.ПолучитьБулево(ЭтоКанал); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Клавиатура); - + СтруктураПараметров = ВернутьСтандартныеПараметры(); - СтруктураПараметров.Вставить("type", Тип); - + СтруктураПараметров.Вставить("type", Тип); + Если (Тип = "text" Или Тип = "picture") И ЗначениеЗаполнено(Текст) Тогда СтруктураПараметров.Вставить("text", Текст); КонецЕсли; - + Если ТипЗнч(Клавиатура) = Тип("Структура") Тогда СтруктураПараметров.Вставить("keyboard", Клавиатура); КонецЕсли; - + Если ЗначениеЗаполнено(Значение) Тогда - - Если Тип = "file" Тогда + + Если Тип = "file" Тогда СтруктураПараметров.Вставить("media" , Значение["URL"]); СтруктураПараметров.Вставить("size" , Значение["Размер"]); СтруктураПараметров.Вставить("file_name", "Файл." + Значение["Расширение"]); @@ -371,49 +371,49 @@ Иначе СтруктураПараметров.Вставить("media" , Значение); КонецЕсли; - + КонецЕсли; - + Если ЭтоКанал Тогда - СтруктураПараметров.Вставить("from", IDПользователя); + СтруктураПараметров.Вставить("from" , IDПользователя); URL = "https://chatapi.viber.com/pa/post"; - Иначе + Иначе СтруктураПараметров.Вставить("receiver", IDПользователя); URL = "https://chatapi.viber.com/pa/send_message"; КонецЕсли; - + Ответ = OPI_Инструменты.Post(URL, СтруктураПараметров, ТокенВЗаголовки(Токен)); - + Попытка Возврат OPI_Инструменты.JsonВСтруктуру(Ответ.ПолучитьТелоКакДвоичныеДанные()); Исключение Возврат Ответ; КонецПопытки; - + КонецФункции -Функция ВернутьСтандартныеПараметры() - +Функция ВернутьСтандартныеПараметры() + СтруктураОтправителя = Новый Структура; СтруктураОтправителя.Вставить("name" , "Bot"); СтруктураОтправителя.Вставить("avatar", ""); - + СтруктураПараметров = Новый Структура; - СтруктураПараметров.Вставить("sender", СтруктураОтправителя); + СтруктураПараметров.Вставить("sender" , СтруктураОтправителя); СтруктураПараметров.Вставить("min_api_version", 1); - + Возврат СтруктураПараметров; - + КонецФункции Функция ТокенВЗаголовки(Знач Токен) - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + СтруктураЗаголовков = Новый Соответствие; СтруктураЗаголовков.Вставить("X-Viber-Auth-Token", Токен); Возврат СтруктураЗаголовков; - + КонецФункции #КонецОбласти diff --git a/src/ru/OInt/core/Modules/OPI_YandexDisk.os b/src/ru/OInt/core/Modules/OPI_YandexDisk.os index de4001629a..6780bfcd6d 100644 --- a/src/ru/OInt/core/Modules/OPI_YandexDisk.os +++ b/src/ru/OInt/core/Modules/OPI_YandexDisk.os @@ -37,7 +37,7 @@ //@skip-check wrong-string-literal-content // Раскомментировать, если выполняется OneScript -#Использовать "../../tools" +#Использовать "../../tools" #Область ПрограммныйИнтерфейс @@ -45,217 +45,217 @@ // Получить информацию о диске // Получает информацию о текущем диске -// +// // Параметры: // Токен - Строка - Токен - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ПолучитьИнформациюОДиске(Знач Токен) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Заголовки = ЗаголовокАвторизации(Токен); Ответ = OPI_Инструменты.Get("https://cloud-api.yandex.net/v1/disk", , Заголовки); - + Возврат Ответ; - + КонецФункции // Создать папку // Создает каталог на диске -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к созаваемой папке - path -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция СоздатьПапку(Знач Токен, Знач Путь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Путь); - + Заголовки = ЗаголовокАвторизации(Токен); URL = "https://cloud-api.yandex.net/v1/disk/resources"; Href = "href"; - + Параметры = Новый Структура; Параметры.Вставить("path", Путь); - - Параметры = OPI_Инструменты.ПараметрыЗапросаВСтроку(Параметры); + + Параметры = OPI_Инструменты.ПараметрыЗапросаВСтроку(Параметры); Ответ = OPI_Инструменты.Put(URL + Параметры, , Заголовки, Ложь); - - URLОтвета = Ответ[Href]; - + + URLОтвета = Ответ[Href]; + Если Не ЗначениеЗаполнено(URLОтвета) Тогда - Возврат Ответ; + Возврат Ответ; КонецЕсли; - + Ответ = OPI_Инструменты.Get(URLОтвета, , Заголовки); - + Возврат Ответ; КонецФункции // Получить объект // Получает информацию об объекте диска по заданному пути -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к папке или файлу - path -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ПолучитьОбъект(Знач Токен, Знач Путь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Путь); - + Заголовки = ЗаголовокАвторизации(Токен); Параметры = Новый Структура; Параметры.Вставить("path", Путь); - + Ответ = OPI_Инструменты.Get("https://cloud-api.yandex.net/v1/disk/resources", Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Удалить объект // Удаляет объект по заданному пути -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к удаляемой папке или файлу - path // ВКорзину - Булево - В корзину - can -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция УдалитьОбъект(Знач Токен, Знач Путь, Знач ВКорзину = Истина) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Путь); OPI_ПреобразованиеТипов.ПолучитьБулево(ВКорзину); - + Заголовки = ЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; Параметры.Вставить("path" , Путь); Параметры.Вставить("permanently", Не ВКорзину); - + Ответ = OPI_Инструменты.Delete("https://cloud-api.yandex.net/v1/disk/resources", Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Создать копию объекта // Создает копию объекта по заданному пути и пути к оригиналу -// +// // Параметры: // Токен - Строка - Токен - token // Оригинал - Строка - Путь к оригинальному файлу или каталогу - from // Путь - Строка - Путь назначения для копии - to // Перезаписывать - Булево - Перезаписывать если файл с таким именем уже существует - rewrite -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция СоздатьКопиюОбъекта(Знач Токен, Знач Оригинал, Знач Путь, Знач Перезаписывать = Ложь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Оригинал); OPI_ПреобразованиеТипов.ПолучитьСтроку(Путь); OPI_ПреобразованиеТипов.ПолучитьБулево(Перезаписывать); - + Заголовки = ЗаголовокАвторизации(Токен); URL = "https://cloud-api.yandex.net/v1/disk/resources/copy"; Href = "href"; - + Параметры = Новый Структура; Параметры.Вставить("from" , Оригинал); Параметры.Вставить("path" , Путь); Параметры.Вставить("overwrite" , Перезаписывать); - - Параметры = OPI_Инструменты.ПараметрыЗапросаВСтроку(Параметры); + + Параметры = OPI_Инструменты.ПараметрыЗапросаВСтроку(Параметры); Ответ = OPI_Инструменты.Post(URL + Параметры, , Заголовки, Ложь); - - URLОтвета = Ответ[Href]; - + + URLОтвета = Ответ[Href]; + Если Не ЗначениеЗаполнено(URLОтвета) Тогда - Возврат Ответ; + Возврат Ответ; КонецЕсли; - + Ответ = OPI_Инструменты.Get(URLОтвета, , Заголовки); - + Возврат Ответ; - + КонецФункции // Получить ссылку для скачивания // Получает ссылку для скачивания файла -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к файлу для скачивания - path -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ПолучитьСсылкуДляСкачивания(Знач Токен, Знач Путь) Экспорт OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Путь); - + Заголовки = ЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; Параметры.Вставить("path", Путь); - + Ответ = OPI_Инструменты.Get("https://cloud-api.yandex.net/v1/disk/resources/download", Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Скачать файл // Скачивает файл по указанному пути -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к файлу для скачивания - path -// ПутьСохранения - Строка - Путь сохранения файла - out -// +// ПутьСохранения - Строка - Путь сохранения файла - out +// // Возвращаемое значение: // ДвоичныеДанные,Строка - Двоичные данные или путь к файлу при указании параметра ПутьСохранения Функция СкачатьФайл(Знач Токен, Знач Путь, Знач ПутьСохранения = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(ПутьСохранения); Ответ = ПолучитьСсылкуДляСкачивания(Токен, Путь); URL = Ответ["href"]; - + Если Не ЗначениеЗаполнено(URL) Тогда Возврат Ответ; КонецЕсли; - + Ответ = OPI_Инструменты.Get(URL, , , ПутьСохранения); - + Возврат Ответ; - + КонецФункции // Получить список файлов // Получает список файлов с или без отбора по типу -// Список доступных типов: audio, backup, book, compressed, data, development, -// diskimage, document, encoded, executable, flash, font, +// Список доступных типов: audio, backup, book, compressed, data, development, +// diskimage, document, encoded, executable, flash, font, // mage, settings, spreadsheet, text, unknown, video, web -// +// // Параметры: // Токен - Строка - Токен - token // Количество - Число,Строка - Количество возвращаемых объектов - amount // СмещениеОтНачала - Число - Смещение для получение объектов не из начала списка - offset // ОтборПоТипу - Строка - Отбор по типу файла - type // СортироватьПоДате - Булево - Истина > сортировать по дате, Ложь > по алфавиту - datesort -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ПолучитьСписокФайлов(Знач Токен @@ -263,50 +263,50 @@ , Знач СмещениеОтНачала = 0 , Знач ОтборПоТипу = "" , Знач СортироватьПоДате = Ложь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Количество); OPI_ПреобразованиеТипов.ПолучитьСтроку(СмещениеОтНачала); OPI_ПреобразованиеТипов.ПолучитьСтроку(ОтборПоТипу); OPI_ПреобразованиеТипов.ПолучитьБулево(СортироватьПоДате); - + Заголовки = ЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; - + Если ЗначениеЗаполнено(Количество) Тогда Параметры.Вставить("limit", OPI_Инструменты.ЧислоВСтроку(Количество)); КонецЕсли; - + Если ЗначениеЗаполнено(СмещениеОтНачала) Тогда Параметры.Вставить("offset", OPI_Инструменты.ЧислоВСтроку(СмещениеОтНачала)); КонецЕсли; - + Если ЗначениеЗаполнено(ОтборПоТипу) Тогда Параметры.Вставить("media_type", ОтборПоТипу); КонецЕсли; - + Если СортироватьПоДате Тогда Назначение = "last-uploaded"; Иначе Назначение = "files"; КонецЕсли; - + Ответ = OPI_Инструменты.Get("https://cloud-api.yandex.net/v1/disk/resources/" + Назначение, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Переместить объект // Перемещает объект по заданному пути и пути к оригиналу -// +// // Параметры: // Токен - Строка - Токен - token // Оригинал - Строка - Путь к оригинальному файлу или папке - from // Путь - Строка - Путь назначение для перемещения - to // Перезаписывать - Булево - Перезаписывать если файл с таким именем уже существует - rewrite -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ПереместитьОбъект(Знач Токен, Знач Оригинал, Знач Путь, Знач Перезаписывать = Ложь) Экспорт @@ -315,97 +315,97 @@ OPI_ПреобразованиеТипов.ПолучитьСтроку(Оригинал); OPI_ПреобразованиеТипов.ПолучитьСтроку(Путь); OPI_ПреобразованиеТипов.ПолучитьБулево(Перезаписывать); - + Заголовки = ЗаголовокАвторизации(Токен); URL = "https://cloud-api.yandex.net/v1/disk/resources/move"; Href = "href"; - + Параметры = Новый Структура; Параметры.Вставить("from" , Оригинал); Параметры.Вставить("path" , Путь); Параметры.Вставить("overwrite" , Перезаписывать); - - Параметры = OPI_Инструменты.ПараметрыЗапросаВСтроку(Параметры); - Ответ = OPI_Инструменты.Post(URL + Параметры, , Заголовки, Ложь); - URLОтвета = Ответ[Href]; - + + Параметры = OPI_Инструменты.ПараметрыЗапросаВСтроку(Параметры); + Ответ = OPI_Инструменты.Post(URL + Параметры, , Заголовки, Ложь); + URLОтвета = Ответ[Href]; + Если Не ЗначениеЗаполнено(URLОтвета) Тогда - Возврат Ответ; + Возврат Ответ; КонецЕсли; - + Ответ = OPI_Инструменты.Get(URLОтвета, , Заголовки); - + Возврат Ответ; - + КонецФункции // Загрузить файл // Загружает файл на диск по заданному пути -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь для сохранение файла на Диске - path // Файл - Строка,ДвоичныеДанные - Файл для загрузки - file // Перезаписывать - Булево - Перезаписывать, если файл с таким именем уже существует - rewrite -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ЗагрузитьФайл(Знач Токен, Знач Путь, Знач Файл, Знач Перезаписывать = Ложь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Путь); OPI_ПреобразованиеТипов.ПолучитьБулево(Перезаписывать); OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Файл); - + Заголовки = ЗаголовокАвторизации(Токен); - Href = "href"; + Href = "href"; Файл = Новый Структура("file", Файл); - + Параметры = Новый Структура; Параметры.Вставить("path" , Путь); Параметры.Вставить("overwrite" , Перезаписывать); - + Ответ = OPI_Инструменты.Get("https://cloud-api.yandex.net/v1/disk/resources/upload", Параметры, Заголовки); URL = Ответ[Href]; - + Если Не ЗначениеЗаполнено(URL) Тогда - Возврат Ответ; + Возврат Ответ; КонецЕсли; - + Ответ = OPI_Инструменты.PutMultipart(URL, Новый Структура(), Файл, "multipart", Заголовки); - + Возврат Ответ; - + КонецФункции // Загрузить файл по URL // Загружает файл на диск, забирая его по заданному URL -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь помещения загруженного файла - path // Адрес - Строка - URL файла - url -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ЗагрузитьФайлПоURL(Знач Токен, Знач Путь, Знач Адрес) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Путь); OPI_ПреобразованиеТипов.ПолучитьСтроку(Адрес); - + Заголовки = ЗаголовокАвторизации(Токен); URL = "https://cloud-api.yandex.net/v1/disk/resources/upload"; - + Параметры = Новый Структура; Параметры.Вставить("url" , КодироватьСтроку(Адрес, СпособКодированияСтроки.КодировкаURL)); Параметры.Вставить("path", Путь); - - Параметры = OPI_Инструменты.ПараметрыЗапросаВСтроку(Параметры); + + Параметры = OPI_Инструменты.ПараметрыЗапросаВСтроку(Параметры); Ответ = OPI_Инструменты.Post(URL + Параметры, , Заголовки, Ложь); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -414,186 +414,186 @@ // Опубликовать объект // Публикует объект диска в публичный доступ -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к публикуемому объекту - path -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ОпубликоватьОбъект(Знач Токен, Знач Путь) Экспорт - - Возврат ПереключениеОбщегоДоступа(Токен, Путь, Истина); - + + Возврат ПереключениеОбщегоДоступа(Токен, Путь, Истина); + КонецФункции // Отменить публикацию объекта // Отменяет публикацию ранее опубликованного объекта -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к опубликованному ранее объекту - path -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ОтменитьПубликациюОбъекта(Знач Токен, Знач Путь) Экспорт - + Возврат ПереключениеОбщегоДоступа(Токен, Путь, Ложь); - + КонецФункции // Получить список опубликованных объектов. // Получает список опубликованных объектов -// +// // Параметры: -// Токен - Строка - Токен - token +// Токен - Строка - Токен - token // Количество - Число - Количество возвращаемых объектов - amount // СмещениеОтНачала - Число - Смещение для получение объектов не из начала списка - offset -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ПолучитьСписокОпубликованныхОбъектов(Знач Токен, Знач Количество = 0, Знач СмещениеОтНачала = 0) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Количество); OPI_ПреобразованиеТипов.ПолучитьСтроку(СмещениеОтНачала); - + Заголовки = ЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; - + Если ЗначениеЗаполнено(Количество) Тогда Параметры.Вставить("limit", Количество); КонецЕсли; - + Если ЗначениеЗаполнено(СмещениеОтНачала) Тогда Параметры.Вставить("offset", СмещениеОтНачала); КонецЕсли; - + Ответ = OPI_Инструменты.Get("https://cloud-api.yandex.net/v1/disk/resources/public", Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить публичный объект // Получает информацию об опубликованном объекте по его URL -// +// // Параметры: // Токен - Строка - Токен - token -// URL - Строка - Адрес объекта - url +// URL - Строка - Адрес объекта - url // Количество - Число - Количество возвращаемых вложенных объектов (для каталога) - amount // СмещениеОтНачала - Число - Смещение для получение вложенных объектов не из начала списка - offset -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ПолучитьПубличныйОбъект(Знач Токен, Знач URL, Знач Количество = 0, Знач СмещениеОтНачала = 0) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(URL); OPI_ПреобразованиеТипов.ПолучитьСтроку(Количество); OPI_ПреобразованиеТипов.ПолучитьСтроку(СмещениеОтНачала); - + Заголовки = ЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; - + Если ЗначениеЗаполнено(Количество) Тогда Параметры.Вставить("limit", OPI_Инструменты.ЧислоВСтроку(Количество)); КонецЕсли; - + Если ЗначениеЗаполнено(СмещениеОтНачала) Тогда Параметры.Вставить("offset", OPI_Инструменты.ЧислоВСтроку(СмещениеОтНачала)); КонецЕсли; - + Параметры.Вставить("public_key", URL); - + Ответ = OPI_Инструменты.Get("https://cloud-api.yandex.net/v1/disk/public/resources", Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить ссылку скачивания публичного объекта // Получает прямую ссылку для скачивания публичного объекта -// +// // Параметры: // Токен - Строка - Токен - token // URL - Строка - Адрес объекта - url // Путь - Строка - Путь внутри объекта - path -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ПолучитьСсылкуСкачиванияПубличногоОбъекта(Знач Токен, Знач URL, Знач Путь = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(URL); OPI_ПреобразованиеТипов.ПолучитьСтроку(Путь); - + Заголовки = ЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; - + Если ЗначениеЗаполнено(Путь) Тогда Параметры.Вставить("path", Путь); КонецЕсли; - + Параметры.Вставить("public_key", URL); - + Ответ = OPI_Инструменты.Get("https://cloud-api.yandex.net/v1/disk/public/resources/download", Параметры, Заголовки); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции - + // Сохранить публичный объект на диск // Сохраняет публичный объект на ваш диск -// +// // Параметры: // Токен - Строка - Токен - token // URL - Строка - Адрес объекта - url // Откуда - Строка - Путь внутри публичного каталога (только для папок) - from // Куда - Строка - Путь сохранения файла - to -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция СохранитьПубличныйОбъектНаДиск(Знач Токен, Знач URL, Откуда = "", Куда = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(URL); OPI_ПреобразованиеТипов.ПолучитьСтроку(Откуда); OPI_ПреобразованиеТипов.ПолучитьСтроку(Куда); - + Заголовки = ЗаголовокАвторизации(Токен); Адрес = "https://cloud-api.yandex.net/v1/disk/public/resources/save-to-disk"; Href = "href"; - + Параметры = Новый Структура; Параметры.Вставить("public_key", КодироватьСтроку(URL, СпособКодированияСтроки.КодировкаURL)); - + Если ЗначениеЗаполнено(Откуда) Тогда Параметры.Вставить("path", Откуда); КонецЕсли; - + Если ЗначениеЗаполнено(Куда) Тогда Параметры.Вставить("save_path", Куда); КонецЕсли; - - Параметры = OPI_Инструменты.ПараметрыЗапросаВСтроку(Параметры); + + Параметры = OPI_Инструменты.ПараметрыЗапросаВСтроку(Параметры); Ответ = OPI_Инструменты.Post(Адрес + Параметры, , Заголовки, Ложь); - - URLОтвета = Ответ[Href]; - + + URLОтвета = Ответ[Href]; + Если Не ЗначениеЗаполнено(URLОтвета) Тогда - Возврат Ответ; + Возврат Ответ; КонецЕсли; - + Ответ = OPI_Инструменты.Get(URLОтвета, , Заголовки); - + Возврат Ответ; - + КонецФункции - + #КонецОбласти #КонецОбласти @@ -601,42 +601,42 @@ #Область СлужебныеПроцедурыИФункции Функция ЗаголовокАвторизации(Знач Токен) - + Заголовки = Новый Соответствие; Заголовки.Вставить("Authorization", "OAuth " + Токен); - + Возврат Заголовки; - + КонецФункции -Функция ПереключениеОбщегоДоступа(Знач Токен, Знач Путь, Знач ОбщийДоступ) - +Функция ПереключениеОбщегоДоступа(Знач Токен, Знач Путь, Знач ОбщийДоступ) + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Путь); OPI_ПреобразованиеТипов.ПолучитьБулево(ОбщийДоступ); - + Заголовки = ЗаголовокАвторизации(Токен); Назначение = ?(ОбщийДоступ, "publish", "unpublish"); Href = "href"; - + URL = "https://cloud-api.yandex.net/v1/disk/resources/" + Назначение; - + Параметры = Новый Структура; Параметры.Вставить("path", Путь); - - Параметры = OPI_Инструменты.ПараметрыЗапросаВСтроку(Параметры); + + Параметры = OPI_Инструменты.ПараметрыЗапросаВСтроку(Параметры); Ответ = OPI_Инструменты.Put(URL + Параметры, , Заголовки, Ложь); - + URLОтвета = Ответ[Href]; - + Если Не ЗначениеЗаполнено(URLОтвета) Тогда - Возврат Ответ; - КонецЕсли; - + Возврат Ответ; + КонецЕсли; + Ответ = OPI_Инструменты.Get(URLОтвета, , Заголовки); - + Возврат Ответ; - + КонецФункции #КонецОбласти diff --git a/src/ru/OInt/core/Modules/OPI_YandexID.os b/src/ru/OInt/core/Modules/OPI_YandexID.os index 0287059d69..4561af3266 100644 --- a/src/ru/OInt/core/Modules/OPI_YandexID.os +++ b/src/ru/OInt/core/Modules/OPI_YandexID.os @@ -41,77 +41,77 @@ // Получить код подтверждения // Получает код подтверждения и адрес страницы, на которой его необходимо ввести -// +// // Параметры: // ClientId - Строка - Client id - id -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ПолучитьКодПодтверждения(Знач ClientId) Экспорт OPI_ПреобразованиеТипов.ПолучитьСтроку(ClientId); - + Параметры = Новый Структура("client_id", ClientId); Ответ = OPI_Инструменты.Post("https://oauth.yandex.ru/device/code", Параметры, , Ложь); - + Возврат Ответ; - + КонецФункции // Преобразовать код в токен // Преобразовывает код в токен после ввода кода при выполнении ПолучитьКодПодтверждения -// +// // Параметры: // ClientId - Строка - Client id - id // ClientSecret - Строка - Client secret - secret // КодУстройства - Строка - device_code из ПолучитьКодПодтверждения() - device -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ПреобразоватьКодВТокен(Знач ClientId, Знач ClientSecret, Знач КодУстройства) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(ClientId); OPI_ПреобразованиеТипов.ПолучитьСтроку(ClientSecret); OPI_ПреобразованиеТипов.ПолучитьСтроку(КодУстройства); - + Параметры = Новый Структура; Параметры.Вставить("grant_type" , "device_code"); Параметры.Вставить("code" , КодУстройства); Параметры.Вставить("client_id" , ClientId); Параметры.Вставить("client_secret" , ClientSecret); - + Ответ = OPI_Инструменты.Post("https://oauth.yandex.ru/token", Параметры, , Ложь); - + Возврат Ответ; - + КонецФункции // Обновить токен // Обновляет токен по Refresh token -// +// // Параметры: // ClientId - Строка - Client id - id // ClientSecret - Строка - Client secret - secret // RefreshToken - Строка - Refresh token - refresh -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ОбновитьТокен(Знач ClientId, Знач ClientSecret, Знач RefreshToken) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(ClientId); OPI_ПреобразованиеТипов.ПолучитьСтроку(ClientSecret); OPI_ПреобразованиеТипов.ПолучитьСтроку(RefreshToken); - + Параметры = Новый Структура; Параметры.Вставить("grant_type" , "refresh_token"); Параметры.Вставить("refresh_token" , RefreshToken); Параметры.Вставить("client_id" , ClientId); Параметры.Вставить("client_secret" , ClientSecret); - + Ответ = OPI_Инструменты.Post("https://oauth.yandex.ru/token", Параметры, , Ложь); - + Возврат Ответ; - + КонецФункции #КонецОбласти diff --git a/src/ru/OInt/tests/Modules/Coverage_ЗапускВсехТестов.os b/src/ru/OInt/tests/Modules/Coverage_ЗапускВсехТестов.os index 28cd6cdf74..122dc30028 100644 --- a/src/ru/OInt/tests/Modules/Coverage_ЗапускВсехТестов.os +++ b/src/ru/OInt/tests/Modules/Coverage_ЗапускВсехТестов.os @@ -1,8 +1,8 @@ -#Использовать "./internal" +#Использовать "./internal" #Использовать "../../tools" Тесты = OPI_ПолучениеДанныхТестов.СформироватьТестыАссертс(); Для Каждого Тест Из Тесты Цикл Выполнить("OPI_Тесты." + Тест + "()"); -КонецЦикла; \ No newline at end of file +КонецЦикла; diff --git a/src/ru/OInt/tests/Modules/internal/OPI_Тесты.os b/src/ru/OInt/tests/Modules/internal/OPI_Тесты.os index c91f4017ad..dfb1fe5b0e 100644 --- a/src/ru/OInt/tests/Modules/internal/OPI_Тесты.os +++ b/src/ru/OInt/tests/Modules/internal/OPI_Тесты.os @@ -67,22 +67,22 @@ #Область Telegram Процедура Телеграм_ПолучитьИнформациюБота() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token", ПараметрыТеста); - + Telegram_ПолучитьИнформациюБота(ПараметрыТеста); - + КонецПроцедуры Процедура Телеграм_ПолучитьОбновления() Экспорт ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token", ПараметрыТеста); - + Telegram_УдалитьWebhook(ПараметрыТеста); Telegram_ПолучитьОбновления(ПараметрыТеста); - + КонецПроцедуры Процедура Телеграм_УстановитьWebhook() Экспорт @@ -93,7 +93,7 @@ Telegram_УстановитьWebhook(ПараметрыТеста); Telegram_УдалитьWebhook(ПараметрыТеста); - + КонецПроцедуры Процедура Телеграм_ОтправитьТекстовоеСообщение() Экспорт @@ -103,9 +103,9 @@ OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChatID" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelID", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("String" , ПараметрыТеста); - + Telegram_ОтправитьТекстовоеСообщение(ПараметрыТеста); - + КонецПроцедуры Процедура Телеграм_ОтправитьКартинку() Экспорт @@ -116,7 +116,7 @@ OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelID", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("String" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture" , ПараметрыТеста); - + Telegram_ОтправитьКартинку(ПараметрыТеста); Telegram_СкачатьФайл(ПараметрыТеста); @@ -130,7 +130,7 @@ OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelID", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("String" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Video" , ПараметрыТеста); - + Telegram_ОтправитьВидео(ПараметрыТеста); Telegram_СкачатьФайл(ПараметрыТеста); @@ -144,7 +144,7 @@ OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelID", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("String" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Audio" , ПараметрыТеста); - + Telegram_ОтправитьАудио(ПараметрыТеста); Telegram_СкачатьФайл(ПараметрыТеста); @@ -158,7 +158,7 @@ OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelID", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("String" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Document" , ПараметрыТеста); - + Telegram_ОтправитьДокумент(ПараметрыТеста); КонецПроцедуры @@ -171,13 +171,13 @@ OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelID", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("String" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("GIF" , ПараметрыТеста); - + Telegram_ОтправитьГифку(ПараметрыТеста); КонецПроцедуры Процедура Телеграм_ОтправитьМедиагруппу() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChatID" , ПараметрыТеста); @@ -186,26 +186,26 @@ OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Video" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Document" , ПараметрыТеста); - + Telegram_ОтправитьМеидагруппу(ПараметрыТеста); КонецПроцедуры Процедура Телеграм_ОтправитьМестоположение() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChatID" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelID", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Long" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Lat" , ПараметрыТеста); - + Telegram_ОтправитьМестоположение(ПараметрыТеста); КонецПроцедуры Процедура Телеграм_ОтправитьКонтакт() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChatID" , ПараметрыТеста); @@ -219,18 +219,18 @@ КонецПроцедуры Процедура Телеграм_ОтправитьОпрос() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChatID" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelID", ПараметрыТеста); - + Telegram_ОтправитьОпрос(ПараметрыТеста); КонецПроцедуры Процедура Телеграм_ПереслатьСообщение() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChatID" , ПараметрыТеста); @@ -238,38 +238,38 @@ OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelMessageID", ПараметрыТеста); Telegram_ПереслатьСообщение(ПараметрыТеста); - + КонецПроцедуры Процедура Телеграм_БанРазбан() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChatID" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelID" , ПараметрыТеста); - + Telegram_Бан(ПараметрыТеста); Telegram_Разбан(ПараметрыТеста); - + КонецПроцедуры Процедура Телеграм_СоздатьСсылкуПриглашение() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelID", ПараметрыТеста); - + Telegram_СоздатьСсылкуПриглашение(ПараметрыТеста); КонецПроцедуры Процедура Телеграм_ЗакрепитьОткрепитьСообщение() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelID" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelMessageID", ПараметрыТеста); - + Telegram_ЗакрепитьСообщение(ПараметрыТеста); Telegram_ОткрепитьСообщение(ПараметрыТеста); Telegram_УдалитьСообщение(ПараметрыТеста); @@ -277,32 +277,32 @@ КонецПроцедуры Процедура Телеграм_ПолучитьЧислоУчастников() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelID", ПараметрыТеста); - + Telegram_ПолучитьЧислоУчастников(ПараметрыТеста); КонецПроцедуры Процедура Телеграм_ПолучитьСписокАватаровФорума() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token", ПараметрыТеста); - + Telegram_ПолучитьСписокАватаровФорума(ПараметрыТеста); - + КонецПроцедуры Процедура Телеграм_СоздатьУдалитьТемуФорума() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ForumID", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("String" , ПараметрыТеста); - + Telegram_СоздатьТемуФорума(ПараметрыТеста); Telegram_ИзменитьТемуФорума(ПараметрыТеста); Telegram_ЗакрытьТемуФорума(ПараметрыТеста); @@ -313,7 +313,7 @@ КонецПроцедуры Процедура Телеграм_СкрытьПоказатьГлавнуюТему() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ForumID", ПараметрыТеста); @@ -324,13 +324,13 @@ КонецПроцедуры Процедура Телеграм_ИзменитьИмяГлавнойТемы() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ForumID", ПараметрыТеста); Telegram_ИзменитьИмяГлавнойТемыФорума(ПараметрыТеста); - + КонецПроцедуры #КонецОбласти @@ -338,251 +338,251 @@ #Область VK Процедура ВК_СоздатьСсылкуТокена() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("VK_AppID", ПараметрыТеста); - VK_СоздатьСсылкуПолученияТокена(ПараметрыТеста); - + VK_СоздатьСсылкуПолученияТокена(ПараметрыТеста); + КонецПроцедуры Процедура ВК_СоздатьУдалитьПост() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture2", ПараметрыТеста); - + VK_СоздатьПост(ПараметрыТеста); VK_УдалитьПост(ПараметрыТеста); КонецПроцедуры Процедура ВК_СоздатьСоставнойПост() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Video" , ПараметрыТеста); - + VK_СоздатьСоставнойПост(ПараметрыТеста); - + КонецПроцедуры Процедура ВК_СоздатьОпрос() Экспорт - + VK_СоздатьОпрос(); - + КонецПроцедуры Процедура ВК_СохранитьУдалитьКартинку() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture" , ПараметрыТеста); - + VK_СоздатьАльбом(ПараметрыТеста); VK_СохранитьКартинкуВАльбом(ПараметрыТеста); VK_УдалитьКартинку(ПараметрыТеста); VK_УдалитьАльбом(ПараметрыТеста); - + КонецПроцедуры Процедура ВК_СоздатьИсторию() Экспорт - + ПараметрыТеста = Новый Соответствие; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture" , ПараметрыТеста); - + VK_СоздатьИсторию(ПараметрыТеста); - + КонецПроцедуры Процедура ВК_МетодыОбсуждений() Экспорт - + ПараметрыТеста = Новый Структура; Параметры = ПолучитьПараметрыВК(); - + VK_СоздатьОбсуждение(ПараметрыТеста); VK_ЗакрытьОбсуждение(ПараметрыТеста); VK_ОткрытьОбсуждение(ПараметрыТеста); - VK_НаписатьВОбсуждение(ПараметрыТеста); - + VK_НаписатьВОбсуждение(ПараметрыТеста); + OPI_VK.ЗакрытьОбсуждение(ПараметрыТеста["VK_ConvID"], Истина, Параметры); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ВК_ЛайкРепостКоммент() Экспорт - + ПараметрыТеста = Новый Структура(); Параметры = ПолучитьПараметрыВК(); Текст = "Пост из автотеста"; - - Результат = OPI_VK.СоздатьПост(Текст, Новый Массив, , , Параметры); - ИДПоста = Результат["response"]["post_id"]; - + + Результат = OPI_VK.СоздатьПост(Текст, Новый Массив, , , Параметры); + ИДПоста = Результат["response"]["post_id"]; + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_PostID", ИДПоста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("VK_PostID", ПараметрыТеста); - - VK_ПоставитьЛайк(ПараметрыТеста); - VK_СделатьРепост(ПараметрыТеста); - VK_НаписатьКомментарий(ПараметрыТеста); - - OPI_VK.УдалитьПост(ИДПоста, Параметры); + + VK_ПоставитьЛайк(ПараметрыТеста); + VK_СделатьРепост(ПараметрыТеста); + VK_НаписатьКомментарий(ПараметрыТеста); + + OPI_VK.УдалитьПост(ИДПоста , Параметры); OPI_VK.УдалитьПост(ПараметрыТеста["Repost"], Параметры); - + OPI_Инструменты.Пауза(5); КонецПроцедуры Процедура ВК_ПолучитьСтатистику() Экспорт - + ПараметрыТеста = Новый Структура(); - + VK_ПолучитьСтатистику(ПараметрыТеста); - + OPI_Инструменты.Пауза(5); КонецПроцедуры Процедура ВК_ПолучитьСтатистикуПостов() Экспорт - + ПараметрыТеста = Новый Структура(); - + VK_ПолучитьСтатистикуПостов(ПараметрыТеста); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ВК_СоздатьРекламнуюКампанию() Экспорт - + Параметры = ПолучитьПараметрыВК(); Текст = "Пост из автотеста"; - - Результат = OPI_VK.СоздатьПост(Текст, Новый Массив, , , Параметры); - ИДПоста = Результат["response"]["post_id"]; - + + Результат = OPI_VK.СоздатьПост(Текст, Новый Массив, , , Параметры); + ИДПоста = Результат["response"]["post_id"]; + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_PostID", ИДПоста); - + ПараметрыТеста = Новый Структура(); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("VK_AdsCabinetID", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("VK_PostID" , ПараметрыТеста); - + VK_СоздатьРекламнуюКампанию(ПараметрыТеста); VK_СоздатьРекламноеОбъявление(ПараметрыТеста); VK_ПриостановитьРекламноеОбъявление(ПараметрыТеста); - + OPI_VK.УдалитьПост(ИДПоста, Параметры); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ВК_ОтправитьСообщение() Экспорт - + ПараметрыТеста = Новый Структура; - - OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("VK_UserID", ПараметрыТеста); + + OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("VK_UserID" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("VK_CommunityToken", ПараметрыТеста); VK_СформироватьКлавиатуру(ПараметрыТеста); VK_НаписатьСообщение(ПараметрыТеста); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ВК_ПолучитьКатегорииТоваров() Экспорт - + ПараметрыТеста = Новый Структура; - + VK_ПолучитьСписокКатегорийТоваров(ПараметрыТеста); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ВК_СоздатьТоварПодборку() Экспорт - + ПараметрыТеста = Новый Структура; - OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture", ПараметрыТеста); + OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture2", ПараметрыТеста); - + VK_СоздатьПодборкуТоваров(ПараметрыТеста); VK_ИзменитьПодборкуТоваров(ПараметрыТеста); VK_ДобавитьТовар(ПараметрыТеста); VK_ИзменитьТовар(ПараметрыТеста); - VK_ДобавитьТоварВПодборку(ПараметрыТеста); + VK_ДобавитьТоварВПодборку(ПараметрыТеста); VK_УдалитьТоварИзПодборки(ПараметрыТеста); VK_УдалитьТовар(ПараметрыТеста); VK_УдалитьПодборку(ПараметрыТеста); OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ВК_СоздатьТоварСоСвойствами() Экспорт - + Параметры = ПолучитьПараметрыВК(); - + ПараметрыТеста = Новый Структура; - OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture", ПараметрыТеста); + OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture2", ПараметрыТеста); - + VK_СоздатьСвойствоТовара(ПараметрыТеста); - VK_ИзменитьСвойствоТовара(ПараметрыТеста); - VK_ДобавитьВариантСвойстваТовара(ПараметрыТеста); - VK_ИзменитьВариантСвойстваТовара(ПараметрыТеста); + VK_ИзменитьСвойствоТовара(ПараметрыТеста); + VK_ДобавитьВариантСвойстваТовара(ПараметрыТеста); + VK_ИзменитьВариантСвойстваТовара(ПараметрыТеста); VK_СоздатьТоварСоСвойством(ПараметрыТеста); VK_ПолучитьТоварыПоИД(ПараметрыТеста); VK_СгруппироватьТовары(ПараметрыТеста); - + OPI_VK.УдалитьТовар(ПараметрыТеста["VK_MarketItemID2"], Параметры); OPI_VK.УдалитьТовар(ПараметрыТеста["VK_MarketItemID3"], Параметры); - + VK_УдалитьВариантСвойстваТовара(ПараметрыТеста); VK_УдалитьСвойствоТовара(ПараметрыТеста); - + КонецПроцедуры Процедура ВК_ПолучитьСписокТоваров() Экспорт - + ПараметрыТеста = Новый Структура; - + VK_ПолучитьСписокТоваров(ПараметрыТеста); - + КонецПроцедуры Процедура ВК_ПолучитьСписокПодборок() Экспорт - + ПараметрыТеста = Новый Структура; - + VK_ПолучитьСписокПодборок(ПараметрыТеста); - + КонецПроцедуры Процедура ВК_ПолучитьСписокСвойств() Экспорт - + ПараметрыТеста = Новый Структура; - + VK_ПолучитьСписокСвойств(ПараметрыТеста); КонецПроцедуры Процедура ВК_ПолучитьСписокЗаказов() Экспорт - + ПараметрыТеста = Новый Структура; - + VK_ПолучитьСписокЗаказов(ПараметрыТеста); - + КонецПроцедуры Процедура ВК_ЗагрузитьВидео() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Video", ПараметрыТеста); - + VK_ЗагрузитьВидеоНаСервер(ПараметрыТеста); - + КонецПроцедуры #КонецОбласти @@ -590,48 +590,48 @@ #Область YandexDisk Процедура ЯДиск_ПолучитьИнформациюОДиске() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("YandexDisk_Token", ПараметрыТеста); - + YandexDisk_ПолучитьИнформациюОДиске(ПараметрыТеста); - + КонецПроцедуры Процедура ЯДиск_СоздатьПапку() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("YandexDisk_Token", ПараметрыТеста); - + YandexDisk_СоздатьПапку(ПараметрыТеста); - + КонецПроцедуры Процедура ЯДиск_ЗагрузитьПоАдресуПолучитьОбъект() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("YandexDisk_Token"); Путь = "/" + Строка(Новый УникальныйИдентификатор) + ".png"; URL = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/Media/logo.png"; OPI_YandexDisk.ЗагрузитьФайлПоURL(Токен, Путь, URL); OPI_Инструменты.Пауза(5); - + Результат = OPI_YandexDisk.ПолучитьОбъект(Токен, Путь); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьОбъект"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["type"]).Равно("file"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["path"]).Равно("disk:" + Путь); OPI_YandexDisk.УдалитьОбъект(Токен, Путь, Ложь); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ЯДиск_ЗагрузитьУдалитьФайл() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("YandexDisk_Token"); Путь = "/" + Строка(Новый УникальныйИдентификатор) + ".png"; Картинка = OPI_ПолучениеДанныхТестов.ПолучитьДвоичные("Picture"); @@ -639,39 +639,39 @@ Картинка.Записать(ИВФ); Результат = OPI_YandexDisk.ЗагрузитьФайл(Токен, Путь, Картинка, Истина); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗагрузитьФайл"); - + Проверка_Пусто(Результат); OPI_Инструменты.Пауза(5); - + Результат = OPI_YandexDisk.УдалитьОбъект(Токен, Путь, Ложь); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьОбъект"); - + Проверка_Пусто(Результат); - + Результат = OPI_YandexDisk.ЗагрузитьФайл(Токен, Путь, ИВФ, Истина); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗагрузитьФайл"); - + Проверка_Пусто(Результат); OPI_Инструменты.Пауза(5); - - Результат = OPI_YandexDisk.УдалитьОбъект(Токен, Путь, Ложь); - + + Результат = OPI_YandexDisk.УдалитьОбъект(Токен, Путь, Ложь); + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьОбъект"); - - Проверка_Пусто(Результат); + + Проверка_Пусто(Результат); УдалитьФайлы(ИВФ); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ЯДиск_СоздатьКопиюОбъекта() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("YandexDisk_Token"); ПутьОригинала = "/" + Строка(Новый УникальныйИдентификатор) + ".png"; ПутьКопии = "/" + Строка(Новый УникальныйИдентификатор) + ".png"; @@ -680,45 +680,45 @@ OPI_YandexDisk.ЗагрузитьФайлПоURL(Токен, ПутьОригинала, URL); OPI_Инструменты.Пауза(25); - + Результат = OPI_YandexDisk.СоздатьКопиюОбъекта(Токен, ПутьОригинала, ПутьКопии, Истина); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьКопиюОбъекта"); - + OPI_Инструменты.Пауза(5); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["type"]).Равно("file"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["path"]).Равно("disk:" + ПутьКопии); OPI_YandexDisk.УдалитьОбъект(Токен, ПутьОригинала, Ложь); - OPI_YandexDisk.УдалитьОбъект(Токен, ПутьКопии, Ложь); - + OPI_YandexDisk.УдалитьОбъект(Токен, ПутьКопии , Ложь); + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ЯДиск_ПолучитьСсылкуНаСкачивание() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("YandexDisk_Token"); Путь = "/" + Строка(Новый УникальныйИдентификатор) + ".png"; URL = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/Media/logo.png"; OPI_YandexDisk.ЗагрузитьФайлПоURL(Токен, Путь, URL); OPI_Инструменты.Пауза(5); - + Результат = OPI_YandexDisk.ПолучитьСсылкуДляСкачивания(Токен, Путь); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСсылкуДляСкачивания"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["method"]).Равно("GET"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["href"]).ИмеетТип("Строка").Заполнено(); - + URL = Результат["href"]; - + Результат = OPI_YandexDisk.СкачатьФайл(Токен, Путь); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("ДвоичныеДанные").Заполнено(); OPI_YandexDisk.УдалитьОбъект(Токен, Путь, Ложь); @@ -726,26 +726,26 @@ КонецПроцедуры Процедура ЯДиск_ПолучитьСписокФайлов() Экспорт - - Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("YandexDisk_Token"); + + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("YandexDisk_Token"); Количество = 2; Отступ = 1; - + Результат = OPI_YandexDisk.ПолучитьСписокФайлов(Токен, Количество, Отступ, "image"); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокФайлов"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["limit"]).Равно(Количество); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["offset"]).Равно(Отступ); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["items"]).ИмеетТип("Массив"); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ЯДиск_ПереместитьОбъект() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("YandexDisk_Token"); ПутьОригинала = "/" + Строка(Новый УникальныйИдентификатор) + ".png"; ПутьКопии = "/" + Строка(Новый УникальныйИдентификатор) + ".png"; @@ -753,104 +753,104 @@ + "OpenIntegrations/main/Media/logo.png"; Результат = OPI_YandexDisk.ЗагрузитьФайлПоURL(Токен, ПутьОригинала, URL); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗагрузитьФайлПоURL"); - + OPI_Инструменты.Пауза(15); - + Результат = OPI_YandexDisk.ПереместитьОбъект(Токен, ПутьОригинала, ПутьКопии, Истина); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереместитьОбъект"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["type"]).Равно("file"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["path"]).Равно("disk:" + ПутьКопии); OPI_YandexDisk.УдалитьОбъект(Токен, ПутьОригинала, Ложь); - OPI_YandexDisk.УдалитьОбъект(Токен, ПутьКопии, Ложь); - + OPI_YandexDisk.УдалитьОбъект(Токен, ПутьКопии , Ложь); + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ЯДиск_ДействияПубличныхОбъектов() Экспорт - + PUrl = "public_url"; Соответствие = "Соответствие"; Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("YandexDisk_Token"); Путь = "/" + Строка(Новый УникальныйИдентификатор) + ".png"; URL = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/Media/logo.png"; - + OPI_YandexDisk.ЗагрузитьФайлПоURL(Токен, Путь, URL); OPI_Инструменты.Пауза(5); - + МассивРезультатов = Новый Массив; - - МассивРезультатов.Добавить(OPI_YandexDisk.ОпубликоватьОбъект(Токен, Путь)); + + МассивРезультатов.Добавить(OPI_YandexDisk.ОпубликоватьОбъект(Токен, Путь)); ПубличныйURL = МассивРезультатов[0][PUrl]; - + Результат = OPI_YandexDisk.ПолучитьСсылкуСкачиванияПубличногоОбъекта(Токен, ПубличныйURL); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСсылкуСкачиванияПубличногоОбъекта"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип(Соответствие).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["method"]).Равно("GET"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["href"]).ИмеетТип("Строка").Заполнено(); - + Результат = OPI_YandexDisk.ПолучитьПубличныйОбъект(Токен, ПубличныйURL); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьПубличныйОбъект"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип(Соответствие).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["type"]).Равно("file"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["path"]).Равно("/"); - + МассивРезультатов.Добавить(OPI_YandexDisk.СохранитьПубличныйОбъектНаДиск(Токен, ПубличныйURL)); - + МассивРезультатов.Добавить(OPI_YandexDisk.ОтменитьПубликациюОбъекта(Токен, Путь)); - + Счетчик = 0; Для Каждого Результат Из МассивРезультатов Цикл - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "Изменение публикации"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип(Соответствие).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["type"]).Равно("file"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["path"]).Заполнено(); - - Если Счетчик = 0 Тогда + + Если Счетчик = 0 Тогда OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[PUrl]).ИмеетТип("Строка").Заполнено(); Иначе OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[PUrl]).ИмеетТип("Неопределено"); КонецЕсли; - + Счетчик = Счетчик + 1; - + КонецЦикла; - + OPI_YandexDisk.УдалитьОбъект(Токен, Путь, Ложь); - + OPI_Инструменты.Пауза(5); КонецПроцедуры Процедура ЯДиск_ПолучитьСписокОпубликованных() Экспорт - - Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("YandexDisk_Token"); + + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("YandexDisk_Token"); Количество = 2; Отступ = 1; - + Результат = OPI_YandexDisk.ПолучитьСписокОпубликованныхОбъектов(Токен, Количество, Отступ); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокОпубликованныхОбъектов"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["limit"]).Равно(Количество); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["offset"]).Равно(Отступ); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["items"]).ИмеетТип("Массив"); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры #КонецОбласти @@ -858,12 +858,12 @@ #Область Viber Процедура Вайбер_ПолучитьИнформациюОКанале() Экспорт - - Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelToken"); + + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelToken"); Результат = OPI_Viber.ПолучитьИнформациюОКанале(Токен); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИнформациюОКанале"); - + Проверка_ВайберОк(Результат); OPI_Инструменты.Пауза(5); @@ -871,13 +871,13 @@ КонецПроцедуры Процедура Вайбер_ПолучитьДанныеПользователя() Экспорт - - Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelToken"); + + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelToken"); Пользователь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelAdminID"); Результат = OPI_Viber.ПолучитьДанныеПользователя(Токен, Пользователь); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьДанныеПользователя"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["chat_hostname"]).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["status_message"]).Заполнено(); OPI_Инструменты.Пауза(5); @@ -885,51 +885,51 @@ КонецПроцедуры Процедура Вайбер_ПолучитьОнлайнПользователей() Экспорт - - Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelToken"); + + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelToken"); Пользователь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_UserID"); Результат = OPI_Viber.ПолучитьОнлайнПользователей(Токен, Пользователь); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьОнлайнПользователей"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["users"]).ИмеетТип("Массив"); Проверка_ВайберОк(Результат); - + OPI_Инструменты.Пауза(5); КонецПроцедуры Процедура Вайбер_ОтправитьТекстовоеСообщение() Экспорт - + Текст = "Тестовое сообщение"; ТокенКанал = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelToken"); - ТокенБота = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_Token"); + ТокенБота = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_Token"); Пользователь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_UserID"); Администратор = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelAdminID"); - + МассивКнопок = Новый Массив; МассивКнопок.Добавить("Кнопка 1"); МассивКнопок.Добавить("Кнопка 2"); МассивКнопок.Добавить("Кнопка 3"); - + Клавиатура = OPI_Viber.СформироватьКлавиатуруИзМассиваКнопок(МассивКнопок); - + Результат = OPI_Viber.ОтправитьТекстовоеСообщение(ТокенБота, Текст, Пользователь, Ложь, Клавиатура); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьТекстовоеСообщение"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message_token"]).Заполнено(); Проверка_ВайберОк(Результат); - + Результат = OPI_Viber.ОтправитьТекстовоеСообщение(ТокенКанал, Текст, Администратор, Истина, Клавиатура); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьТекстовоеСообщение"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message_token"]).Заполнено(); Проверка_ВайберОк(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Вайбер_ОтправитьКартинку() Экспорт @@ -937,79 +937,79 @@ Текст = "Тестовое сообщение"; Картинка = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Picture"); ТокенКанал = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelToken"); - ТокенБота = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_Token"); + ТокенБота = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_Token"); Пользователь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_UserID"); Администратор = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelAdminID"); - + Результат = OPI_Viber.ОтправитьКартинку(ТокенБота, Картинка, Пользователь, Ложь, Текст); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьКартинку"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message_token"]).Заполнено(); Проверка_ВайберОк(Результат); - + Результат = OPI_Viber.ОтправитьКартинку(ТокенКанал, Картинка, Администратор, Истина, Текст); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьКартинку"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message_token"]).Заполнено(); Проверка_ВайберОк(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Вайбер_ОтправитьФайл() Экспорт - + Документ = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Document"); ТокенКанал = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelToken"); - ТокенБота = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_Token"); + ТокенБота = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_Token"); Пользователь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_UserID"); Администратор = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelAdminID"); - + Результат = OPI_Viber.ОтправитьФайл(ТокенБота, Документ, Пользователь, Ложь, "docx"); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьФайл"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message_token"]).Заполнено(); Проверка_ВайберОк(Результат); - + Результат = OPI_Viber.ОтправитьФайл(ТокенКанал, Документ, Администратор, Истина, "docx"); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьФайл"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message_token"]).Заполнено(); Проверка_ВайберОк(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Вайбер_ОтправитьКонтакт() Экспорт - + Имя = "Петр Петров"; Телефон = "+123456789"; ТокенКанал = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelToken"); - ТокенБота = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_Token"); + ТокенБота = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_Token"); Пользователь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_UserID"); Администратор = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelAdminID"); - + Результат = OPI_Viber.ОтправитьКонтакт(ТокенБота, Имя, Телефон, Пользователь, Ложь); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьКонтакт"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message_token"]).Заполнено(); Проверка_ВайберОк(Результат); - + Результат = OPI_Viber.ОтправитьКонтакт(ТокенКанал, Имя, Телефон, Администратор, Истина); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьКонтакт"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message_token"]).Заполнено(); Проверка_ВайберОк(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Вайбер_ОтправитьЛокацию() Экспорт @@ -1017,52 +1017,52 @@ Широта = "48.87373649724122"; Долгота = "2.2954639195323967"; ТокенКанал = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelToken"); - ТокенБота = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_Token"); + ТокенБота = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_Token"); Пользователь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_UserID"); Администратор = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelAdminID"); - + Результат = OPI_Viber.ОтправитьЛокацию(ТокенБота, Широта, Долгота, Пользователь, Ложь); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьЛокацию"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message_token"]).Заполнено(); Проверка_ВайберОк(Результат); - + Результат = OPI_Viber.ОтправитьЛокацию(ТокенКанал, Широта, Долгота, Администратор, Истина); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьЛокацию"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message_token"]).Заполнено(); Проверка_ВайберОк(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Вайбер_ОтправитьСсылку() Экспорт URL = "https://github.com/Bayselonarrend/OpenIntegrations"; ТокенКанал = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelToken"); - ТокенБота = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_Token"); + ТокенБота = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_Token"); Пользователь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_UserID"); Администратор = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelAdminID"); - + Результат = OPI_Viber.ОтправитьСсылку(ТокенБота, URL, Пользователь, Ложь); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьСсылку"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message_token"]).Заполнено(); Проверка_ВайберОк(Результат); - + Результат = OPI_Viber.ОтправитьСсылку(ТокенКанал, URL, Администратор, Истина); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьСсылку"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message_token"]).Заполнено(); Проверка_ВайберОк(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры #КонецОбласти @@ -1070,53 +1070,53 @@ #Область GoogleWorkspace Процедура ГВ_ПолучитьСсылкуАвторизации() Экспорт - - ClientID = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_ClientID"); + + ClientID = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_ClientID"); Результат = OPI_GoogleWorkspace.СформироватьСсылкуПолученияКода(ClientID); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат) - .ИмеетТип("Строка") + .ИмеетТип("Строка") .Заполнено(); - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Google_Link", Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ГВ_ПолучитьТокен() Экспорт - + ClientID = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_ClientID"); ClientSecret = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_ClientSecret"); Code = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Code"); - + Результат = OPI_GoogleWorkspace.ПолучитьТокенПоКоду(ClientID, ClientSecret, Code); - + Если ЗначениеЗаполнено(Результат["access_token"]) И ЗначениеЗаполнено(Результат["refresh_token"]) Тогда - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Google_Token" , Результат["access_token"]); OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Google_Refresh", Результат["refresh_token"]); - + КонецЕсли; - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ГВ_ОбновитьТокен() Экспорт - + ClientID = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_ClientID"); ClientSecret = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_ClientSecret"); RefreshToken = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Refresh"); - + Результат = OPI_GoogleWorkspace.ОбновитьТокен(ClientID, ClientSecret, RefreshToken); - - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие"); + + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["access_token"]).Заполнено(); - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Google_Token", Результат["access_token"]); - + OPI_Инструменты.Пауза(5); КонецПроцедуры @@ -1126,22 +1126,22 @@ #Область GoogleCalendar Процедура ГК_ПолучитьСписокКалендарей() Экспорт - - Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); + + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); Результат = OPI_GoogleCalendar.ПолучитьСписокКалендарей(Токен); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокКалендарей"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат) .ИмеетТип("Массив"); OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ГК_СоздатьУдалитьКалендарь() Экспорт - - Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); + + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); Наименование = "Тестовый календарь"; Описание = "Тестовое описание"; НаименованиеИзмененное = Наименование + " (изм.)"; @@ -1150,82 +1150,82 @@ Summary = "summary"; Черный = "#000000"; Желтый = "#ffd800"; - - Результат = OPI_GoogleCalendar.СоздатьКалендарь(Токен, Наименование); - + + Результат = OPI_GoogleCalendar.СоздатьКалендарь(Токен, Наименование); + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьКалендарь"); - - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип(ТипСоответствие); + + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип(ТипСоответствие); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Summary]).Равно(Наименование); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["id"]).ИмеетТип(ТипСтрока).Заполнено(); - + Календарь = Результат["id"]; - + Результат = OPI_GoogleCalendar.ИзменитьМетаданныеКалендаря(Токен , Календарь , НаименованиеИзмененное , Описание); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьМетаданныеКалендаря"); - + Проверка_ГКОбъект(Результат, НаименованиеИзмененное, Описание); - + Результат = OPI_GoogleCalendar.ПолучитьМетаданныеКалендаря(Токен, Календарь); - - OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьМетаданныеКалендаря"); - + + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьМетаданныеКалендаря"); + Проверка_ГКОбъект(Результат, НаименованиеИзмененное, Описание); Результат = OPI_GoogleCalendar.ДобавитьКалендарьВСписок(Токен, Календарь); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьКалендарьВСписок"); - + Проверка_ГКОбъект(Результат, НаименованиеИзмененное, Описание); - + Результат = OPI_GoogleCalendar.ИзменитьКалендарьСписка(Токен, Календарь, Черный, Желтый, Ложь); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьКалендарьСписка"); - - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип(ТипСоответствие); + + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип(ТипСоответствие); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Summary]).Равно(НаименованиеИзмененное); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["foregroundColor"]).Равно(Черный); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["backgroundColor"]).Равно(Желтый); - + Результат = OPI_GoogleCalendar.ПолучитьКалендарьСписка(Токен, Календарь); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьКалендарьСписка"); - - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип(ТипСоответствие); + + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип(ТипСоответствие); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Summary]).Равно(НаименованиеИзмененное); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["foregroundColor"]).Равно(Черный); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["backgroundColor"]).Равно(Желтый); Результат = OPI_GoogleCalendar.ОчиститьОсновнойКалендарь(Токен); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОчиститьОсновнойКалендарь"); - + Проверка_Пусто(Результат); - + Результат = OPI_GoogleCalendar.УдалитьКалендарьИзСписка(Токен, Календарь); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьКалендарьИзСписка"); - + Проверка_Пусто(Результат); - + Результат = OPI_GoogleCalendar.УдалитьКалендарь(Токен, Календарь); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьКалендарь"); - + Проверка_Пусто(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ГК_СоздатьУдалитьСобытие() Экспорт - + ТекущаяДата = OPI_Инструменты.ПолучитьТекущуюДату(); - Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); Календарь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_CalendarID"); Наименование = "Новое событие"; Описание = "Описание тестового события"; @@ -1234,12 +1234,12 @@ Час = 3600; Вложения = Новый Соответствие; - + Вложения.Вставить("Картинка1" , "https://opi.neocities.org/assets/images/logo_long-e8fdcca6ff8b32e679ea49a1ccdd3eac.png"); Вложения.Вставить("Картинка2" , "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/Media/logo.png?v1"); - + СоответствиеСобытия = Новый Соответствие; СоответствиеСобытия.Вставить("Описание" , Описание); СоответствиеСобытия.Вставить("Заголовок" , Наименование); @@ -1248,59 +1248,59 @@ СоответствиеСобытия.Вставить("ДатаОкончания" , СоответствиеСобытия["ДатаНачала"] + Час); СоответствиеСобытия.Вставить("МассивURLФайловВложений" , Вложения); СоответствиеСобытия.Вставить("ОтправлятьУведомления" , Истина); - + Результат = OPI_GoogleCalendar.СоздатьСобытие(Токен, Календарь, СоответствиеСобытия); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьСобытие"); - + Событие = Результат[UID]; - + Проверка_ГКОбъект(Результат, Наименование, Описание); - - СоответствиеСобытия = Новый Соответствие; + + СоответствиеСобытия = Новый Соответствие; СоответствиеСобытия.Вставить("Описание", ОписаниеИзм); - + Результат = OPI_GoogleCalendar.ИзменитьСобытие(Токен, Календарь, СоответствиеСобытия, Событие); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьСобытие"); - + Проверка_ГКОбъект(Результат, Наименование, ОписаниеИзм); - + Результат = OPI_GoogleCalendar.ПолучитьСобытие(Токен, Календарь, Событие); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСобытие"); - + Проверка_ГКОбъект(Результат, Наименование, ОписаниеИзм); Результат = OPI_GoogleCalendar.ПереместитьСобытие(Токен, Календарь, Календарь, Событие); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереместитьСобытие"); - + Проверка_ГКОбъект(Результат, Наименование, ОписаниеИзм); - - Результат = OPI_GoogleCalendar.УдалитьСобытие(Токен, Календарь, Событие); - + + Результат = OPI_GoogleCalendar.УдалитьСобытие(Токен, Календарь, Событие); + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьСобытие"); - + Проверка_Пусто(Результат); - + OPI_Инструменты.Пауза(5); КонецПроцедуры Процедура ГК_ПолучитьСписокСобытий() Экспорт - - Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); + + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); Календарь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_CalendarID"); Результат = OPI_GoogleCalendar.ПолучитьСписокСобытий(Токен, Календарь); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокСобытий"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Массив"); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры #КонецОбласти @@ -1308,121 +1308,121 @@ #Область GoogleDrive Процедура ГД_ПолучитьСписокКаталогов() Экспорт - + MimeType_ = "mimeType"; Name_ = "name"; Имя = "Тестовая папка"; Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); Результат = OPI_GoogleDrive.ПолучитьСписокКаталогов(Токен, Имя, Истина); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокКаталогов"); - + Результат = Результат[0]; - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["files"]).ИмеетТип("Массив"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[MimeType_]).Равно("application/vnd.google-apps.folder"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Name_]).Заполнено(); - + OPI_Инструменты.Пауза(5); Идентификатор = Результат["id"]; - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("GD_Catalog", Идентификатор); - + Результат = OPI_GoogleDrive.ПолучитьИнформациюОбОбъекте(Токен, Идентификатор); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИнформациюОбОбъекте"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[MimeType_]).Равно("application/vnd.google-apps.folder"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Name_]).Заполнено(); - + OPI_Инструменты.Пауза(5); КонецПроцедуры Процедура ГД_ЗагрузитьУдалитьФайл() Экспорт - + ЛишниеБайты = 2; - + Kind_ = "kind"; Content_ = "content"; MIME_ = "MIME"; MimeType_ = "mimeType"; Name_ = "name"; Id_ = "id"; - + МассивУдаляемых = Новый Массив; Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); Картинка = OPI_ПолучениеДанныхТестов.ПолучитьДвоичные("Picture"); КартинкаЗамены = OPI_ПолучениеДанныхТестов.ПолучитьДвоичные("Picture2"); Каталог = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("GD_Catalog"); - + Описание = OPI_GoogleDrive.ПолучитьОписаниеФайла(); Описание.Вставить("Родитель", Каталог); - + Результат = OPI_GoogleDrive.ЗагрузитьФайл(Токен, Картинка, Описание); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗагрузитьФайл"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[MimeType_]).Равно(Описание[MIME_]); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Name_]).Равно(Описание["Имя"]); Идентификатор = Результат[Id_]; МассивУдаляемых.Добавить(Идентификатор); - + НовоеИмя = "Скопированный файл.jpeg"; Результат = OPI_GoogleDrive.СкопироватьОбъект(Токен, Идентификатор, НовоеИмя, "root"); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СкоприроватьОбъект"); - + OPI_Инструменты.Пауза(5); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[MimeType_]).Равно(Описание[MIME_]); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Name_]).Равно(НовоеИмя); - + МассивУдаляемых.Добавить(Результат[Id_]); - + Результат = OPI_GoogleDrive.СкачатьФайл(Токен, Идентификатор); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СкачатьФайл"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат.Размер()).Равно(Картинка.Размер() + ЛишниеБайты); OPI_Инструменты.Пауза(5); - + НовоеИмя = "Обновленный файл.jpg"; Результат = OPI_GoogleDrive.ОбновитьФайл(Токен, Идентификатор, КартинкаЗамены, НовоеИмя); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОбновитьФайл"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[MimeType_]).Равно(Описание[MIME_]); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Name_]).Равно(НовоеИмя); OPI_Инструменты.Пауза(5); - + Комментарий = "Yo"; Результат = OPI_GoogleDrive.СоздатьКомментарий(Токен, Идентификатор, Комментарий); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьКомментарий"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Content_]).Равно(Комментарий); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Kind_]).Равно("drive#comment"); - + OPI_Инструменты.Пауза(5); - + Для Каждого Удаляемый Из МассивУдаляемых Цикл - Результат = OPI_GoogleDrive.УдалитьОбъект(Токен, Удаляемый); - + Результат = OPI_GoogleDrive.УдалитьОбъект(Токен, Удаляемый); + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьОбъект"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(ЗначениеЗаполнено(Результат)).Равно(Ложь); OPI_Инструменты.Пауза(2); КонецЦикла; - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ГД_СоздатьУдалитьКомментарий() Экспорт - + Kind_ = "kind"; Content_ = "content"; Id_ = "id"; @@ -1430,75 +1430,75 @@ Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); Каталог = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("GD_Catalog"); Картинка = OPI_ПолучениеДанныхТестов.ПолучитьДвоичные("Picture"); - + Описание = OPI_GoogleDrive.ПолучитьОписаниеФайла(); Описание.Вставить("Родитель", Каталог); - + Результат = OPI_GoogleDrive.ЗагрузитьФайл(Токен, Картинка, Описание); Идентификатор = Результат[Id_]; - + Комментарий = "Новый комментарий"; МассивРезультатов = Новый Массив; Результат = OPI_GoogleDrive.СоздатьКомментарий(Токен, Идентификатор, Комментарий); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьКомментарий"); - + ИДКомментария = Результат[Id_]; - + МассивРезультатов.Добавить(Результат); - + Результат = OPI_GoogleDrive.ПолучитьКомментарий(Токен, Идентификатор, ИДКомментария); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьКомментарий"); - + МассивРезультатов.Добавить(Результат); - + Результат = OPI_GoogleDrive.ПолучитьСписокКомментариев(Токен, Идентификатор); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокКомментариев"); - + Комментарии = Результат[Comments_]; ОбъектКомментарий = Комментарии[Комментарии.ВГраница()]; - + МассивРезультатов.Добавить(ОбъектКомментарий); - - Для Каждого Результат Из МассивРезультатов Цикл + + Для Каждого Результат Из МассивРезультатов Цикл OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Content_]).Равно(Комментарий); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Kind_]).Равно("drive#comment"); КонецЦикла; - - Результат = OPI_GoogleDrive.УдалитьКомментарий(Токен, Идентификатор, ИДКомментария); - + + Результат = OPI_GoogleDrive.УдалитьКомментарий(Токен, Идентификатор, ИДКомментария); + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьКомментарий"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(ЗначениеЗаполнено(Результат)).Равно(Ложь); OPI_GoogleDrive.УдалитьОбъект(Токен, Идентификатор); - + КонецПроцедуры Процедура ГД_СоздатьКаталог() Экспорт - + Name_ = "name"; Имя = "Тестовая папка"; Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); Каталог = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("GD_Catalog"); - + МассивРезультатов = Новый Массив; - + МассивРезультатов.Добавить(OPI_GoogleDrive.СоздатьПапку(Токен, Имя)); МассивРезультатов.Добавить(OPI_GoogleDrive.СоздатьПапку(Токен, Имя, Каталог)); - + Для Каждого Результат Из МассивРезультатов Цикл - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьПапку"); - + ИДКаталога = Результат["id"]; - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Name_]).Равно(Имя); - + OPI_GoogleDrive.УдалитьОбъект(Токен, ИДКаталога); - + КонецЦикла; КонецПроцедуры @@ -1508,90 +1508,90 @@ #Область GoogleSheets Процедура ГТ_СоздатьТаблицу() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); Наименование = "Тестовая таблица"; - + МассивЛистов = Новый Массив; МассивЛистов.Добавить("Лист1"); МассивЛистов.Добавить("Лист2"); - + Результат = OPI_GoogleSheets.СоздатьКнигу(Токен, Наименование, МассивЛистов); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьКнигу"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["properties"]["title"]).Равно(Наименование); Для Н = 0 По МассивЛистов.ВГраница() Цикл - + ИмяЛиста = Результат["sheets"][Н]["properties"]["title"]; OPI_ПолучениеДанныхТестов.ОжидаетЧто(ИмяЛиста).Равно(МассивЛистов[Н]); - Лист = Результат["sheets"][Н]["properties"]["sheetId"]; - Лист = OPI_Инструменты.ЧислоВСтроку(Лист); - + Лист = Результат["sheets"][Н]["properties"]["sheetId"]; + Лист = OPI_Инструменты.ЧислоВСтроку(Лист); + КонецЦикла; - + Книга = Результат["spreadsheetId"]; - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("GS_Spreadsheet", Книга); OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("GS_Sheet" , Лист); - + Наименование = "Тестовая таблица (доп.)"; Результат = OPI_GoogleSheets.СоздатьКнигу(Токен, Наименование, МассивЛистов); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "КопироватьЛист (доп.)"); - + Книга2 = Результат["spreadsheetId"]; - + Результат = OPI_GoogleSheets.КопироватьЛист(Токен, Книга, Книга2, Лист); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "КопироватьЛист"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["title"]).Заполнено(); - + Наименование = "Тестовый лист"; - + Результат = OPI_GoogleSheets.ДобавитьЛист(Токен, Книга, Наименование); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьЛист"); НовыйЛист = Результат["replies"][0]["addSheet"]["properties"]["sheetId"]; НовыйЛист = OPI_Инструменты.ЧислоВСтроку(НовыйЛист); - - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["spreadsheetId"]).Равно(Книга); + + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["spreadsheetId"]).Равно(Книга); Результат = OPI_GoogleSheets.УдалитьЛист(Токен, Книга, НовыйЛист); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьЛист"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["spreadsheetId"]).Равно(Книга); - + Наименование = "Тестовая таблица (изм.)"; - + Результат = OPI_GoogleSheets.ИзменитьНаименованиеКниги(Токен, Книга, Наименование); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьНаименованиеКниги"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["spreadsheetId"]).Равно(Книга); - + КонецПроцедуры Процедура ГТ_ПолучитьТаблицу() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); Книга = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("GS_Spreadsheet"); Наименование = "Тестовая таблица (изм.)"; Результат = OPI_GoogleSheets.ПолучитьКнигу(Токен, Книга); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьТаблицу"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["properties"]["title"]).Равно(Наименование); КонецПроцедуры Процедура ГТ_ЗаполнитьОчиститьЯчейки() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); Книга = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("GS_Spreadsheet"); Лист = "Лист2"; @@ -1605,41 +1605,41 @@ СтруктураЯчеек.Вставить("A4", "Это A4"); СтруктураЯчеек.Вставить("B1", "Это B1"); СтруктураЯчеек.Вставить("B4", "Это B4"); - + МассивЯчеек = Новый Массив; МассивЯчеек.Добавить("B2"); МассивЯчеек.Добавить("A3"); МассивЯчеек.Добавить("B4"); Результат = OPI_GoogleSheets.УстановитьЗначенияЯчеек(Токен, Книга, СтруктураЯчеек, Лист); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УстановитьЗначенияЯчеек"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["spreadsheetId"]).Равно(Книга); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["totalUpdatedCells"]).Равно(СтруктураЯчеек.Количество()); - + Результат = OPI_GoogleSheets.ПолучитьЗначенияЯчеек(Токен, Книга, МассивЯчеек, Лист); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьЗначенияЯчеек"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["spreadsheetId"]).Равно(Книга); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["valueRanges"].Количество()).Равно(МассивЯчеек.Количество()); - + Результат = OPI_GoogleSheets.ПолучитьЗначенияЯчеек(Токен, Книга, , Лист); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьЗначенияЯчеек"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["spreadsheetId"]).Равно(Книга); - + МассивЯчеек = Новый Массив; МассивЯчеек.Добавить("B2"); МассивЯчеек.Добавить("A3"); МассивЯчеек.Добавить("B4"); Результат = OPI_GoogleSheets.ОчиститьЯчейки(Токен, Книга, МассивЯчеек, Лист); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОчиститьЯчейки"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["spreadsheetId"]).Равно(Книга); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["clearedRanges"].Количество()).Равно(МассивЯчеек.Количество()); @@ -1650,154 +1650,154 @@ #Область Twitter Процедура Твиттер_ПолучитьСсылкуАвторизации() Экспорт - + Параметры = ПолучитьПараметрыТвиттер(); Результат = OPI_Twitter.ПолучитьСсылкуАвторизации(Параметры); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Строка").Заполнено(); - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Twitter_URL", Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Твиттер_ОбновитьТокен() Экспорт - + Параметры = ПолучитьПараметрыТвиттер(); Результат = OPI_Twitter.ОбновитьТокен(Параметры); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["access_token"]).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["refresh_token"]).Заполнено(); - + Рефреш = Результат["refresh_token"]; Токен = Результат["access_token"]; - - Если ЗначениеЗаполнено(Рефреш) И Не Рефреш = "null" Тогда + + Если ЗначениеЗаполнено(Рефреш) И Не Рефреш = "null" Тогда OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Twitter_Refresh", Рефреш); КонецЕсли; - + Если ЗначениеЗаполнено(Токен) И Не Токен = "null" Тогда OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Twitter_Token" , Токен); КонецЕсли; - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Твиттер_СоздатьТекстовыйТвит() Экспорт - + Параметры = ПолучитьПараметрыТвиттер(); Текст = "Тестовый твитт" + Строка(Новый УникальныйИдентификатор); - + Результат = OPI_Twitter.СоздатьТекстовыйТвит(Текст, Параметры); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьТекстовыйТвит"); - + Проверка_ТвиттерТекст(Результат, Текст); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Твиттер_СоздатьТвитСКартинкой() Экспорт - + Параметры = ПолучитьПараметрыТвиттер(); Текст = "Тестовый твитт" + Строка(Новый УникальныйИдентификатор); Картинка = OPI_ПолучениеДанныхТестов.ПолучитьДвоичные("Picture"); ИВФ = ПолучитьИмяВременногоФайла("png"); Картинка.Записать(ИВФ); - - Результат = OPI_Twitter.СоздатьТвитКартинки(Текст, Картинка, Параметры); - + + Результат = OPI_Twitter.СоздатьТвитКартинки(Текст, Картинка, Параметры); + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьТвитКартинки"); - - Проверка_ТвиттерТекст(Результат, Текст); - + + Проверка_ТвиттерТекст(Результат, Текст); + Текст = "Тестовый твитт" + Строка(Новый УникальныйИдентификатор); Результат = OPI_Twitter.СоздатьТвитКартинки(Текст, ИВФ, Параметры); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьТвитКартинки"); - + Проверка_ТвиттерТекст(Результат, Текст); - + УдалитьФайлы(ИВФ); - + OPI_Инструменты.Пауза(20); - + КонецПроцедуры Процедура Твиттер_СоздатьТвитСВидео() Экспорт - + Параметры = ПолучитьПараметрыТвиттер(); Текст = "Тестовый твитт" + Строка(Новый УникальныйИдентификатор); Видео = OPI_ПолучениеДанныхТестов.ПолучитьДвоичные("Video"); ИВФ = ПолучитьИмяВременногоФайла("mp4"); Видео.Записать(ИВФ); - - Результат = OPI_Twitter.СоздатьТвитВидео(Текст, Видео, Параметры); - + + Результат = OPI_Twitter.СоздатьТвитВидео(Текст, Видео, Параметры); + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьТвитВидео"); - - Проверка_ТвиттерТекст(Результат, Текст); - + + Проверка_ТвиттерТекст(Результат, Текст); + Текст = "Тестовый твитт" + Строка(Новый УникальныйИдентификатор); Результат = OPI_Twitter.СоздатьТвитВидео(Текст, ИВФ, Параметры); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьТвитВидео"); - + Проверка_ТвиттерТекст(Результат, Текст); - + УдалитьФайлы(ИВФ); - + OPI_Инструменты.Пауза(20); - + КонецПроцедуры Процедура Твиттер_СоздатьТвитСГиф() Экспорт - + Параметры = ПолучитьПараметрыТвиттер(); Текст = "Тестовый твитт" + Строка(Новый УникальныйИдентификатор); Гифка = OPI_ПолучениеДанныхТестов.ПолучитьДвоичные("GIF"); ИВФ = ПолучитьИмяВременногоФайла("gif"); Гифка.Записать(ИВФ); - - Результат = OPI_Twitter.СоздатьТвитГифки(Текст, Гифка, Параметры); - + + Результат = OPI_Twitter.СоздатьТвитГифки(Текст, Гифка, Параметры); + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьТвитГифки"); - - Проверка_ТвиттерТекст(Результат, Текст); - + + Проверка_ТвиттерТекст(Результат, Текст); + Текст = "Тестовый твитт" + Строка(Новый УникальныйИдентификатор); Результат = OPI_Twitter.СоздатьТвитГифки(Текст, ИВФ, Параметры); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьТвитГифки"); - + Проверка_ТвиттерТекст(Результат, Текст); - + УдалитьФайлы(ИВФ); - + OPI_Инструменты.Пауза(20); - + КонецПроцедуры Процедура Твиттер_СоздатьТвитСОпросом() Экспорт - + Параметры = ПолучитьПараметрыТвиттер(); Текст = "Тестовый твитт" + Строка(Новый УникальныйИдентификатор); МассивОтветов = Новый Массив; МассивОтветов.Добавить("Вариант 1"); МассивОтветов.Добавить("Вариант 2"); - + Результат = OPI_Twitter.СоздатьТвитОпрос(Текст, МассивОтветов, 60, Параметры); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьТвитОпрос"); - + Проверка_ТвиттерТекст(Результат, Текст); - + OPI_Инструменты.Пауза(20); - + КонецПроцедуры #КонецОбласти @@ -1805,25 +1805,25 @@ #Область Notion Процедура Ноушн_СоздатьСтраницу() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Token"); Родитель = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Parent"); Заголовок = "Тестовый заголовок"; - + Результат = OPI_Notion.СоздатьСтраницу(Токен, Родитель, Заголовок); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьСтраницу"); - + Проверка_НоушнОбъект(Результат); КонецПроцедуры Процедура Ноушн_СоздатьИзменитьБазу() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Token"); Родитель = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Parent"); Заголовок = "Тестовый заголовок"; - + Свойства = Новый Соответствие; Свойства.Вставить("Имя" , "title"); Свойства.Вставить("Описание" , "rich_text"); @@ -1836,69 +1836,69 @@ Свойства.Вставить("Почта" , "email"); Свойства.Вставить("Телефон" , "phone_number"); Свойства.Вставить("Пользователь" , "people"); - + ВыборЗначения = Новый Соответствие; - ВыборЗначения.Вставить("Новый", "green"); - ВыборЗначения.Вставить("В работе", "yellow"); + ВыборЗначения.Вставить("Новый" , "green"); + ВыборЗначения.Вставить("В работе" , "yellow"); ВыборЗначения.Вставить("Удаленный", "red"); Свойства.Вставить("Статус", ВыборЗначения); - - Результат = OPI_Notion.СоздатьБазуДанных(Токен, Родитель, Заголовок, Свойства); - + + Результат = OPI_Notion.СоздатьБазуДанных(Токен, Родитель, Заголовок, Свойства); + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьБазуДанных"); - + Проверка_НоушнОбъект(Результат, "database"); - + База = Результат["id"]; Заголовок = "Тестовый заголовок"; - Описание = "Тестовое описание"; - + Описание = "Тестовое описание"; + Свойства = Новый Соответствие; Свойства.Вставить("Почта", "rich_text"); // Тип поля "Почта" будет изменен с email на текст Свойства.Вставить("Сайт"); // Поле "Сайт" будет удалено - + Результат = OPI_Notion.ИзменитьСвойстваБазы(Токен, База, Свойства, Заголовок, Описание); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьСвойстваБазы"); - + Проверка_НоушнОбъект(Результат, "database"); КонецПроцедуры Процедура Ноушн_ПолучитьИнформациюОСтранице() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Token"); Страница = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Page"); - + Результат = OPI_Notion.ПолучитьСтраницу(Токен, Страница); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСтраницу"); - - Проверка_НоушнОбъект(Результат); - + + Проверка_НоушнОбъект(Результат); + КонецПроцедуры Процедура Ноушн_ПолучитьИнформациюОБазе() Экспорт Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Token"); База = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Base"); - + Результат = OPI_Notion.ПолучитьБазуДанных(Токен, База); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьБазуДанных"); - + Проверка_НоушнОбъект(Результат, "database"); - + КонецПроцедуры Процедура Ноушн_СоздатьСтраницуВБазу() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Token"); База = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Base"); - + Картинка = Новый Соответствие; Картинка.Вставить("Лого", OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Picture")); - + Свойства = Новый Соответствие; Свойства.Вставить("Имя" , "ООО Вектор"); Свойства.Вставить("Описание" , "Наш первый клиент"); @@ -1910,98 +1910,98 @@ Свойства.Вставить("Сайт" , "https://vector.ru"); Свойства.Вставить("Почта" , "mail@vector.ru"); Свойства.Вставить("Телефон" , "88005553535"); - Свойства.Вставить("Статус" , "Новый"); - + Свойства.Вставить("Статус" , "Новый"); + Результат = OPI_Notion.СоздатьСтраницуВБазу(Токен, База, Свойства); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьСтраницуВБазу"); - + Проверка_НоушнОбъект(Результат); - + Родитель = СтрЗаменить(Результат["parent"]["database_id"], "-", ""); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Родитель).Равно(База); - + КонецПроцедуры Процедура Ноушн_ИзменитьСвойстваСтраницы() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Token"); Страница = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Page"); Иконка = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Picture"); Обложка = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Picture2"); Архивировать = Ложь; - + Свойства = Новый Соответствие; Свойства.Вставить("Активен" , Ложь); Свойства.Вставить("Почта" , "vector@mail.ru"); - + Результат = OPI_Notion.ИзменитьСвойстваСтраницы(Токен , Страница , Свойства , Иконка , Обложка , Архивировать); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьСвойстваСтраницы"); - + Проверка_НоушнОбъект(Результат); - + КонецПроцедуры Процедура Ноушн_СоздатьУдалитьБлок() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Token"); Родитель = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Parent"); Блок = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Block"); - - Результат = OPI_Notion.ВернутьБлок(Токен, Блок); - + + Результат = OPI_Notion.ВернутьБлок(Токен, Блок); + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВернутьБлок"); - + Проверка_НоушнОбъект(Результат, "block"); - + Результат = OPI_Notion.СоздатьБлок(Токен, Родитель, Результат); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьБлок"); - + Проверка_НоушнОбъект(Результат, "list"); - + Блок = Результат["results"][0]["id"]; - Результат = OPI_Notion.ВернутьДочерниеБлоки(Токен, Блок); - + Результат = OPI_Notion.ВернутьДочерниеБлоки(Токен, Блок); + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВернутьДочерниеБлоки"); - + Проверка_НоушнОбъект(Результат, "list"); - + Результат = OPI_Notion.УдалитьБлок(Токен, Блок); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьБлок"); - + Проверка_НоушнОбъект(Результат, "block"); - + КонецПроцедуры Процедура Ноушн_ПолучитьПользователей() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Token"); Результат = OPI_Notion.СписокПользователей(Токен); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СписокПользователей"); - + Проверка_НоушнОбъект(Результат, "list"); - + КонецПроцедуры Процедура Ноушн_ПолучитьДанныеПользователя() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Token"); - Пользователь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_User"); + Пользователь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_User"); Результат = OPI_Notion.ПолучитьДанныеПользователя(Токен, Пользователь); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьДанныеПользователя"); - + Проверка_НоушнОбъект(Результат, "user"); - + КонецПроцедуры #КонецОбласти @@ -2009,160 +2009,160 @@ #Область Slack Процедура Слак_ПолучитьИнформациюОБоте() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); Результат = OPI_Slack.ПолучитьИнформациюОБоте(Токен); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИнформациюОБоте"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["bot_id"]).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["user_id"]).Заполнено(); - + КонецПроцедуры Процедура Слак_ПолучитьСписокПользователей() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); Результат = OPI_Slack.ПолучитьСписокПользователей(Токен); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокПользователей"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["members"]).ИмеетТип("Массив"); - + КонецПроцедуры Процедура Слак_ПолучитьСписокОбластей() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); Результат = OPI_Slack.ПолучитьСписокРабочихОбластей(Токен); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокРабочихОбластей"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["teams"]).ИмеетТип("Массив"); - + КонецПроцедуры Процедура Слак_ОтправитьУдалитьСообщение() Экспорт - Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); Канал = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Channel"); Текст = "Тестовое сообщение 1"; Текст2 = "Тестовое сообщение 2"; Отметки = Новый Массив; Картинка = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/Media/logo.png?v1"; - + Результат = OPI_Slack.ОтправитьСообщение(Токен, Канал, Текст); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьСообщение"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["channel"]).Равно(Канал); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ts"]).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message"]["text"]).Равно(Текст); - + Отметка = Результат["ts"]; - + Результат = OPI_Slack.ИзменитьСообщение(Токен, Канал, Отметка, Текст2); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьСообщение"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["channel"]).Равно(Канал); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ts"]).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message"]["text"]).Равно(Текст2); - + Результат = OPI_Slack.ПолучитьСписокОтветовНаСообщение(Токен, Канал, Отметка); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокОтветовНаСообщение"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["messages"]).ИмеетТип("Массив"); - + Результат = OPI_Slack.ПолучитьСсылкуНаСообщение(Токен, Канал, Отметка); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСсылкуНаСообщение"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["channel"]).Равно(Канал); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["permalink"]).Заполнено(); - + Проверка_СлакОк(Результат); - + Отметки.Добавить(Отметка); - + МассивБлоков = Новый Массив; Блок = OPI_Slack.СформироватьБлокКартинку(Картинка, "Yo"); МассивБлоков.Добавить(Блок); - + Результат = OPI_Slack.ОтправитьСообщение(Токен, Канал, Текст, , МассивБлоков); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьСообщение (картинка)"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["channel"]).Равно(Канал); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ts"]).Заполнено(); - + Отметки.Добавить(Результат["ts"]); - - Блок = OPI_Slack.СформироватьБлокКартинку(Картинка, "Yo"); + + Блок = OPI_Slack.СформироватьБлокКартинку(Картинка, "Yo"); БлокJSON = OPI_Инструменты.JSONСтрокой(Блок); - + ИВФ = ПолучитьИмяВременногоФайла("json"); - + ТекстовыйДокумент = Новый ТекстовыйДокумент(); ТекстовыйДокумент.УстановитьТекст(БлокJSON); ТекстовыйДокумент.Записать(ИВФ); - + Результат = OPI_Slack.ОтправитьСообщение(Токен, Канал, Текст, , ИВФ); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьСообщение (json)"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["channel"]).Равно(Канал); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ts"]).Заполнено(); - + Отметки.Добавить(Результат["ts"]); - - Блоки = "['" + ИВФ + "','" + ИВФ + "']"; + + Блоки = "['" + ИВФ + "','" + ИВФ + "']"; Результат = OPI_Slack.ОтправитьСообщение(Токен, Канал, Текст, , Блоки); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьСообщение (json массив)"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["channel"]).Равно(Канал); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ts"]).Заполнено(); - + Отметки.Добавить(Результат["ts"]); УдалитьФайлы(ИВФ); - + Для Каждого Отметка Из Отметки Цикл - + Результат = OPI_Slack.УдалитьСообщение(Токен, Канал, Отметка); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьСообщение"); Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["channel"]).Равно(Канал); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ts"]).Заполнено(); - + КонецЦикла; - + Час = 3600; Сутки = 24; Отправка = OPI_Инструменты.ПолучитьТекущуюДату() + (Сутки * Час); Результат = OPI_Slack.ОтправитьСообщение(Токен, Канал, Текст, Отправка); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьСообщение (отложенное)"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["channel"]).Равно(Канал); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["scheduled_message_id"]).Заполнено(); - + Отметка = Результат["scheduled_message_id"]; Результат = OPI_Slack.УдалитьСообщение(Токен, Канал, Отметка, Истина); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьСообщение"); Проверка_СлакОк(Результат); @@ -2170,50 +2170,50 @@ КонецПроцедуры Процедура Слак_ОтправитьУдалитьЭфемерное() Экспорт - - Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); + + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); Канал = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Channel"); Пользователь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_User"); Картинка = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/Media/logo.png?v1"; Текст = "Тестовое сообщение 1"; - + Блок = OPI_Slack.СформироватьБлокКартинку(Картинка, "Yo"); Результат = OPI_Slack.ОтправитьЭфемерноеСообщение(Токен, Канал, Текст, Пользователь, Блок); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьСообщение"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message_ts"]).Заполнено(); - + КонецПроцедуры Процедура Слак_ПолучитьОтложенныеСообщения() Экспорт - - Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); + + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); Канал = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Channel"); - + Результат = OPI_Slack.ПолучитьСписокОтложенныхСообщений(Токен, Канал); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокОтложенныхСообщений"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["scheduled_messages"]).ИмеетТип("Массив"); - + КонецПроцедуры Процедура Слак_СоздатьАрхивироватьКанал() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); Пользователь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_User"); Имя = "testconv" + Строка(Новый УникальныйИдентификатор); Тема = "Тестовая тема"; Цель = "Тестовая цель"; - + #Область СоздатьКанал Результат = OPI_Slack.СоздатьКанал(Токен, Имя); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьКанал"); - + Данные = Результат["channel"]; Канал = Данные["id"]; @@ -2223,9 +2223,9 @@ #Область УстановитьТемуКанала Результат = OPI_Slack.УстановитьТемуКанала(Токен, Канал, Тема); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УстановитьТемуКанала"); - + Данные = Результат["channel"]; Канал = Данные["id"]; @@ -2233,144 +2233,144 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Данные["name"]).Равно(Имя); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Данные["topic"]["value"]).Равно(Тема); #КонецОбласти - + #Область УстановитьЦельКанала Результат = OPI_Slack.УстановитьЦельКанала(Токен, Канал, Цель); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УстановитьЦельКанала"); - + Проверка_СлакОк(Результат); #КонецОбласти - + #Область ПолучитьКанал Результат = OPI_Slack.ПолучитьКанал(Токен, Канал); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьКанал"); - + Данные = Результат["channel"]; Канал = Данные["id"]; Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Данные["name"]).Равно(Имя); #КонецОбласти - + #Область ПригласитьПользователейВКанал Результат = OPI_Slack.ПригласитьПользователейВКанал(Токен, Канал, Пользователь); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПригласитьПользователейВКанал"); - + Данные = Результат["channel"]; Канал = Данные["id"]; Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Данные["name"]).Равно(Имя); #КонецОбласти - + #Область ВыгнатьПользователяИзКанала Результат = OPI_Slack.ВыгнатьПользователяИзКанала(Токен, Канал, Пользователь); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВыгнатьПользователяИзКанала"); - + Проверка_СлакОк(Результат); #КонецОбласти - + #Область ПолучитьИсториюКанала Результат = OPI_Slack.ПолучитьИсториюКанала(Токен, Канал); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИсториюКанала"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["messages"]).ИмеетТип("Массив"); #КонецОбласти - + #Область ПолучитьСписокПользователейКанала Результат = OPI_Slack.ПолучитьСписокПользователейКанала(Токен, Канал); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокПользователейКанала"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["members"]).ИмеетТип("Массив"); #КонецОбласти #Область ПокинутьКанал Результат = OPI_Slack.ПокинутьКанал(Токен, Канал); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПокинутьКанал"); - + Проверка_СлакОк(Результат); #КонецОбласти - + #Область ВступитьВКанал Результат = OPI_Slack.ВступитьВКанал(Токен, Канал); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВступитьВКанал"); - + Данные = Результат["channel"]; Канал = Данные["id"]; Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Данные["name"]).Равно(Имя); #КонецОбласти - + #Область ПереименоватьКанал НовоеИмя = "testconv" + Строка(Новый УникальныйИдентификатор); Результат = OPI_Slack.ПереименоватьКанал(Токен, Канал, НовоеИмя); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереименоватьКанал"); - + Данные = Результат["channel"]; Канал = Данные["id"]; Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Данные["name"]).Равно(НовоеИмя); #КонецОбласти - + #Область АрхивироватьКанал Результат = OPI_Slack.АрхивироватьКанал(Токен, Канал); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "АрхивироватьКанал"); - + Проверка_СлакОк(Результат); #КонецОбласти - + КонецПроцедуры Процедура Слак_ПолучитьСписокКаналов() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); - + Результат = OPI_Slack.ПолучитьСписокКаналов(Токен); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокКаналов"); Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["channels"]).ИмеетТип("Массив"); - + КонецПроцедуры Процедура Слак_ОткрытьЗакрытьДиалог() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); Пользователь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_User"); Текст = "Yo, dude"; - + Результат = OPI_Slack.ОткрытьДиалог(Токен, Пользователь); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОткрытьДиалог"); Диалог = Результат["channel"]["id"]; Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["channel"]).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Диалог).Заполнено(); - + Результат = OPI_Slack.ОтправитьСообщение(Токен, Диалог, Текст); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьСообщение"); - + Проверка_СлакОк(Результат); Результат = OPI_Slack.ЗакрытьДиалог(Токен, Диалог); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗакрытьДиалог"); Проверка_СлакОк(Результат); @@ -2378,12 +2378,12 @@ КонецПроцедуры Процедура Слак_ПолучитьСписокФайлов() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); Канал = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Channel"); - + Результат = OPI_Slack.ПолучитьСписокФайлов(Токен, Канал); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокФайлов"); Проверка_СлакОк(Результат); @@ -2392,113 +2392,113 @@ КонецПроцедуры Процедура Слак_ЗагрузитьУдалитьФайл() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); Файл = OPI_ПолучениеДанныхТестов.ПолучитьДвоичные("Document"); Канал = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Channel"); МассивФайлов = Новый Массив; ИмяФайла = "megadoc.docx"; Заголовок = "Новый файл"; - + Результат = OPI_Slack.ЗагрузитьФайл(Токен, Файл, ИмяФайла, Заголовок); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗагрузитьФайл"); ЗагруженныйФайл = Результат["files"][0]; МассивФайлов.Добавить(ЗагруженныйФайл["id"]); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(ЗагруженныйФайл["name"]).Равно(ИмяФайла); - + Результат = OPI_Slack.ЗагрузитьФайл(Токен, Файл, ИмяФайла, Заголовок, Канал); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗагрузитьФайл (в канал)"); ЗагруженныйФайл = Результат["files"][0]; МассивФайлов.Добавить(ЗагруженныйФайл["id"]); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(ЗагруженныйФайл["name"]).Равно(ИмяФайла); - + Результат = OPI_Slack.ПолучитьДанныеФайла(Токен, ЗагруженныйФайл["id"]); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьФайл"); - + ЗагруженныйФайл = Результат["file"]; - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(ЗагруженныйФайл["name"]).Равно(ИмяФайла); - + Для Каждого ЗагруженныйФайл Из МассивФайлов Цикл - + Результат = OPI_Slack.УдалитьФайл(Токен, ЗагруженныйФайл); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьФайл"); - + Проверка_СлакОк(Результат); - + КонецЦикла; КонецПроцедуры Процедура Слак_ПолучитьСписокВФ() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); Канал = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Channel"); - + Результат = OPI_Slack.ПолучитьСписокВнешнихФайлов(Токен); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокВнешнихФайлов"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["files"]).ИмеетТип("Массив"); - + Результат = OPI_Slack.ПолучитьСписокВнешнихФайлов(Токен, Канал); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокВнешнихФайлов"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["files"]).ИмеетТип("Массив"); - + КонецПроцедуры Процедура Слак_ЗагрузитьУдалитьВФ() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); Файл = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Document"); Канал = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Channel"); Заголовок = "Новый файл"; - + Результат = OPI_Slack.ДобавитьВнешнийФайл(Токен, Файл, Заголовок); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьВнешнийФайл"); - + ЗагруженныйФайл = Результат["file"]; - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(ЗагруженныйФайл["title"]).Равно(Заголовок); - + Результат = OPI_Slack.ПолучитьВнешнийФайл(Токен, ЗагруженныйФайл["id"]); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьВнешнийФайл"); - + ЗагруженныйФайл = Результат["file"]; - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(ЗагруженныйФайл["title"]).Равно(Заголовок); - + Результат = OPI_Slack.ОтправитьВнешнийФайл(Токен, ЗагруженныйФайл["id"], Канал); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьВнешнийФайл"); - + Проверка_СлакОк(Результат); - + Результат = OPI_Slack.УдалитьВнешнийФайл(Токен, ЗагруженныйФайл["id"]); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьВнешнийФайл"); - + Проверка_СлакОк(Результат); - + КонецПроцедуры #КонецОбласти @@ -2506,127 +2506,127 @@ #Область Airtable Процедура АТ_СоздатьБазу() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Airtable_Token"); Область = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Airtable_Workspace"); Наименование = "Тестовая база"; - + МассивПолей = Новый Массив; МассивПолей.Добавить(OPI_Airtable.ПолучитьПолеНомера("Номер")); МассивПолей.Добавить(OPI_Airtable.ПолучитьПолеСтроковое("Строковое")); - + ИмяТаблицы = "Тестовая таблица"; - + СоответствиеТаблиц = Новый Соответствие; СоответствиеТаблиц.Вставить(ИмяТаблицы, МассивПолей); - + Результат = OPI_Airtable.СоздатьБазу(Токен, Область, Наименование, СоответствиеТаблиц); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьБазу"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["id"]).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["tables"][0]["name"]).Равно(ИмяТаблицы); - + База = Результат["id"]; OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Airtable_Base", База); - + Результат = OPI_Airtable.ПолучитьТаблицыБазы(Токен, База); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьТаблицыБазы"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["tables"]).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["tables"]).ИмеетТип("Массив"); Результат = OPI_Airtable.ПолучитьСписокБаз(Токен); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокБаз"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["bases"]).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["bases"]).ИмеетТип("Массив"); - + КонецПроцедуры Процедура АТ_СоздатьТаблицу() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Airtable_Token"); База = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Airtable_Base"); - + МассивПолей = Новый Массив; - МассивПолей.Добавить(OPI_Airtable.ПолучитьПолеНомера("Номер")); + МассивПолей.Добавить(OPI_Airtable.ПолучитьПолеНомера("Номер")); OPI_ПолучениеДанныхТестов.ЗаписатьЛог(МассивПолей[0], "ПолучитьПолеНомера"); - + МассивПолей.Добавить(OPI_Airtable.ПолучитьПолеСтроковое("Строковое")); OPI_ПолучениеДанныхТестов.ЗаписатьЛог(МассивПолей[1], "ПолучитьПолеСтроковое"); - + МассивПолей.Добавить(OPI_Airtable.ПолучитьПолеВложения("Вложение")); OPI_ПолучениеДанныхТестов.ЗаписатьЛог(МассивПолей[2], "ПолучитьПолеВложения"); - + МассивПолей.Добавить(OPI_Airtable.ПолучитьПолеФлажка("Флажок")); OPI_ПолучениеДанныхТестов.ЗаписатьЛог(МассивПолей[3], "ПолучитьПолеФлажка"); - + МассивПолей.Добавить(OPI_Airtable.ПолучитьПолеДаты("Дата")); OPI_ПолучениеДанныхТестов.ЗаписатьЛог(МассивПолей[4], "ПолучитьПолеДаты"); - + МассивПолей.Добавить(OPI_Airtable.ПолучитьПолеТелефона("Телефон")); OPI_ПолучениеДанныхТестов.ЗаписатьЛог(МассивПолей[5], "ПолучитьПолеТелефона"); - + МассивПолей.Добавить(OPI_Airtable.ПолучитьПолеПочты("Почта")); - OPI_ПолучениеДанныхТестов.ЗаписатьЛог(МассивПолей[6], "ПолучитьПолеПочты"); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(МассивПолей[6], "ПолучитьПолеПочты"); + МассивПолей.Добавить(OPI_Airtable.ПолучитьПолеСсылки("Ссылка")); - OPI_ПолучениеДанныхТестов.ЗаписатьЛог(МассивПолей[7], "ПолучитьПолеСсылки"); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(МассивПолей[7], "ПолучитьПолеСсылки"); + ИмяТаблицы = "Тестовая таблица 2"; Описание = "Новая таблица"; - + Результат = OPI_Airtable.СоздатьТаблицу(Токен, База, ИмяТаблицы, МассивПолей, Описание); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьТаблицу"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["name"]).Равно(ИмяТаблицы); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["description"]).Равно(Описание); - + Таблица = Результат["id"]; ИмяТаблицы = "Тестовая таблица 2 (изм.)"; Описание = "Новая таблица (изм.)"; - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Airtable_Table", Таблица); - + Результат = OPI_Airtable.ИзменитьТаблицу(Токен, База, Таблица, ИмяТаблицы, Описание); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьТаблицу"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["name"]).Равно(ИмяТаблицы); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["description"]).Равно(Описание); КонецПроцедуры Процедура АТ_СоздатьПоле() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Airtable_Token"); База = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Airtable_Base"); Таблица = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Airtable_Table"); Имя = Строка(Новый УникальныйИдентификатор); - + Поле = OPI_Airtable.ПолучитьПолеНомера(Имя); - + Результат = OPI_Airtable.СоздатьПоле(Токен, База, Таблица, Поле); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьПоле"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["name"]).Равно(Имя); - - Поле = Результат["id"]; + + Поле = Результат["id"]; Имя = Имя + "(изм.)"; Описание = "Новое описание"; - + Результат = OPI_Airtable.ИзменитьПоле(Токен, База, Таблица, Поле, Имя, Описание); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьПоле"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["name"]).Равно(Имя); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["description"]).Равно(Описание); - + КонецПроцедуры Процедура АТ_СоздатьУдалитьЗаписи() Экспорт @@ -2634,94 +2634,94 @@ Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Airtable_Token"); База = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Airtable_Base"); Таблица = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Airtable_Table"); - + Числовой = 10; Строчный = "Привет"; - + ОписаниеСтроки1 = Новый Структура("Номер,Строковое", Числовой, Строчный); ОписаниеСтроки2 = Новый Структура("Номер,Строковое", Числовой, Строчный); - + МассивУдаляемых = Новый Массив; МассивОписаний = Новый Массив; МассивОписаний.Добавить(ОписаниеСтроки1); МассивОписаний.Добавить(ОписаниеСтроки2); - + Результат = OPI_Airtable.СоздатьЗаписи(Токен, База, Таблица, МассивОписаний); OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьЗаписи"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["records"]).ИмеетТип("Массив"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["records"].Количество()).Равно(2); - + Для Каждого Запись Из Результат["records"] Цикл МассивУдаляемых.Добавить(Запись["id"]); КонецЦикла; - + Результат = OPI_Airtable.СоздатьЗаписи(Токен, База, Таблица, ОписаниеСтроки1); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьЗаписи (одна)"); - + ОдиночнаяЗапись = Результат["id"]; OPI_ПолучениеДанныхТестов.ОжидаетЧто(ОдиночнаяЗапись).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["createdTime"]).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["fields"]["Номер"]).Равно(Числовой); OPI_ПолучениеДанныхТестов.ОжидаетЧто(СокрЛП(Результат["fields"]["Строковое"])).Равно(Строчный); - + Результат = OPI_Airtable.ПолучитьЗапись(Токен, База, Таблица, ОдиночнаяЗапись); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьЗапись"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["id"]).Равно(ОдиночнаяЗапись); - + Текст = "Тестовый комментарий"; Результат = OPI_Airtable.СоздатьКомментарий(Токен, База, Таблица, ОдиночнаяЗапись, Текст); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьКомментарий"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["text"]).Равно(Текст); - + Коммент = Результат["id"]; Текст = "Тестовый комментарий (изм.)"; Результат = OPI_Airtable.ИзменитьКомментарий(Токен, База, Таблица, ОдиночнаяЗапись, Коммент, Текст); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьКомментарий"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["text"]).Равно(Текст); - + Результат = OPI_Airtable.ПолучитьКомментарии(Токен, База, Таблица, ОдиночнаяЗапись); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьКомментарии"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["comments"]).ИмеетТип("Массив"); - + Результат = OPI_Airtable.УдалитьКомментарий(Токен, База, Таблица, ОдиночнаяЗапись, Коммент); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьКомментарий"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["deleted"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["id"]).Равно(Коммент); - + Результат = OPI_Airtable.ПолучитьСписокЗаписей(Токен, База, Таблица); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокЗаписей"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["records"]).ИмеетТип("Массив"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["records"]).Заполнено(); - + Результат = OPI_Airtable.УдалитьЗаписи(Токен, База, Таблица, МассивУдаляемых); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьЗаписи"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["records"]).ИмеетТип("Массив"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["records"]).Заполнено(); - + Результат = OPI_Airtable.УдалитьЗаписи(Токен, База, Таблица, ОдиночнаяЗапись); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьЗаписи (одна)"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["records"]).ИмеетТип("Массив"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["records"]).Заполнено(); - + КонецПроцедуры #КонецОбласти @@ -2729,29 +2729,29 @@ #Область Dropbox Процедура ДропБокс_ПолучитьОбновитьТокен() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Dropbox_Appkey" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Dropbox_Appsecret", ПараметрыТеста); - - Dropbox_ПолучитьСсылкуАвторизации(ПараметрыТеста); - + + Dropbox_ПолучитьСсылкуАвторизации(ПараметрыТеста); + OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Dropbox_Code", ПараметрыТеста); Dropbox_ПолучитьТокен(ПараметрыТеста); - + OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Dropbox_Refresh", ПараметрыТеста); - + Dropbox_ОбновитьТокен(ПараметрыТеста); - + КонецПроцедуры Процедура ДропБокс_ЗагрузитьФайл() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Dropbox_Token", ПараметрыТеста); - OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture", ПараметрыТеста); - + OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture" , ПараметрыТеста); + Dropbox_ЗагрузитьФайл(ПараметрыТеста); Dropbox_ПолучитьИнформациюОбОбъекте(ПараметрыТеста); Dropbox_ПолучитьСписокВерсийОбъекта(ПараметрыТеста); @@ -2761,73 +2761,73 @@ Dropbox_ПереместитьОбъект(ПараметрыТеста); Dropbox_КопироватьОбъект(ПараметрыТеста); Dropbox_УдалитьОбъект(ПараметрыТеста); - + КонецПроцедуры Процедура ДропБокс_СоздатьКаталог() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Dropbox_Token", ПараметрыТеста); - + Dropbox_СоздатьПапку(ПараметрыТеста); Dropbox_СкачатьПапку(ПараметрыТеста); - + КонецПроцедуры Процедура ДропБокс_ПолучитьСписокФайловПапки() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Dropbox_Token", ПараметрыТеста); - + Dropbox_ПолучитьСписокФайловПапки(ПараметрыТеста); - + КонецПроцедуры Процедура ДропБокс_ЗагрузитьФайлПоURL() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Dropbox_Token", ПараметрыТеста); - OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Document", ПараметрыТеста); - + OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Document" , ПараметрыТеста); + Dropbox_ЗагрузитьФайлПоURL(ПараметрыТеста); Dropbox_ПолучитьСтатусЗагрузкиПоURL(ПараметрыТеста); - + КонецПроцедуры Процедура ДропБокс_СоздатьУдалитьТег() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Dropbox_Token", ПараметрыТеста); - + Dropbox_ДобавитьТег(ПараметрыТеста); Dropbox_ПолучитьСписокТегов(ПараметрыТеста); Dropbox_УдалитьТег(ПараметрыТеста); - + КонецПроцедуры Процедура ДропБокс_ПолучитьАккаунт() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Dropbox_Token", ПараметрыТеста); - + Dropbox_ПолучитьИнформациюОбАккаунте(ПараметрыТеста); Dropbox_ПолучитьДанныеИспользованияПространства(ПараметрыТеста); - + КонецПроцедуры Процедура ДропБокс_РаботаСДоступами() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Dropbox_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Dropbox_OtherUser", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Dropbox_FileID" , ПараметрыТеста); - + Dropbox_ДобавитьПользователейКФайлу(ПараметрыТеста); Dropbox_ОпубликоватьПапку(ПараметрыТеста); Dropbox_ДобавитьПользователейКПапке(ПараметрыТеста); Dropbox_ОтменитьПубликациюПапки(ПараметрыТеста); Dropbox_ОтменитьПубликациюФайла(ПараметрыТеста); - + КонецПроцедуры #КонецОбласти @@ -2835,37 +2835,37 @@ #Область Bitrix24 Процедура Б24_РаботаСТокеном() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Domain" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_ClientID" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_ClientSecret", ПараметрыТеста); - + Bitrix24_ПолучитьСсылкуАвторизацииПриложения(ПараметрыТеста); - + OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Code", ПараметрыТеста); - + Bitrix24_ПолучитьТокен(ПараметрыТеста); - + OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Refresh", ПараметрыТеста); - + Bitrix24_ОбновитьТокен(ПараметрыТеста); - + КонецПроцедуры Процедура Б24_СерверноеВремя() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_URL" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Domain", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Token" , ПараметрыТеста); - - Bitrix24_СерверноеВремя(ПараметрыТеста); + + Bitrix24_СерверноеВремя(ПараметрыТеста); КонецПроцедуры Процедура Б24_РаботаСНовостями() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_URL" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Domain", ПараметрыТеста); @@ -2880,18 +2880,18 @@ Bitrix24_ДобавитьКомментарийНовости(ПараметрыТеста); Bitrix24_ДобавитьПолучателейКНовости(ПараметрыТеста); Bitrix24_УдалитьНовость(ПараметрыТеста); - + КонецПроцедуры Процедура Б24_РаботаСЗадачами() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_URL" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Domain", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_UserID", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture" , ПараметрыТеста); - + Bitrix24_ПолучитьСтруктуруЗадачи(ПараметрыТеста); Bitrix24_СоздатьЗадачу(ПараметрыТеста); Bitrix24_СоздатьЗависимостьЗадач(ПараметрыТеста); @@ -2910,7 +2910,7 @@ Bitrix24_НачатьВыполнениеЗадачи(ПараметрыТеста); Bitrix24_НачатьНаблюдатьЗаЗадачей(ПараметрыТеста); Bitrix24_ПрекратитьНаблюдатьЗаЗадачей(ПараметрыТеста); - Bitrix24_ПриостановитьЗадачу(ПараметрыТеста); + Bitrix24_ПриостановитьЗадачу(ПараметрыТеста); Bitrix24_ПолучитьИсториюЗадачи(ПараметрыТеста); Bitrix24_ПолучитьСписокЗадач(ПараметрыТеста); Bitrix24_ПроверитьДоступКЗадаче(ПараметрыТеста); @@ -2922,29 +2922,29 @@ Bitrix24_ВозобновитьЭлементЧеклистаЗадачи(ПараметрыТеста); Bitrix24_УдалитьЭлементЧеклистаЗадачи(ПараметрыТеста); Bitrix24_ПолучитьПланЗадачНаДень(ПараметрыТеста); - + Наименование = "Картинка задачи.jpg"; - Картинка = ПараметрыТеста["Picture"]; + Картинка = ПараметрыТеста["Picture"]; IDПриемника = 3; - + URL = ПараметрыТеста["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ЗагрузитьФайлВХранилище(URL, Наименование, Картинка, IDПриемника); - IDФайла = Результат["result"]["ID"]; - - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_TaskFileID", IDФайла); + IDФайла = Результат["result"]["ID"]; + + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_TaskFileID", IDФайла); ПараметрыТеста.Вставить("Bitrix24_TaskFileID", IDФайла); - - Bitrix24_ДобавитьФайлВЗадачу(ПараметрыТеста); - + + Bitrix24_ДобавитьФайлВЗадачу(ПараметрыТеста); + OPI_Bitrix24.УдалитьФайл(URL, IDФайла); - + Bitrix24_УдалитьЗадачу(ПараметрыТеста); - + КонецПроцедуры Процедура Б24_РаботаСДиском() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_URL" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Domain", ПараметрыТеста); @@ -2979,7 +2979,7 @@ Bitrix24_ПоместитьКаталогВКорзину(ПараметрыТеста); Bitrix24_ВосстановитьКаталог(ПараметрыТеста); Bitrix24_УдалитьКаталог(ПараметрыТеста); - + КонецПроцедуры Процедура Б24_РаботаСКомментариями() Экспорт @@ -2988,25 +2988,25 @@ OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_URL" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Domain", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Token" , ПараметрыТеста); - + ТекущаяДата = OPI_Инструменты.ПолучитьТекущуюДату(); Час = 3600; Сутки = 24; Исполнитель = 1; - + СтруктураЗадачи = Новый Структура; СтруктураЗадачи.Вставить("TITLE" , "Новая задача"); СтруктураЗадачи.Вставить("DESCRIPTION" , "Новое описание задачи"); СтруктураЗадачи.Вставить("PRIORITY" , "2"); СтруктураЗадачи.Вставить("DEADLINE" , ТекущаяДата + Час * Сутки); СтруктураЗадачи.Вставить("RESPONSIBLE_ID", Исполнитель); - + URL = ПараметрыТеста["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.СоздатьЗадачу(URL, СтруктураЗадачи); - IDЗадачи = Результат["result"]["task"]["id"]; - - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_CommentsTaskID", IDЗадачи); + IDЗадачи = Результат["result"]["task"]["id"]; + + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_CommentsTaskID", IDЗадачи); ПараметрыТеста.Вставить("Bitrix24_CommentsTaskID", IDЗадачи); Bitrix24_ДобавитьКомментарийЗадачи(ПараметрыТеста); @@ -3017,9 +3017,9 @@ Bitrix24_ПолучитьСписокКомментариевЗадачи(ПараметрыТеста); Bitrix24_ПолучитьКомменатрийЗадачи(ПараметрыТеста); Bitrix24_УдалитьКомментарийЗадачи(ПараметрыТеста); - - OPI_Bitrix24.УдалитьЗадачу(URL, IDЗадачи); - + + OPI_Bitrix24.УдалитьЗадачу(URL, IDЗадачи); + КонецПроцедуры Процедура Б24_УчетРабочегоВремени() Экспорт @@ -3028,25 +3028,25 @@ OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_URL" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Domain", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Token" , ПараметрыТеста); - + ТекущаяДата = OPI_Инструменты.ПолучитьТекущуюДату(); Час = 3600; Сутки = 24; Исполнитель = 1; - + СтруктураЗадачи = Новый Структура; СтруктураЗадачи.Вставить("TITLE" , "Новая задача"); СтруктураЗадачи.Вставить("DESCRIPTION" , "Новое описание задачи"); СтруктураЗадачи.Вставить("PRIORITY" , "2"); СтруктураЗадачи.Вставить("DEADLINE" , ТекущаяДата + Час * Сутки); СтруктураЗадачи.Вставить("RESPONSIBLE_ID", Исполнитель); - + URL = ПараметрыТеста["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.СоздатьЗадачу(URL, СтруктураЗадачи); - IDЗадачи = Результат["result"]["task"]["id"]; - - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_ElapsedTaskID", IDЗадачи); + IDЗадачи = Результат["result"]["task"]["id"]; + + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_ElapsedTaskID", IDЗадачи); ПараметрыТеста.Вставить("Bitrix24_ElapsedTaskID", IDЗадачи); Bitrix24_ДобавитьТрудозатратыЗадачи(ПараметрыТеста); @@ -3054,51 +3054,51 @@ Bitrix24_ПолучитьСписокТрудозатратЗадачи(ПараметрыТеста); Bitrix24_ИзменитьТрудозатратыЗадачи(ПараметрыТеста); Bitrix24_УдалитьТрудозатратыЗадачи(ПараметрыТеста); - - OPI_Bitrix24.УдалитьЗадачу(URL, IDЗадачи); - + + OPI_Bitrix24.УдалитьЗадачу(URL, IDЗадачи); + КонецПроцедуры Процедура Б24_Канбан() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_URL" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Domain", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Token" , ПараметрыТеста); - + ТекущаяДата = OPI_Инструменты.ПолучитьТекущуюДату(); Час = 3600; Сутки = 24; Исполнитель = 1; - + СтруктураЗадачи = Новый Структура; СтруктураЗадачи.Вставить("TITLE" , "Новая задача"); СтруктураЗадачи.Вставить("DESCRIPTION" , "Новое описание задачи"); СтруктураЗадачи.Вставить("PRIORITY" , "2"); СтруктураЗадачи.Вставить("DEADLINE" , ТекущаяДата + Час * Сутки); СтруктураЗадачи.Вставить("RESPONSIBLE_ID", Исполнитель); - + URL = ПараметрыТеста["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.СоздатьЗадачу(URL, СтруктураЗадачи); - IDЗадачи = Результат["result"]["task"]["id"]; - - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_KanbanTaskID", IDЗадачи); + IDЗадачи = Результат["result"]["task"]["id"]; + + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_KanbanTaskID", IDЗадачи); ПараметрыТеста.Вставить("Bitrix24_KanbanTaskID", IDЗадачи); - + Bitrix24_ДобавитьСтадиюКанбана(ПараметрыТеста); Bitrix24_ПолучитьСтадииКанбана(ПараметрыТеста); Bitrix24_ПеренестиЗадачуВСтадиюКанбана(ПараметрыТеста); Bitrix24_ИзменитьСтадиюКанбана(ПараметрыТеста); - - OPI_Bitrix24.УдалитьЗадачу(URL, IDЗадачи); - + + OPI_Bitrix24.УдалитьЗадачу(URL, IDЗадачи); + Bitrix24_УдалитьСтадиюКанбана(ПараметрыТеста); - + КонецПроцедуры Процедура Б24_РаботаСЧатами() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_URL" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Domain", ПараметрыТеста); @@ -3106,7 +3106,7 @@ OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture2" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Document" , ПараметрыТеста); - + Bitrix24_ПолучитьСтатусПользователя(ПараметрыТеста); Bitrix24_УстановитьСтатусПользователя(ПараметрыТеста); Bitrix24_ПолучитьПользователей(ПараметрыТеста); @@ -3134,11 +3134,11 @@ Bitrix24_ПрочитатьВсе(ПараметрыТеста); Bitrix24_СменитьВладельцаЧата(ПараметрыТеста); Bitrix24_ПокинутьЧат(ПараметрыТеста); - + КонецПроцедуры Процедура Б24_РаботаСУведомлениями() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_URL" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Domain", ПараметрыТеста); @@ -3146,11 +3146,11 @@ OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture2" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Document" , ПараметрыТеста); - + Bitrix24_СоздатьПерсональноеУведомление(ПараметрыТеста); Bitrix24_СоздатьСистемноеУведомление(ПараметрыТеста); Bitrix24_УдалитьУведомление(ПараметрыТеста); - + КонецПроцедуры #КонецОбласти @@ -3161,24 +3161,24 @@ #Область СлужебныеПроцедурыИФункции -Функция ПолучитьПараметрыВК() - +Функция ПолучитьПараметрыВК() + Параметры = Новый Структура; НомерГруппы = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("VK_GroupID"); - + Параметры.Вставить("access_token" , OPI_ПолучениеДанныхТестов.ПолучитьПараметр("VK_Token")); Параметры.Вставить("owner_id" , "-" + НомерГруппы); Параметры.Вставить("app_id" , OPI_ПолучениеДанныхТестов.ПолучитьПараметр("VK_AppID")); Параметры.Вставить("group_id" , НомерГруппы); - + Возврат Параметры; - + КонецФункции -Функция ПолучитьПараметрыТвиттер() - +Функция ПолучитьПараметрыТвиттер() + Параметры = Новый Соответствие; - + Параметры.Вставить("redirect_uri" , OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Twitter_Redirect")); Параметры.Вставить("client_id" , OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Twitter_ClinetID")); Параметры.Вставить("client_secret" , OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Twitter_ClientSecret")); @@ -3186,102 +3186,102 @@ Параметры.Вставить("refresh_token" , OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Twitter_Refresh")); Параметры.Вставить("oauth_token" , OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Twitter_OAuthToken")); Параметры.Вставить("oauth_token_secret" , OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Twitter_OAuthSecret")); - - Параметры.Вставить("oauth_consumer_key" + + Параметры.Вставить("oauth_consumer_key" , OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Twitter_OAuthConsumerKey")); - Параметры.Вставить("oauth_consumer_secret" + Параметры.Вставить("oauth_consumer_secret" , OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Twitter_OAuthConsumerSecret")); Возврат Параметры; - + КонецФункции #Область Проверки -Процедура Проверка_Пусто(Знач Результат) +Процедура Проверка_Пусто(Знач Результат) OPI_ПолучениеДанныхТестов.ОжидаетЧто(ЗначениеЗаполнено(Результат)).Равно(Ложь); КонецПроцедуры -Процедура Проверка_Строка(Знач Результат) - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Строка"); +Процедура Проверка_Строка(Знач Результат) + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Строка"); КонецПроцедуры Процедура Проверка_ДвоичныеДанные(Знач Результат, Знач Размер = Неопределено) - + МинимальныйРазмер = 500000; - - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("ДвоичныеДанные"); - + + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("ДвоичныеДанные"); + Если Не Размер = Неопределено Тогда - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат.Размер() >= Размер).Равно(Истина); + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат.Размер() >= Размер).Равно(Истина); Иначе OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат.Размер() > МинимальныйРазмер).Равно(Истина); КонецЕсли; - + КонецПроцедуры Процедура Проверка_Массив(Знач Результат, Знач Количество = Неопределено) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Массив"); - + Если Не Количество = Неопределено Тогда - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетДлину(Количество); - КонецЕсли; - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетДлину(Количество); + КонецЕсли; + КонецПроцедуры Процедура Проверка_Соответствие(Знач Результат) - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); + КонецПроцедуры Процедура Проверка_Структура(Знач Результат) OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Структура").Заполнено(); - + КонецПроцедуры Процедура Проверка_ТелеграмИстина(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).Равно(Истина); - + КонецПроцедуры Процедура Проверка_ТелеграмИнформацияБота(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["username"]).Заполнено(); - + КонецПроцедуры Процедура Проверка_ТелеграмМассив(Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие") .Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Массив"); - + КонецПроцедуры Процедура Проверка_ТелеграмУстановкаВебхук(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["description"]).Равно("Webhook was set"); - + КонецПроцедуры Процедура Проверка_ТелеграмУдалениеВебхук(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["description"]).Заполнено(); - + КонецПроцедуры Процедура Проверка_ТелеграмСообщение(Знач Результат, Знач Текст) @@ -3289,16 +3289,16 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["text"]).Равно(Текст); - + КонецПроцедуры Процедура Проверка_ТелеграмКартинка(Знач Результат, Знач Текст) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие") .Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["caption"]).Равно(Текст); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["photo"]).ИмеетТип("Массив"); - + КонецПроцедуры Процедура Проверка_ТелеграмВидео(Знач Результат, Знач Текст) @@ -3307,7 +3307,7 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["caption"]).Равно(Текст); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["video"]["mime_type"]).Равно("video/mp4"); - + КонецПроцедуры Процедура Проверка_ТелеграмАудио(Знач Результат, Знач Текст) @@ -3316,7 +3316,7 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["caption"]).Равно(Текст); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["audio"]["mime_type"]).Равно("audio/mpeg"); - + КонецПроцедуры Процедура Проверка_ТелеграмДокумент(Знач Результат, Знач Текст) @@ -3324,20 +3324,20 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["caption"]).Равно(Текст); - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["document"]).ИмеетТип("Соответствие").Заполнено(); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["document"]).ИмеетТип("Соответствие").Заполнено(); + КонецПроцедуры Процедура Проверка_ТелеграмГифка(Знач Результат, Знач Текст) Result_ = "result"; - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Result_]["caption"]).Равно(Текст); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Result_]["document"]).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Result_]["animation"]["mime_type"]).Равно("video/mp4"); - + КонецПроцедуры Процедура Проверка_ТелеграмМедиагруппа(Знач Результат) @@ -3345,15 +3345,15 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Массив"); - + КонецПроцедуры Процедура Проверка_ТелеграмМестоположение(Знач Результат) OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["location"]).ИмеетТип("Соответствие").Заполнено(); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["location"]).ИмеетТип("Соответствие").Заполнено(); + КонецПроцедуры Процедура Проверка_ТелеграмКонтакт(Знач Результат, Знач Имя) @@ -3362,7 +3362,7 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["contact"]).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["contact"]["first_name"]).Равно(Имя); - + КонецПроцедуры Процедура Проверка_ТелеграмОпрос(Знач Результат, Знач Вопрос) @@ -3371,22 +3371,22 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["poll"]).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["poll"]["question"]).Равно(Вопрос); - + КонецПроцедуры Процедура Проверка_ТелеграмПереслать(Знач Результат, Знач IDСообщения) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["forward_origin"]["message_id"]).Равно(Число(IDСообщения)); - + КонецПроцедуры Процедура Проверка_ТелеграмБан(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["description"]).Равно("Bad Request: can't remove chat owner"); - + КонецПроцедуры Процедура Проверка_ТелеграмПриглашение(Знач Результат, Знач Заголовок, Знач UnixИстечение) @@ -3397,7 +3397,7 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Result_]["member_limit"]).Равно(200); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Result_]["name"]).Равно(Заголовок); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Result_]["expire_date"]).Равно(Число(UnixИстечение)); - + КонецПроцедуры Процедура Проверка_ТелеграмЧисло(Знач Результат) @@ -3405,7 +3405,7 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Число"); - + КонецПроцедуры Процедура Проверка_ТелеграмСозданиеТемы(Знач Результат, Знач Имя, Иконка) @@ -3414,60 +3414,60 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["name"]).Равно(Имя); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["icon_custom_emoji_id"]).Равно(Иконка); - + КонецПроцедуры Процедура Проверка_ВКПост(Знач Результат) OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["post_id"]).ИмеетТип("Число").Заполнено(); - + КонецПроцедуры Процедура Проверка_ВКИстина(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]).ИмеетТип("Число").Равно(1); - + КонецПроцедуры Процедура Проверка_ВКАльбом(Знач Результат, Знач Описание) OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["description"]).Равно(Описание); - + КонецПроцедуры Процедура Проверка_ВККартинкаАльбома(Знач Результат, Знач ОписаниеКартинки, Знач ИДАльбома) Response = "response"; - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Response][0]["text"]).Равно(ОписаниеКартинки); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Response][0]["album_id"]).Равно(ИДАльбома); - + КонецПроцедуры Процедура Проверка_ВКИстория(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["count"]).ИмеетТип("Число").Равно(1); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["items"]).ИмеетТип("Массив").Заполнено(); - + КонецПроцедуры Процедура Проверка_ВКОбсуждение(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]).ИмеетТип("Число").Заполнено(); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]).ИмеетТип("Число").Заполнено(); + КонецПроцедуры Процедура Проверка_ВКЛайк(Знач Результат) OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["likes"]).ИмеетТип("Число").Заполнено(); - + КонецПроцедуры Процедура Проверка_ВКРепост(Знач Результат) @@ -3475,37 +3475,37 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["success"]).ИмеетТип("Число").Равно(1); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["wall_repost_count"]).ИмеетТип("Число").Равно(1); - + КонецПроцедуры Процедура Проверка_ВККомментарий(Знач Результат) OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["comment_id"]).ИмеетТип("Число").Заполнено(); - + КонецПроцедуры Процедура Проверка_ВКСтатистика(Знач Результат) - + ТипСоответствие = "Соответствие"; - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип(ТипСоответствие).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"][0]["visitors"]).ИмеетТип(ТипСоответствие).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"][0]["reach"]).ИмеетТип(ТипСоответствие).Заполнено(); - + КонецПроцедуры Процедура Проверка_ВКСтатистикаПостов(Знач Результат) OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Массив").ИмеетДлину(2); - + КонецПроцедуры Процедура Проверка_ВКЧисло(Знач Результат) - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие"); + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]).ИмеетТип("Число").Заполнено(); - + КонецПроцедуры Процедура Проверка_ВКПодборка(Знач Результат) @@ -3513,59 +3513,59 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["albums_count"]).ИмеетТип("Число").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["market_album_id"]).ИмеетТип("Число").Заполнено(); - + КонецПроцедуры Процедура Проверка_ВКТовар(Знач Результат) OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["market_item_id"]).ИмеетТип("Число").Заполнено(); - + КонецПроцедуры Процедура Проверка_ВКСвойство(Знач Результат) OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["property_id"]).ИмеетТип("Число").Заполнено(); - + КонецПроцедуры Процедура Проверка_ВКВариантСвойства(Знач Результат) OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["variant_id"]).ИмеетТип("Число").Заполнено(); - + КонецПроцедуры Процедура Проверка_ВКИНформацияОТоварах(Знач Результат) OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["items"]).ИмеетТип("Массив").ИмеетДлину(2); - + КонецПроцедуры Процедура Проверка_ВКГруппаТоваров(Знач Результат) OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["item_group_id"]).ИмеетТип("Число").Заполнено(); - + КонецПроцедуры Процедура Проверка_ВКВидео(Знач Результат) OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["video_id"]).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["video_hash"]).Заполнено(); - + КонецПроцедуры Процедура Проверка_ЯДискДиск(Знач Результат) Соответствие_ = "Соответствие"; - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип(Соответствие_).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["system_folders"]).ИмеетТип(Соответствие_); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["user"]).ИмеетТип(Соответствие_); - + КонецПроцедуры Процедура Проверка_ЯДискКаталог(Знач Результат, Знач Путь) @@ -3573,69 +3573,69 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["type"]).Равно("dir"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["path"]).Равно("disk:" + Путь); - + КонецПроцедуры Процедура Проверка_ГКОбъект(Знач Результат, Знач Наименование, Знач Описание) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["summary"]).Равно(Наименование); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["description"]).Равно(Описание); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["id"]).ИмеетТип("Строка").Заполнено(); - + КонецПроцедуры Процедура Проверка_ТвиттерТекст(Знач Результат, Знач Текст) - + ТекстОтвета = Результат["data"]["text"]; ТекстОтвета = Лев(ТекстОтвета, СтрДлина(Текст)); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(ТекстОтвета).Равно(Текст); КонецПроцедуры Процедура Проверка_ВайберОк(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["status_message"]).Равно("ok"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["status"]).Равно(0); КонецПроцедуры Процедура Проверка_НоушнОбъект(Знач Результат, Знач Вид = "page") - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["object"]).Равно(Вид); - + КонецПроцедуры Процедура Проверка_СлакОк(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); КонецПроцедуры Процедура Проверка_ДропБоксФайл(Знач Результат, Знач Путь) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["path_display"]).Равно(Путь); - + КонецПроцедуры Процедура Проверка_ДропБоксМетаданные(Знач Результат, Знач Путь) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["metadata"]["path_display"]).Равно(Путь); - + КонецПроцедуры Процедура Проверка_ДропБоксМассив(Знач Результат, Знач Количество = Неопределено) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["entries"]).ИмеетТип("Массив"); - + Если Не Количество = Неопределено Тогда OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["entries"].Количество()).Равно(Количество); КонецЕсли; - + КонецПроцедуры Процедура Проверка_ДропБоксРабота(Знач Результат) @@ -3647,10 +3647,10 @@ КонецПроцедуры Процедура Проверка_ДропБоксТеги(Знач Результат, Знач Количество) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["paths_to_tags"]).ИмеетТип("Массив"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["paths_to_tags"].Количество()).Равно(Количество); - + КонецПроцедуры Процедура Проверка_ДропбоксАккаунт(Знач Результат) @@ -3673,38 +3673,38 @@ КонецПроцедуры Процедура Проверка_БитриксВремя(Знач Результат) - + Время = Результат["result"]; - + Если Не ТипЗнч(Время) = Тип("Дата") Тогда Время = XMLЗначение(Тип("Дата"), Время); КонецЕсли; - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Время).ИмеетТип("Дата").Заполнено(); - + КонецПроцедуры Процедура Проверка_БитриксАвторизация(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["access_token"]).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["refresh_token"]).Заполнено(); КонецПроцедуры Процедура Проверка_БитриксЧисло(Знач Результат) - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Число").Заполнено(); + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Число").Заполнено(); КонецПроцедуры Процедура Проверка_БитриксИстина(Знач Результат) - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Булево").Равно(Истина); -КонецПроцедуры + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Булево").Равно(Истина); +КонецПроцедуры Процедура Проверка_БитриксБулево(Знач Результат) - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Булево"); + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Булево"); КонецПроцедуры Процедура Проверка_БитриксСтрока(Знач Результат) - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Строка").Заполнено(); + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Строка").Заполнено(); КонецПроцедуры Процедура Проверка_БитриксМассив(Знач Результат) @@ -3720,22 +3720,22 @@ КонецПроцедуры Процедура Проверка_БитриксМассивОбъектов(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Массив"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"][0]["ID"]).Заполнено(); - + КонецПроцедуры Процедура Проверка_БитриксПоля(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["fields"]).Заполнено(); - + КонецПроцедуры Процедура Проверка_БитриксЗадача(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["task"]).Заполнено(); - + КонецПроцедуры Процедура Проверка_БитриксСписокЗадач(Знач Результат) @@ -3758,75 +3758,75 @@ КонецПроцедуры Процедура Проверка_БитриксДоступныеДействия(Знач Результат, Знач Количество) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Соответствие"); - + Действия = Результат["result"]["allowedActions"]; OPI_ПолучениеДанныхТестов.ОжидаетЧто(Действия).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Действия.Количество()).Равно(Количество); - + КонецПроцедуры Процедура Проверка_БитриксКомментарий(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["POST_MESSAGE"]).Заполнено(); - + КонецПроцедуры Процедура Проверка_БитриксРезультат(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["text"]).Заполнено(); КонецПроцедуры Процедура Проверка_БитриксНеопределено(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Неопределено"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["time"]).Заполнено(); КонецПроцедуры Процедура Проверка_БитриксСписокКомментариев(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Массив"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"][0]["POST_MESSAGE"]).Заполнено(); - + КонецПроцедуры Процедура Проверка_БитриксСписокРезультатов(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Массив"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"][0]["text"]).Заполнено(); - + КонецПроцедуры Процедура Проверка_БитриксСообщения(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["messages"]).ИмеетТип("Массив"); - + КонецПроцедуры Процедура Проверка_БитриксДиалог(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["dialogId"]).Заполнено(); - + КонецПроцедуры Процедура Проверка_БитриксСообщение(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["id"]).Заполнено(); - + КонецПроцедуры Процедура Проверка_БитриксФайлСообщение(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["MESSAGE_ID"]).Заполнено(); - + КонецПроцедуры #КонецОбласти @@ -3839,90 +3839,90 @@ Токен = ПараметрыФункции["Telegram_Token"]; Результат = OPI_Telegram.ПолучитьИнформациюБота(Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИнформациюБота", "Telegram"); - + Проверка_ТелеграмИнформацияБота(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ПолучитьОбновления(ПараметрыФункции) - - Токен = ПараметрыФункции["Telegram_Token"]; + + Токен = ПараметрыФункции["Telegram_Token"]; Результат = OPI_Telegram.ПолучитьОбновления(Токен); // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьОбновления", "Telegram"); - + Проверка_ТелеграмМассив(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_УстановитьWebhook(ПараметрыФункции) - + Токен = ПараметрыФункции["Telegram_Token"]; URL = ПараметрыФункции["Telegram_URL"]; - + Результат = OPI_Telegram.УстановитьWebhook(Токен, URL); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УстановитьWebhook", "Telegram"); - + Проверка_ТелеграмУстановкаВебхук(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_УдалитьWebhook(ПараметрыФункции) - + Токен = ПараметрыФункции["Telegram_Token"]; Результат = OPI_Telegram.УдалитьWebhook(Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьWebhook", "Telegram"); - + Проверка_ТелеграмУдалениеВебхук(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ОтправитьТекстовоеСообщение(ПараметрыФункции) - + Токен = ПараметрыФункции["Telegram_Token"]; IDЧата = ПараметрыФункции["Telegram_ChatID"]; - IDКанала = ПараметрыФункции["Telegram_ChannelID"]; + IDКанала = ПараметрыФункции["Telegram_ChannelID"]; Текст = ПараметрыФункции["String"]; - + Результат = OPI_Telegram.ОтправитьТекстовоеСообщение(Токен, IDЧата, Текст); - - OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьТекстовоеСообщение", "Telegram"); - + + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьТекстовоеСообщение", "Telegram"); + Проверка_ТелеграмСообщение(Результат, Текст); // SKIP - + Результат = OPI_Telegram.ОтправитьТекстовоеСообщение(Токен, IDКанала, Текст); - + // END - - OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьТекстовоеСообщение (канал)"); - + + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьТекстовоеСообщение (канал)"); + Проверка_ТелеграмСообщение(Результат, Текст); - + IDСообщения = OPI_Инструменты.ЧислоВСтроку(Результат["result"]["message_id"]); OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Telegram_ChannelMessageID", IDСообщения); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ОтправитьКартинку(ПараметрыФункции) @@ -3931,42 +3931,42 @@ IDЧата = ПараметрыФункции["Telegram_ChatID"]; IDКанала = ПараметрыФункции["Telegram_ChannelID"]; Текст = ПараметрыФункции["String"]; - Картинка = ПараметрыФункции["Picture"]; - + Картинка = ПараметрыФункции["Picture"]; + КартинкаПуть = ПолучитьИмяВременногоФайла("png"); КопироватьФайл(Картинка, КартинкаПуть); - + КартинкаДД = Новый ДвоичныеДанные(КартинкаПуть); - + Результат = OPI_Telegram.ОтправитьКартинку(Токен, IDЧата, Текст, Картинка); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьКартинку", "Telegram"); - + Проверка_ТелеграмКартинка(Результат, Текст); // SKIP - + Результат = OPI_Telegram.ОтправитьКартинку(Токен, IDКанала, Текст, КартинкаПуть); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьКартинку (Путь)"); - + Проверка_ТелеграмКартинка(Результат, Текст); // SKIP - + Результат = OPI_Telegram.ОтправитьКартинку(Токен, IDКанала, Текст, КартинкаДД); - - // END - + + // END + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьКартинку (ДД)"); - + Проверка_ТелеграмКартинка(Результат, Текст); - + УдалитьФайлы(КартинкаПуть); - + IDФайла = Результат["result"]["photo"][0]["file_id"]; OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Telegram_FileID", IDФайла); - + ПараметрыФункции.Вставить("Telegram_FileID", IDФайла); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ОтправитьВидео(ПараметрыФункции) @@ -3976,41 +3976,41 @@ IDКанала = ПараметрыФункции["Telegram_ChannelID"]; Текст = ПараметрыФункции["String"]; Видео = ПараметрыФункции["Video"]; - + ВидеоПуть = ПолучитьИмяВременногоФайла("mp4"); КопироватьФайл(Видео, ВидеоПуть); - + ВидеоДД = Новый ДвоичныеДанные(ВидеоПуть); - + Результат = OPI_Telegram.ОтправитьВидео(Токен, IDЧата, Текст, Видео); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьВидео", "Telegram"); - + Проверка_ТелеграмВидео(Результат, Текст); // SKIP - + Результат = OPI_Telegram.ОтправитьВидео(Токен, IDКанала, Текст, ВидеоПуть); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьВидео (Путь)"); - + Проверка_ТелеграмВидео(Результат, Текст); // SKIP - + Результат = OPI_Telegram.ОтправитьВидео(Токен, IDКанала, Текст, ВидеоДД); - - // END - + + // END + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьВидео (ДД)"); - + Проверка_ТелеграмВидео(Результат, Текст); - + УдалитьФайлы(ВидеоПуть); - + IDФайла = Результат["result"]["video"]["file_id"]; OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Telegram_FileID", IDФайла); - + ПараметрыФункции.Вставить("Telegram_FileID", IDФайла); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ОтправитьАудио(ПараметрыФункции) @@ -4020,41 +4020,41 @@ IDКанала = ПараметрыФункции["Telegram_ChannelID"]; Текст = ПараметрыФункции["String"]; Аудио = ПараметрыФункции["Audio"]; - + АудиоПуть = ПолучитьИмяВременногоФайла("mp3"); КопироватьФайл(Аудио, АудиоПуть); - + АудиоДД = Новый ДвоичныеДанные(АудиоПуть); - + Результат = OPI_Telegram.ОтправитьАудио(Токен, IDЧата, Текст, Аудио); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьАудио", "Telegram"); - + Проверка_ТелеграмАудио(Результат, Текст); // SKIP - + Результат = OPI_Telegram.ОтправитьАудио(Токен, IDКанала, Текст, АудиоПуть); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьАудио (Путь)"); - + Проверка_ТелеграмАудио(Результат, Текст); // SKIP - + Результат = OPI_Telegram.ОтправитьАудио(Токен, IDКанала, Текст, АудиоДД); - - // END - + + // END + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьАудио (ДД)"); - + Проверка_ТелеграмАудио(Результат, Текст); - + УдалитьФайлы(АудиоПуть); - + IDФайла = Результат["result"]["audio"]["file_id"]; OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Telegram_FileID", IDФайла); - + ПараметрыФункции.Вставить("Telegram_FileID", IDФайла); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ОтправитьДокумент(ПараметрыФункции) @@ -4064,42 +4064,42 @@ IDКанала = ПараметрыФункции["Telegram_ChannelID"]; Текст = ПараметрыФункции["String"]; Документ = ПараметрыФункции["Document"]; - + ДокументПуть = ПолучитьИмяВременногоФайла("docx"); КопироватьФайл(Документ, ДокументПуть); - + ДокументДД = Новый ДвоичныеДанные(ДокументПуть); - + Результат = OPI_Telegram.ОтправитьДокумент(Токен, IDЧата, Текст, Документ); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьДокумент", "Telegram"); - + Проверка_ТелеграмДокумент(Результат, Текст); // SKIP - + Результат = OPI_Telegram.ОтправитьДокумент(Токен, IDЧата, Текст, Документ, , , "customname.docx"); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьДокумент (с именем)", "Telegram"); - + Проверка_ТелеграмДокумент(Результат, Текст); // SKIP - + Результат = OPI_Telegram.ОтправитьДокумент(Токен, IDКанала, Текст, ДокументПуть); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьДокумент (Путь)"); - + Проверка_ТелеграмДокумент(Результат, Текст); // SKIP - + Результат = OPI_Telegram.ОтправитьДокумент(Токен, IDКанала, Текст, ДокументДД, , , "customname.docx"); - - // END - + + // END + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьДокумент (ДД)"); - + Проверка_ТелеграмДокумент(Результат, Текст); - + УдалитьФайлы(ДокументПуть); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ОтправитьГифку(ПараметрыФункции) @@ -4109,36 +4109,36 @@ IDКанала = ПараметрыФункции["Telegram_ChannelID"]; Текст = ПараметрыФункции["String"]; Гифка = ПараметрыФункции["GIF"]; - + ГифкаПуть = ПолучитьИмяВременногоФайла("gif"); КопироватьФайл(Гифка, ГифкаПуть); - + ГифкаДД = Новый ДвоичныеДанные(ГифкаПуть); - + Результат = OPI_Telegram.ОтправитьГифку(Токен, IDЧата, Текст, Гифка); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьГифку", "Telegram"); - + Проверка_ТелеграмГифка(Результат, Текст); // SKIP - + Результат = OPI_Telegram.ОтправитьГифку(Токен, IDКанала, Текст, ГифкаПуть); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьГифку (Путь)"); - + Проверка_ТелеграмГифка(Результат, Текст); // SKIP - + Результат = OPI_Telegram.ОтправитьГифку(Токен, IDКанала, Текст, ГифкаДД); - - // END - + + // END + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьГифку (ДД)"); - + Проверка_ТелеграмГифка(Результат, Текст); - + УдалитьФайлы(ГифкаПуть); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ОтправитьМеидагруппу(ПараметрыФункции) @@ -4148,157 +4148,157 @@ Текст = ПараметрыФункции["String"]; Картинка = ПараметрыФункции["Picture"]; Видео = ПараметрыФункции["Video"]; - + КартинкаПуть = ПолучитьИмяВременногоФайла("png"); КопироватьФайл(Картинка, КартинкаПуть); - + ВидеоПуть = ПолучитьИмяВременногоФайла("mp4"); КопироватьФайл(Видео, ВидеоПуть); - + ВидеоДД = Новый ДвоичныеДанные(ВидеоПуть); - + Медиагруппа = Новый Соответствие; Медиагруппа.Вставить(КартинкаПуть, "photo"); Медиагруппа.Вставить(ВидеоДД , "video"); - + Результат = OPI_Telegram.ОтправитьМедиагруппу(Токен, IDЧата, Текст, Медиагруппа); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьМедиагруппу", "Telegram"); - + Проверка_ТелеграмМедиагруппа(Результат); - - ДокументURL = ПараметрыФункции["Document"]; + + ДокументURL = ПараметрыФункции["Document"]; ДокументПуть = ПолучитьИмяВременногоФайла("docx"); IDКанала = ПараметрыФункции["Telegram_ChannelID"]; - + КопироватьФайл(ДокументURL, ДокументПуть); - + МедиаГруппа = Новый Соответствие; Медиагруппа.Вставить(ДокументURL , "document"); - Медиагруппа.Вставить(ДокументПуть, "document"); - + Медиагруппа.Вставить(ДокументПуть, "document"); + Результат = OPI_Telegram.ОтправитьМедиагруппу(Токен, IDКанала, Текст, Медиагруппа); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьМедиагруппу (доки)", "Telegram"); - + Проверка_ТелеграмМедиагруппа(Результат); - + УдалитьФайлы(ВидеоПуть); УдалитьФайлы(КартинкаПуть); УдалитьФайлы(ДокументПуть); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ОтправитьМестоположение(ПараметрыФункции) - + Токен = ПараметрыФункции["Telegram_Token"]; IDЧата = ПараметрыФункции["Telegram_ChatID"]; - IDКанала = ПараметрыФункции["Telegram_ChannelID"]; + IDКанала = ПараметрыФункции["Telegram_ChannelID"]; Ширина = ПараметрыФункции["Lat"]; Долгота = ПараметрыФункции["Long"]; - + Результат = OPI_Telegram.ОтправитьМестоположение(Токен, IDЧата, Ширина, Долгота); - - OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьМестоположение", "Telegram"); - + + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьМестоположение", "Telegram"); + Проверка_ТелеграмМестоположение(Результат); // SKIP - + Результат = OPI_Telegram.ОтправитьМестоположение(Токен, IDКанала, Ширина, Долгота); - + // END - - OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьМестоположение (канал)"); - + + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьМестоположение (канал)"); + Проверка_ТелеграмМестоположение(Результат); OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ОтправитьКонтакт(ПараметрыФункции) Токен = ПараметрыФункции["Telegram_Token"]; IDЧата = ПараметрыФункции["Telegram_ChatID"]; - IDКанала = ПараметрыФункции["Telegram_ChannelID"]; + IDКанала = ПараметрыФункции["Telegram_ChannelID"]; Имя = ПараметрыФункции["Name"]; Фамилия = ПараметрыФункции["Surname"]; Телефон = ПараметрыФункции["Phone"]; - + Результат = OPI_Telegram.ОтправитьКонтакт(Токен, IDЧата , Имя, Фамилия, Телефон); - - OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьКонтакт", "Telegram"); - + + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьКонтакт", "Telegram"); + Проверка_ТелеграмКонтакт(Результат, Имя); // SKIP OPI_Инструменты.Пауза(20); // SKIP - + Результат = OPI_Telegram.ОтправитьКонтакт(Токен, IDКанала, Имя, Фамилия, Телефон); - + // END - - OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьКонтакт (канал)"); - + + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьКонтакт (канал)"); + Проверка_ТелеграмКонтакт(Результат, Имя); OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ОтправитьОпрос(ПараметрыФункции) Токен = ПараметрыФункции["Telegram_Token"]; IDЧата = ПараметрыФункции["Telegram_ChatID"]; - IDКанала = ПараметрыФункции["Telegram_ChannelID"]; + IDКанала = ПараметрыФункции["Telegram_ChannelID"]; Вопрос = "Какой ваш любимый цвет?"; - + МассивОтветов = Новый Массив; МассивОтветов.Добавить("Красный"); МассивОтветов.Добавить("Желтый"); МассивОтветов.Добавить("Зеленый"); МассивОтветов.Добавить("Синий"); - + Результат = OPI_Telegram.ОтправитьОпрос(Токен, IDЧата , Вопрос, МассивОтветов, Ложь); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьОпрос", "Telegram"); - + Проверка_ТелеграмОпрос(Результат, Вопрос); // SKIP - + Результат = OPI_Telegram.ОтправитьОпрос(Токен, IDКанала, Вопрос, МассивОтветов, Истина); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьОпрос (канал)"); - + Проверка_ТелеграмОпрос(Результат, Вопрос); // SKIP - + // END - + СтрочныйМассив = "['Красный', 'Желтый','Зеленый' ,'Синий']"; - + Результат = OPI_Telegram.ОтправитьОпрос(Токен, IDКанала, Вопрос, СтрочныйМассив, Истина); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьОпрос (строчный массив)"); - + Проверка_ТелеграмОпрос(Результат, Вопрос); OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_СкачатьФайл(ПараметрыФункции) - + IDФайла = ПараметрыФункции["Telegram_FileID"]; Токен = ПараметрыФункции["Telegram_Token"]; Результат = OPI_Telegram.СкачатьФайл(Токен, IDФайла); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СкачатьФайл", "Telegram"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("ДвоичныеДанные"); - + КонецПроцедуры Процедура Telegram_ПереслатьСообщение(ПараметрыФункции) @@ -4307,74 +4307,74 @@ IDЧата = ПараметрыФункции["Telegram_ChatID"]; IDКанала = ПараметрыФункции["Telegram_ChannelID"]; IDСообщения = ПараметрыФункции["Telegram_ChannelMessageID"]; - + Результат = OPI_Telegram.ПереслатьСообщение(Токен, IDСообщения, IDКанала, IDЧата); - + // END OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереслатьСообщение", "Telegram"); - + Проверка_ТелеграмПереслать(Результат, IDСообщения); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_Бан(ПараметрыФункции) - - Токен = ПараметрыФункции["Telegram_Token"]; + + Токен = ПараметрыФункции["Telegram_Token"]; IDПользователя = ПараметрыФункции["Telegram_ChatID"]; IDКанала = ПараметрыФункции["Telegram_ChannelID"]; - + Результат = OPI_Telegram.Бан(Токен, IDКанала, IDПользователя); // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "Бан", "Telegram"); - + Проверка_ТелеграмБан(Результат); OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_Разбан(ПараметрыФункции) - + Токен = ПараметрыФункции["Telegram_Token"]; IDПользователя = ПараметрыФункции["Telegram_ChatID"]; IDКанала = ПараметрыФункции["Telegram_ChannelID"]; - + Результат = OPI_Telegram.Разбан(Токен, IDКанала, IDПользователя); // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "Разбан", "Telegram"); - + Проверка_ТелеграмБан(Результат); OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_СоздатьСсылкуПриглашение(ПараметрыФункции) Токен = ПараметрыФункции["Telegram_Token"]; - IDКанала = ПараметрыФункции["Telegram_ChannelID"]; - Сутки = 86400; + IDКанала = ПараметрыФункции["Telegram_ChannelID"]; + Сутки = 86400; ТекущаяДата = OPI_Инструменты.ПолучитьТекущуюДату(); - Заголовок = "Ссылка " + Строка(ТекущаяДата); + Заголовок = "Ссылка " + Строка(ТекущаяДата); Истечение = ТекущаяДата + Сутки; UnixИстечение = OPI_Инструменты.UNIXTime(Истечение); - + Результат = OPI_Telegram.СоздатьСсылкуПриглашение(Токен, IDКанала, Заголовок, Истечение, 200); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьСсылкуПриглашение", "Telegram"); Проверка_ТелеграмПриглашение(Результат, Заголовок, UnixИстечение); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ЗакрепитьСообщение(ПараметрыФункции) @@ -4382,17 +4382,17 @@ Токен = ПараметрыФункции["Telegram_Token"]; IDКанала = ПараметрыФункции["Telegram_ChannelID"]; IDСообщения = ПараметрыФункции["Telegram_ChannelMessageID"]; - + Результат = OPI_Telegram.ЗакрепитьСообщение(Токен, IDКанала, IDСообщения); // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗакрепитьСообщение", "Telegram"); - + Проверка_ТелеграмИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ОткрепитьСообщение(ПараметрыФункции) @@ -4400,262 +4400,262 @@ Токен = ПараметрыФункции["Telegram_Token"]; IDКанала = ПараметрыФункции["Telegram_ChannelID"]; IDСообщения = ПараметрыФункции["Telegram_ChannelMessageID"]; - + Результат = OPI_Telegram.ОткрепитьСообщение(Токен, IDКанала, IDСообщения); // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОткрепитьСообщение", "Telegram"); - + Проверка_ТелеграмИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ПолучитьЧислоУчастников(ПараметрыФункции) - + Токен = ПараметрыФункции["Telegram_Token"]; IDКанала = ПараметрыФункции["Telegram_ChannelID"]; - + Результат = OPI_Telegram.ПолучитьЧислоУчастников(Токен, IDКанала); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьЧислоУчастников", "Telegram"); - + Проверка_ТелеграмЧисло(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ПолучитьСписокАватаровФорума(ПараметрыФункции) - + Токен = ПараметрыФункции["Telegram_Token"]; Результат = OPI_Telegram.ПолучитьСписокИконокАватаров(Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокИконокАватаров", "Telegram"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_СоздатьТемуФорума(ПараметрыФункции) - - Токен = ПараметрыФункции["Telegram_Token"]; + + Токен = ПараметрыФункции["Telegram_Token"]; Чат = ПараметрыФункции["Telegram_ForumID"]; Иконка = "5357419403325481346"; Имя = "Тестовая тема " + Строка(Новый УникальныйИдентификатор); - + Результат = OPI_Telegram.СоздатьТемуФорума(Токен, Чат, Имя, Иконка); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьТемуФорума", "Telegram"); - + Тема = Результат["result"]["message_thread_id"]; - + ПараметрыФункции.Вставить("Telegram_TopicID", Тема); OPI_Инструменты.ДобавитьПоле("Telegram_TopicID", Тема, "Строка", ПараметрыФункции); OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Telegram_TopicID", ПараметрыФункции["Telegram_TopicID"]); - + Проверка_ТелеграмСозданиеТемы(Результат, Имя, Иконка); - - ЧатТема = Чат + "*" + Тема; - Текст = ПараметрыФункции["String"]; + + ЧатТема = Чат + "*" + Тема; + Текст = ПараметрыФункции["String"]; Результат = OPI_Telegram.ОтправитьТекстовоеСообщение(Токен, ЧатТема, Текст); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьТекстовоеСообщение (форум)"); - + Проверка_ТелеграмСообщение(Результат, Текст); - + КонецПроцедуры Процедура Telegram_ИзменитьТемуФорума(ПараметрыФункции) - Токен = ПараметрыФункции["Telegram_Token"]; + Токен = ПараметрыФункции["Telegram_Token"]; Чат = ПараметрыФункции["Telegram_ForumID"]; Тема = ПараметрыФункции["Telegram_TopicID"]; НовоеИмя = "Новый тестовый заголовок"; НовяИконка = "5310132165583840589"; Результат = OPI_Telegram.ИзменитьТемуФорума(Токен, Чат, Тема, НовоеИмя, НовяИконка); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьТемуФорума", "Telegram"); - + Проверка_ТелеграмИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ЗакрытьТемуФорума(ПараметрыФункции) - Токен = ПараметрыФункции["Telegram_Token"]; + Токен = ПараметрыФункции["Telegram_Token"]; Чат = ПараметрыФункции["Telegram_ForumID"]; Тема = ПараметрыФункции["Telegram_TopicID"]; OPI_Telegram.ОткрытьТемуФорума(Токен, Чат); // SKIP - + Результат = OPI_Telegram.ЗакрытьТемуФорума(Токен, Чат); // Закрывает главную тему - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗакрытьТемуФорума (главная)"); - + Проверка_ТелеграмИстина(Результат); // SKIP - + Результат = OPI_Telegram.ЗакрытьТемуФорума(Токен, Чат, Тема); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗакрытьТемуФорума", "Telegram"); - + Проверка_ТелеграмИстина(Результат); - + OPI_Инструменты.Пауза(25); - + КонецПроцедуры Процедура Telegram_ОткрытьТемуФорума(ПараметрыФункции) - Токен = ПараметрыФункции["Telegram_Token"]; + Токен = ПараметрыФункции["Telegram_Token"]; Чат = ПараметрыФункции["Telegram_ForumID"]; Тема = ПараметрыФункции["Telegram_TopicID"]; Результат = OPI_Telegram.ОткрытьТемуФорума(Токен, Чат); // Открывает главную тему - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОткрытьТемуФорума (главная)"); - + Проверка_ТелеграмИстина(Результат); // SKIP - + Результат = OPI_Telegram.ОткрытьТемуФорума(Токен, Чат, Тема); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОткрытьТемуФорума", "Telegram"); - + Проверка_ТелеграмИстина(Результат); - + OPI_Инструменты.Пауза(25); - + КонецПроцедуры Процедура Telegram_УдалитьТемуФорума(ПараметрыФункции) - Токен = ПараметрыФункции["Telegram_Token"]; + Токен = ПараметрыФункции["Telegram_Token"]; Чат = ПараметрыФункции["Telegram_ForumID"]; Тема = ПараметрыФункции["Telegram_TopicID"]; - - Результат = OPI_Telegram.УдалитьТемуФорума(Токен, Чат, Тема); - + + Результат = OPI_Telegram.УдалитьТемуФорума(Токен, Чат, Тема); + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьТемуФорума", "Telegram"); - + Проверка_ТелеграмИстина(Результат); - + OPI_Инструменты.Пауза(25); - + КонецПроцедуры Процедура Telegram_ОчиститьСписокЗакрепленныхСообщенийТемы(ПараметрыФункции) - Токен = ПараметрыФункции["Telegram_Token"]; + Токен = ПараметрыФункции["Telegram_Token"]; Чат = ПараметрыФункции["Telegram_ForumID"]; Тема = ПараметрыФункции["Telegram_TopicID"]; - + Результат = OPI_Telegram.ОчиститьСписокЗакрепленныхСообщенийТемы(Токен, Чат); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОчиститьСписокЗакрепленныхСообщенийТемы (главная)"); - + Проверка_ТелеграмИстина(Результат); // SKIP - + Результат = OPI_Telegram.ОчиститьСписокЗакрепленныхСообщенийТемы(Токен, Чат, Тема); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОчиститьСписокЗакрепленныхСообщенийТемы", "Telegram"); - + Проверка_ТелеграмИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_СкрытьГлавнуюТемуФорума(ПараметрыФункции) - Токен = ПараметрыФункции["Telegram_Token"]; + Токен = ПараметрыФункции["Telegram_Token"]; Чат = ПараметрыФункции["Telegram_ForumID"]; - + Результат = OPI_Telegram.СкрытьГлавнуюТемуФорума(Токен, Чат); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СкрытьГлавнуюТемуФорума", "Telegram"); - + Проверка_ТелеграмИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ПоказатьГлавнуюТемуФорума(ПараметрыФункции) - Токен = ПараметрыФункции["Telegram_Token"]; + Токен = ПараметрыФункции["Telegram_Token"]; Чат = ПараметрыФункции["Telegram_ForumID"]; - + Результат = OPI_Telegram.ПоказатьГлавнуюТемуФорума(Токен, Чат); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПоказатьГлавнуюТемуФорума", "Telegram"); - + Проверка_ТелеграмИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ИзменитьИмяГлавнойТемыФорума(ПараметрыФункции) - Заголовок = "Новое имя главной темы " + Строка(Новый УникальныйИдентификатор); - Токен = ПараметрыФункции["Telegram_Token"]; - Чат = ПараметрыФункции["Telegram_ForumID"]; - + Заголовок = "Новое имя главной темы " + Строка(Новый УникальныйИдентификатор); + Токен = ПараметрыФункции["Telegram_Token"]; + Чат = ПараметрыФункции["Telegram_ForumID"]; + Результат = OPI_Telegram.ИзменитьИмяГлавнойТемыФорума(Токен, Чат, Заголовок); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьИмяГлавнойТемыФорума", "Telegram"); - + Проверка_ТелеграмИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_УдалитьСообщение(ПараметрыФункции) - - Токен = ПараметрыФункции["Telegram_Token"]; - IDЧата = ПараметрыФункции["Telegram_ChannelID"]; + + Токен = ПараметрыФункции["Telegram_Token"]; + IDЧата = ПараметрыФункции["Telegram_ChannelID"]; IDСообщения = ПараметрыФункции["Telegram_ChannelMessageID"]; - + Результат = OPI_Telegram.УдалитьСообщение(Токен, IDЧата, IDСообщения); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьСообщение", "Telegram"); - + Проверка_ТелеграмИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры #КонецОбласти @@ -4666,82 +4666,82 @@ Приложение = ПараметрыФункции["VK_AppID"]; Результат = OPI_VK.СоздатьСсылкуПолученияТокена(Приложение); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьСсылкуПолученияТокена", "VK"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Строка").Заполнено(); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_СоздатьПост(ПараметрыФункции) - + Параметры = ПолучитьПараметрыВК(); Текст = "Пост из автотеста"; URL = "https://github.com/Bayselonarrend/OpenIntegrations"; - + Картинка = ПараметрыФункции["Picture"]; // URL, Путь или Двоичные данные Картинка2 = ПараметрыФункции["Picture2"]; // URL, Путь или Двоичные данные - - ИВФ = ПолучитьИмяВременногоФайла("png"); + + ИВФ = ПолучитьИмяВременногоФайла("png"); КопироватьФайл(Картинка2, ИВФ); - + МассивКартинок = Новый Массив; МассивКартинок.Добавить(Картинка); МассивКартинок.Добавить(ИВФ); - + Результат = OPI_VK.СоздатьПост(Текст, МассивКартинок, Истина, URL, Параметры); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьПост", "VK"); Проверка_ВКПост(Результат); // SKIP ИДПоста = Результат["response"]["post_id"]; // SKIP Результат = OPI_VK.УдалитьПост(ИДПоста, Параметры); // SKIP - + Результат = OPI_VK.СоздатьПост(Текст, Картинка, Ложь , , Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьПост (одна картинка)"); - Проверка_ВКПост(Результат); - - ИДПоста = Результат["response"]["post_id"]; - Результат = OPI_VK.УдалитьПост(ИДПоста, Параметры); - - OPI_Инструменты.Пауза(5); - + Проверка_ВКПост(Результат); + + ИДПоста = Результат["response"]["post_id"]; + Результат = OPI_VK.УдалитьПост(ИДПоста, Параметры); + + OPI_Инструменты.Пауза(5); + Результат = OPI_VK.СоздатьПост(Текст, ИВФ , Истина, URL, Параметры); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьПост (один путь)"); - Проверка_ВКПост(Результат); - + Проверка_ВКПост(Результат); + ИДПоста = Результат["response"]["post_id"]; OPI_Инструменты.ДобавитьПоле("VK_PostID", ИДПоста, "Строка", ПараметрыФункции); OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_PostID", ПараметрыФункции["VK_PostID"]); - + УдалитьФайлы(ИВФ); OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_УдалитьПост(ПараметрыФункции) - + Параметры = ПолучитьПараметрыВК(); ИДПоста = ПараметрыФункции["VK_PostID"]; - + Результат = OPI_VK.УдалитьПост(ИДПоста, Параметры); // END OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьПост", "VK"); - + Проверка_ВКИстина(Результат); - + КонецПроцедуры Процедура VK_СоздатьСоставнойПост(ПараметрыФункции) @@ -4749,154 +4749,154 @@ Параметры = ПолучитьПараметрыВК(); Текст = "Пост из автотеста"; URL = "https://github.com/Bayselonarrend/OpenIntegrations"; - + Картинка = ПараметрыФункции["Picture"]; // URL, Путь или Двоичные данные Видео = ПараметрыФункции["Video"]; // URL, Путь или Двоичные данные - - ИВФ = ПолучитьИмяВременногоФайла("png"); + + ИВФ = ПолучитьИмяВременногоФайла("png"); КопироватьФайл(Картинка, ИВФ); - + ЗагрузкаКартинки = OPI_VK.ЗагрузитьФотоНаСервер(ИВФ, Параметры)["response"][0]; ЗагрузкаВидео = OPI_VK.ЗагрузитьВидеоНаСервер(Видео, "Новое видео", , , Параметры); - + ВладелецКартинки = OPI_Инструменты.ЧислоВСтроку(ЗагрузкаКартинки["owner_id"]); ВладелецВидео = OPI_Инструменты.ЧислоВСтроку(ЗагрузкаВидео["owner_id"]); - + IDКартинки = OPI_Инструменты.ЧислоВСтроку(ЗагрузкаКартинки["id"]); IDВидео = OPI_Инструменты.ЧислоВСтроку(ЗагрузкаВидео["video_id"]); - + МассивВложений = Новый Массив; МассивВложений.Добавить("photo" + ВладелецКартинки + "_" + IDКартинки); МассивВложений.Добавить("video" + ВладелецВидео + "_" + IDВидео); - + Результат = OPI_VK.СоздатьСоставнойПост(Текст, МассивВложений, Ложь, URL, Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьСоставнойПост", "VK"); - + Проверка_ВКПост(Результат); - УдалитьФайлы(ИВФ); - + УдалитьФайлы(ИВФ); + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_СоздатьОпрос() Параметры = ПолучитьПараметрыВК(); Вопрос = "Какой ваш любимый цвет?"; - + МассивВариантов = Новый Массив; МассивВариантов.Добавить("Красный"); МассивВариантов.Добавить("Желтый"); МассивВариантов.Добавить("Зеленый"); - + Результат = OPI_VK.СоздатьОпрос(Вопрос, МассивВариантов, , Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьОпрос", "VK"); - + Проверка_ВКПост(Результат); - + ИДПоста = Результат["response"]["post_id"]; OPI_VK.УдалитьПост(ИДПоста, Параметры); - + OPI_Инструменты.Пауза(10); - + КонецПроцедуры Процедура VK_СоздатьАльбом(ПараметрыФункции) - + Параметры = ПолучитьПараметрыВК(); Имя = "Альбом из автотеста"; Описание = "Новый альбом из автотеста"; - + Результат = OPI_VK.СоздатьАльбом(Имя, Описание, Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьАльбом", "VK"); - + Проверка_ВКАльбом(Результат, Описание); - + ИДАльбома = Результат["response"]["id"]; ПараметрыФункции.Вставить("VK_AlbumID", ИДАльбома); OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_AlbumID", ИДАльбома); - + КонецПроцедуры Процедура VK_СохранитьКартинкуВАльбом(ПараметрыФункции) - + Параметры = ПолучитьПараметрыВК(); ОписаниеКартинки = "Картинка автотест"; ИДАльбома = ПараметрыФункции["VK_AlbumID"]; - + Картинка = ПараметрыФункции["Picture"]; // URL, Путь к файлу или Двоичные данные ИВФ = ПолучитьИмяВременногоФайла("png"); КопироватьФайл(Картинка, ИВФ); - + Картинка = Новый ДвоичныеДанные(ИВФ); - + Результат = OPI_VK.СохранитьКартинкуВАльбом(ИДАльбома, Картинка, ОписаниеКартинки, Параметры); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СохранитьКартинкуВАльбом", "VK"); - + Проверка_ВККартинкаАльбома(Результат, ОписаниеКартинки, ИДАльбома); // SKIP - - ИДКартинки = Результат["response"][0]["id"]; // SKIP + + ИДКартинки = Результат["response"][0]["id"]; // SKIP Результат = OPI_VK.УдалитьКартинку(ИДКартинки, Параметры); // SKIP - + Результат = OPI_VK.СохранитьКартинкуВАльбом(ИДАльбома, ИВФ, ОписаниеКартинки, Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СохранитьКартинкуВАльбом (путь)"); - + Проверка_ВККартинкаАльбома(Результат, ОписаниеКартинки, ИДАльбома); // SKIP - + ИДКартинки = Результат["response"][0]["id"]; ПараметрыФункции.Вставить("VK_PictureID", ИДКартинки); OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_PictureID", ИДКартинки); - + УдалитьФайлы(ИВФ); OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_УдалитьКартинку(ПараметрыФункции) - + Параметры = ПолучитьПараметрыВК(); ИДКартинки = ПараметрыФункции["VK_PictureID"]; - + Результат = OPI_VK.УдалитьКартинку(ИДКартинки, Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьКартинку", "VK"); - + Проверка_ВКИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_УдалитьАльбом(ПараметрыФункции) - + Параметры = ПолучитьПараметрыВК(); ИДАльбома = ПараметрыФункции["VK_AlbumID"]; - + Результат = OPI_VK.УдалитьАльбом(ИДАльбома, Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьАльбом", "VK"); - + Проверка_ВКИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_СоздатьИсторию(ПараметрыФункции) @@ -4908,25 +4908,25 @@ ИВФ = ПолучитьИмяВременногоФайла("png"); КопироватьФайл(Картинка, ИВФ); Картинка = Новый ДвоичныеДанные(ИВФ); - + Результат = OPI_VK.СоздатьИсторию(Картинка , URL, Параметры); OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьИсторию", "VK"); - + Проверка_ВКИстория(Результат); // SKIP - + Результат = OPI_VK.СоздатьИсторию(ИВФ, , Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьИсторию (путь)"); - + Проверка_ВКИстория(Результат); - + УдалитьФайлы(ИВФ); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_СоздатьОбсуждение(ПараметрыФункции) @@ -4934,104 +4934,104 @@ Параметры = ПолучитьПараметрыВК(); Название = "Обсуждаем: какой цвет лучше?"; Сообщение = "Красный, желтый, синий или какой-то другой?"; - + Результат = OPI_VK.СоздатьОбсуждение(Название, Сообщение, Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьОбсуждение", "VK"); - + Проверка_ВКОбсуждение(Результат); - + ИДОбсуждения = Результат["response"]; ПараметрыФункции.Вставить("VK_ConvID", ИДОбсуждения); - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_ConvID", ИДОбсуждения); - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_ConvID", ИДОбсуждения); + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_ЗакрытьОбсуждение(ПараметрыФункции) - + Параметры = ПолучитьПараметрыВК(); ИДОбсуждения = ПараметрыФункции["VK_ConvID"]; Результат = OPI_VK.ЗакрытьОбсуждение(ИДОбсуждения, Ложь, Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗакрытьОбсуждение", "VK"); - + Проверка_ВКИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_ОткрытьОбсуждение(ПараметрыФункции) - + Параметры = ПолучитьПараметрыВК(); ИДОбсуждения = ПараметрыФункции["VK_ConvID"]; Результат = OPI_VK.ОткрытьОбсуждение(ИДОбсуждения, Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОткрытьОбсуждение", "VK"); - + Проверка_ВКИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_НаписатьВОбсуждение(ПараметрыФункции) - + Параметры = ПолучитьПараметрыВК(); ИДОбсуждения = ПараметрыФункции["VK_ConvID"]; Сообщение = "Мне больше нравится желтый"; - + Результат = OPI_VK.НаписатьВОбсуждение(ИДОбсуждения, Сообщение, Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "НаписатьВОбсуждение", "VK"); - + Проверка_ВКОбсуждение(Результат); - + КонецПроцедуры Процедура VK_ПоставитьЛайк(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); IDПоста = ПараметрыФункции["VK_PostID"]; - + Результат = OPI_VK.ПоставитьЛайк(IDПоста, , Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПоставитьЛайк", "VK"); - + Проверка_ВКЛайк(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_СделатьРепост(ПараметрыФункции) - + Параметры = ПолучитьПараметрыВК(); IDПоста = 2571; IDСтены = -218704372; - + Результат = OPI_VK.СделатьРепост(IDПоста, IDСтены, , , Параметры); // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СделатьРепост", "VK"); - + Проверка_ВКРепост(Результат); - + ПараметрыФункции.Вставить("Repost", Результат["response"]["post_id"]); - + OPI_Инструменты.Пауза(5); КонецПроцедуры @@ -5042,78 +5042,78 @@ Текст = "Новый комментарий"; IDПоста = ПараметрыФункции["VK_PostID"]; IDСтены = Параметры["owner_id"]; - + Результат = OPI_VK.НаписатьКомментарий(IDПоста, IDСтены, Текст, Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "НаписатьКомментарий", "VK"); - + Проверка_ВККомментарий(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_ПолучитьСтатистику(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + ТекущаяДата = OPI_Инструменты.ПолучитьТекущуюДату(); ДатаНачала = НачалоДня(ТекущаяДата); ДатаОкончания = КонецДня(ДатаНачала); - + Результат = OPI_VK.ПолучитьСтатистику(ДатаНачала, ДатаОкончания, Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСтатистику", "VK"); - + Проверка_ВКСтатистика(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_ПолучитьСтатистикуПостов(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + МассивПостов = Новый Массив; МассивПостов.Добавить(214); МассивПостов.Добавить(215); - + Результат = OPI_VK.ПолучитьСтатистикуПостов(МассивПостов, Параметры); // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСтатистикуПостов", "VK"); - + Проверка_ВКСтатистикаПостов(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_СоздатьРекламнуюКампанию(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + IDКабинета = ПараметрыФункции["VK_AdsCabinetID"]; Наименование = "Новая кампания"; - + Результат = OPI_VK.СоздатьРекламнуюКампанию(IDКабинета, Наименование, Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьРекламнуюКампанию", "VK"); - + Проверка_Соответствие(Результат); - + ИДКампании = Результат["response"][0]["id"]; OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_AdsCampaignID", ИДКампании); ПараметрыФункции.Вставить("VK_AdsCampaignID", ИДКампании); - + КонецПроцедуры Процедура VK_СоздатьРекламноеОбъявление(ПараметрыФункции) @@ -5125,256 +5125,256 @@ НомерКатегории = 126; IDПоста = ПараметрыФункции["VK_PostID"]; IDКабинета = ПараметрыФункции["VK_AdsCabinetID"]; - + Результат = OPI_VK.СоздатьРекламноеОбъявление(НомерКампании , ДневнойЛимит , НомерКатегории , IDПоста , IDКабинета , Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьРекламноеОбъявление", "VK"); - + Проверка_Соответствие(Результат); - + ИДОбъявления = Результат["response"][0]["id"]; OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_AdsPostID", ИДОбъявления); ПараметрыФункции.Вставить("VK_AdsPostID", ИДОбъявления); - + КонецПроцедуры Процедура VK_ПриостановитьРекламноеОбъявление(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + IDКабинета = ПараметрыФункции["VK_AdsCabinetID"]; IDОбъявления = ПараметрыФункции["VK_AdsPostID"]; - + Результат = OPI_VK.ПриостановитьРекламноеОбъявление(IDКабинета, IDОбъявления, Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПриостановитьРекламноеОбъявление", "VK"); - + Проверка_Соответствие(Результат); - + КонецПроцедуры Процедура VK_СформироватьКлавиатуру(ПараметрыФункции) МассивКнопок = Новый Массив; МассивКнопок.Добавить("Button 1"); - МассивКнопок.Добавить("Button 2"); - + МассивКнопок.Добавить("Button 2"); + Клавиатура = OPI_VK.СформироватьКлавиатуру(МассивКнопок); - + // END - + Проверка_Строка(Клавиатура); - + КонецПроцедуры Процедура VK_НаписатьСообщение(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + Текст = "Сообщение из автотеста"; IDПользователя = ПараметрыФункции["VK_UserID"]; Communitytoken = ПараметрыФункции["VK_CommunityToken"]; - + МассивКнопок = Новый Массив; МассивКнопок.Добавить("Button 1"); - МассивКнопок.Добавить("Button 2"); - + МассивКнопок.Добавить("Button 2"); + Клавиатура = OPI_VK.СформироватьКлавиатуру(МассивКнопок); Результат = OPI_VK.НаписатьСообщение(Текст, IDПользователя, Communitytoken, Клавиатура, Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "НаписатьСообщение", "VK"); - - Проверка_ВКЧисло(Результат); - + + Проверка_ВКЧисло(Результат); + КонецПроцедуры Процедура VK_ПолучитьСписокКатегорийТоваров(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + Результат = OPI_VK.ПолучитьСписокКатегорийТоваров(Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокКатегорийТоваров", "VK"); - + Проверка_Соответствие(Результат); - + КонецПроцедуры Процедура VK_СоздатьПодборкуТоваров(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + Название = "Тестовая подборка"; Картинка = ПараметрыФункции["Picture"]; Основная = Истина; Скрытая = Ложь; - + Результат = OPI_VK.СоздатьПодборкуТоваров(Название , Картинка , Основная , Скрытая - , Параметры); - + , Параметры); + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьПодборкуТоваров", "VK"); - + Проверка_ВКПодборка(Результат); - + OPI_Инструменты.Пауза(5); - + ИДПодборки = Результат["response"]["market_album_id"]; OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_MarketAlbumID", ИДПодборки); ПараметрыФункции.Вставить("VK_MarketAlbumID", ИДПодборки); - + КонецПроцедуры Процедура VK_ИзменитьПодборкуТоваров(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + Название = "Измененная подборка"; - Подборка = ПараметрыФункции["VK_MarketAlbumID"]; - + Подборка = ПараметрыФункции["VK_MarketAlbumID"]; + Результат = OPI_VK.ИзменитьПодборкуТоваров(Название, Подборка, , , , Параметры); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьПодборкуТоваров", "VK"); - + Проверка_ВКИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_ДобавитьТовар(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + Картинка1 = ПараметрыФункции["Picture"]; // URL, Путь к файлу или двоичные данные Картинка2 = ПараметрыФункции["Picture2"]; // URL, Путь к файлу или двоичные данные - Подборка = ПараметрыФункции["VK_MarketAlbumID"]; - + Подборка = ПараметрыФункции["VK_MarketAlbumID"]; + МассивКартинок = Новый Массив; МассивКартинок.Добавить(Картинка1); МассивКартинок.Добавить(Картинка2); - + ОписаниеТовара = Новый Соответствие(); - ОписаниеТовара.Вставить("Имя" , "Тестовый товар"); + ОписаниеТовара.Вставить("Имя" , "Тестовый товар"); ОписаниеТовара.Вставить("Описание" , "Описание товара"); - ОписаниеТовара.Вставить("Категория" , "20173"); - ОписаниеТовара.Вставить("Цена" , 1); - ОписаниеТовара.Вставить("СтараяЦена" , 15); - ОписаниеТовара.Вставить("ОсновноеФото" , Картинка1); - ОписаниеТовара.Вставить("URL" , "https://github.com/Bayselonarrend/OpenIntegrations"); - ОписаниеТовара.Вставить("ДополнительныеФото" , МассивКартинок); - ОписаниеТовара.Вставить("ГлавныйВГруппе" , Истина); - ОписаниеТовара.Вставить("Ширина" , 20); - ОписаниеТовара.Вставить("Высота" , 30); - ОписаниеТовара.Вставить("Глубина" , 40); + ОписаниеТовара.Вставить("Категория" , "20173"); + ОписаниеТовара.Вставить("Цена" , 1); + ОписаниеТовара.Вставить("СтараяЦена" , 15); + ОписаниеТовара.Вставить("ОсновноеФото" , Картинка1); + ОписаниеТовара.Вставить("URL" , "https://github.com/Bayselonarrend/OpenIntegrations"); + ОписаниеТовара.Вставить("ДополнительныеФото" , МассивКартинок); + ОписаниеТовара.Вставить("ГлавныйВГруппе" , Истина); + ОписаниеТовара.Вставить("Ширина" , 20); + ОписаниеТовара.Вставить("Высота" , 30); + ОписаниеТовара.Вставить("Глубина" , 40); ОписаниеТовара.Вставить("Вес" , 100); ОписаниеТовара.Вставить("SKU" , "12345"); ОписаниеТовара.Вставить("ДоступныйОстаток" , "10"); - - Результат = OPI_VK.ДобавитьТовар(ОписаниеТовара, Подборка, Параметры); - - // END - + + Результат = OPI_VK.ДобавитьТовар(ОписаниеТовара, Подборка, Параметры); + + // END + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьТовар", "VK"); - + Проверка_ВКТовар(Результат); - + ИДТовара = Результат["response"]["market_item_id"]; OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_MarketItemID", ИДТовара); ПараметрыФункции.Вставить("VK_MarketItemID", ИДТовара); - + КонецПроцедуры Процедура VK_ИзменитьТовар(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - - Товар = ПараметрыФункции["VK_MarketItemID"]; - + + Товар = ПараметрыФункции["VK_MarketItemID"]; + ОписаниеТовара = Новый Соответствие; ОписаниеТовара.Вставить("Имя", "Тестовый товар измененный"); - + Результат = OPI_VK.ИзменитьТовар(Товар, ОписаниеТовара, , Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьТовар", "VK"); - + Проверка_ВКИстина(Результат); - + КонецПроцедуры Процедура VK_ДобавитьТоварВПодборку(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + Товар = ПараметрыФункции["VK_MarketItemID"]; Подборка = ПараметрыФункции["VK_MarketAlbumID"]; - + Результат = OPI_VK.ДобавитьТоварВПодборку(Товар, Подборка, Параметры); - - // END - + + // END + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьТоварВПодборку", "VK"); - + Проверка_ВКЧисло(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_УдалитьТоварИзПодборки(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + Товар = ПараметрыФункции["VK_MarketItemID"]; Подборка = ПараметрыФункции["VK_MarketAlbumID"]; - - Результат = OPI_VK.УдалитьТоварИзПодборки(Товар, Подборка, Параметры); - + + Результат = OPI_VK.УдалитьТоварИзПодборки(Товар, Подборка, Параметры); + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьТоварИзПодборки", "VK"); - + Проверка_ВКИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_УдалитьТовар(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + Товар = ПараметрыФункции["VK_MarketItemID"]; - + Результат = OPI_VK.УдалитьТовар(Товар, Параметры); - - // END - + + // END + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьТовар", "VK"); - + Проверка_ВКИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_УдалитьПодборку(ПараметрыФункции) @@ -5382,235 +5382,235 @@ Параметры = ПолучитьПараметрыВК(); Подборка = ПараметрыФункции["VK_MarketAlbumID"]; - - Результат = OPI_VK.УдалитьПодборку(Подборка, Параметры); - + + Результат = OPI_VK.УдалитьПодборку(Подборка, Параметры); + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьПодборку", "VK"); - + Проверка_ВКИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_СоздатьСвойствоТовара(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + Название = "Цвет"; - + Результат = OPI_VK.СоздатьСвойствоТовара(Название, Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьСвойствоТовара", "VK"); - + Проверка_ВКСвойство(Результат); - + OPI_Инструменты.Пауза(5); - + Свойство = Результат["response"]["property_id"]; Свойство = OPI_Инструменты.ЧислоВСтроку(Свойство); - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_PropID", Свойство); ПараметрыФункции.Вставить("VK_PropID", Свойство); - + КонецПроцедуры Процедура VK_ИзменитьСвойствоТовара(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + Название = "Цвет (изм.)"; Свойство = ПараметрыФункции["VK_PropID"]; - + Результат = OPI_VK.ИзменитьСвойствоТовара(Название, Свойство, Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьСвойствоТовара", "VK"); - + OPI_Инструменты.Пауза(5); - + Проверка_ВКИстина(Результат); - + КонецПроцедуры Процедура VK_ДобавитьВариантСвойстваТовара(ПараметрыФункции) Счетчик = 1; // SKIP Параметры = ПолучитьПараметрыВК(); - + Свойство = ПараметрыФункции["VK_PropID"]; МассивВариантов = Новый Массив; МассивВариантов.Добавить("Желтый"); МассивВариантов.Добавить("Синий"); МассивВариантов.Добавить("Красный"); - + Для Каждого Значение Из МассивВариантов Цикл - + Результат = OPI_VK.ДобавитьВариантСвойстваТовара(Значение, Свойство, Параметры); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьВариантСвойстваТовара", "VK"); - - Проверка_ВКВариантСвойства(Результат); // SKIP + + Проверка_ВКВариантСвойства(Результат); // SKIP OPI_Инструменты.Пауза(5); // SKIP - + ИДВарианта = Результат["response"]["variant_id"]; // SKIP ИмяПараметра = "VK_PropVarID" + Строка(Счетчик); // SKIP - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр(ИмяПараметра, ИДВарианта); // SKIP ПараметрыФункции.Вставить(ИмяПараметра, ИДВарианта); Счетчик = Счетчик + 1; // SKIP - - КонецЦикла; - + + КонецЦикла; + // END - + КонецПроцедуры Процедура VK_ИзменитьВариантСвойстваТовара(ПараметрыФункции) - + Параметры = ПолучитьПараметрыВК(); - + Свойство = ПараметрыФункции["VK_PropID"]; Вариант = ПараметрыФункции["VK_PropVarID1"]; Значение = "Новое имя варианта"; - + Результат = OPI_VK.ИзменитьВариантСвойстваТовара(Значение , Свойство , Вариант , Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьВариантСвойстваТовара", "VK"); - + Проверка_ВКИстина(Результат); - + КонецПроцедуры Процедура VK_СоздатьТоварСоСвойством(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + Картинка1 = ПараметрыФункции["Picture"]; Картинка2 = ПараметрыФункции["Picture2"]; ВариантСвойства1 = ПараметрыФункции["VK_PropVarID1"]; ВариантСвойства2 = ПараметрыФункции["VK_PropVarID2"]; - + МассивКартинок = Новый Массив; МассивКартинок.Добавить(Картинка1); МассивКартинок.Добавить(Картинка2); - + Товар = Новый Соответствие(); - Товар.Вставить("Имя" , "Тестовый товар (со свойством)"); + Товар.Вставить("Имя" , "Тестовый товар (со свойством)"); Товар.Вставить("Описание" , "Описание товара"); - Товар.Вставить("Категория" , "20173"); - Товар.Вставить("Цена" , 1); - Товар.Вставить("СтараяЦена" , 15); - Товар.Вставить("ОсновноеФото" , Картинка1); - Товар.Вставить("URL" , "https://github.com/Bayselonarrend/OpenIntegrations"); - Товар.Вставить("ДополнительныеФото" , МассивКартинок); - Товар.Вставить("ГлавныйВГруппе" , Истина); - Товар.Вставить("НомерГруппы" , Неопределено); - Товар.Вставить("Ширина" , 20); - Товар.Вставить("Высота" , 30); - Товар.Вставить("Глубина" , 40); + Товар.Вставить("Категория" , "20173"); + Товар.Вставить("Цена" , 1); + Товар.Вставить("СтараяЦена" , 15); + Товар.Вставить("ОсновноеФото" , Картинка1); + Товар.Вставить("URL" , "https://github.com/Bayselonarrend/OpenIntegrations"); + Товар.Вставить("ДополнительныеФото" , МассивКартинок); + Товар.Вставить("ГлавныйВГруппе" , Истина); + Товар.Вставить("НомерГруппы" , Неопределено); + Товар.Вставить("Ширина" , 20); + Товар.Вставить("Высота" , 30); + Товар.Вставить("Глубина" , 40); Товар.Вставить("Вес" , 100); Товар.Вставить("SKU" , 12345); Товар.Вставить("ДоступныйОстаток" , "10"); Товар.Вставить("ЗначенияСвойств" , ВариантСвойства1); - - Результат = OPI_VK.ДобавитьТовар(Товар, , Параметры); - + + Результат = OPI_VK.ДобавитьТовар(Товар, , Параметры); + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ТоварСоСвойством1"); - + Проверка_ВКТовар(Результат); - + ИДТовара = Результат["response"]["market_item_id"]; OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_MarketItemID2", ИДТовара); ПараметрыФункции.Вставить("VK_MarketItemID2", ИДТовара); - + Товар.Вставить("Имя" , "Тестовый товар (другой)"); Товар.Вставить("ЗначенияСвойств", ВариантСвойства2); - Результат = OPI_VK.ДобавитьТовар(Товар, , Параметры); - + Результат = OPI_VK.ДобавитьТовар(Товар, , Параметры); + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ТоварСоСвойством2"); - + Проверка_ВКТовар(Результат); - + ИДТовара = Результат["response"]["market_item_id"]; OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_MarketItemID3", ИДТовара); ПараметрыФункции.Вставить("VK_MarketItemID3", ИДТовара); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_ПолучитьТоварыПоИД(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + Товар1 = ПараметрыФункции["VK_MarketItemID2"]; Товар2 = ПараметрыФункции["VK_MarketItemID3"]; - + МассивТоваров = Новый Массив; МассивТоваров.Добавить(Товар1); МассивТоваров.Добавить(Товар2); - + Результат = OPI_VK.ПолучитьТоварыПоИД(МассивТоваров, Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьТоварыПоИД", "VK"); - + Проверка_ВКИнформацияОТоварах(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_СгруппироватьТовары(ПараметрыФункции) - + Параметры = ПолучитьПараметрыВК(); - + Товар1 = ПараметрыФункции["VK_MarketItemID2"]; Товар2 = ПараметрыФункции["VK_MarketItemID3"]; - + МассивТоваров = Новый Массив; МассивТоваров.Добавить(Товар1); МассивТоваров.Добавить(Товар2); - + Результат = OPI_VK.СгруппироватьТовары(МассивТоваров, , Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СгруппироватьТовары", "VK"); - + Проверка_ВКГруппаТоваров(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры - + Процедура VK_УдалитьВариантСвойстваТовара(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); Вариант = ПараметрыФункции["VK_PropVarID1"]; - + Результат = OPI_VK.УдалитьВариантСвойстваТовара(Вариант, Параметры); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьВариантСвойстваТовара", "VK"); - + Проверка_ВКИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_УдалитьСвойствоТовара(ПараметрыФункции) @@ -5618,93 +5618,93 @@ Параметры = ПолучитьПараметрыВК(); Свойство = ПараметрыФункции["VK_PropID"]; - + Результат = OPI_VK.УдалитьСвойствоТовара(Свойство, Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьСвойствоТовара"); - + OPI_Инструменты.Пауза(5); - + Проверка_ВКИстина(Результат); - + КонецПроцедуры Процедура VK_ПолучитьСписокТоваров(ПараметрыФункции) - Параметры = ПолучитьПараметрыВК(); + Параметры = ПолучитьПараметрыВК(); Результат = OPI_VK.ПолучитьСписокТоваров(, Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокТоваров", "VK"); - + Проверка_Массив(Результат); OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_ПолучитьСписокПодборок(ПараметрыФункции) - Параметры = ПолучитьПараметрыВК(); + Параметры = ПолучитьПараметрыВК(); Результат = OPI_VK.ПолучитьСписокПодборок(Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокПодборок", "VK"); - + Проверка_Массив(Результат); OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_ПолучитьСписокСвойств(ПараметрыФункции) - Параметры = ПолучитьПараметрыВК(); + Параметры = ПолучитьПараметрыВК(); Результат = OPI_VK.ПолучитьСписокСвойств(Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокСвойств", "VK"); - + Проверка_Массив(Результат); OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_ПолучитьСписокЗаказов(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); Результат = OPI_VK.ПолучитьСписокЗаказов(Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокЗаказов", "VK"); - + Проверка_Массив(Результат); OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_ЗагрузитьВидеоНаСервер(ПараметрыФункции) - + Параметры = ПолучитьПараметрыВК(); - + Видео = ПараметрыФункции["Video"]; Наименование = "Новое видео"; Описание = "Описание видео"; - + Результат = OPI_VK.ЗагрузитьВидеоНаСервер(Видео, Наименование, Описание, , Параметры); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗагрузитьВидеоНаСервер", "VK"); - + Проверка_ВКВидео(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры #КонецОбласти @@ -5715,38 +5715,38 @@ КлючПриложения = ПараметрыФункции["Dropbox_Appkey"]; Результат = OPI_Dropbox.ПолучитьСсылкуАвторизации(КлючПриложения); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСсылкуАвторизации", "Dropbox"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Строка"); - + КонецПроцедуры Процедура Dropbox_ПолучитьТокен(ПараметрыФункции) - + КлючПриложения = ПараметрыФункции["Dropbox_Appkey"]; СекретПриложения = ПараметрыФункции["Dropbox_Appsecret"]; Код = ПараметрыФункции["Dropbox_Code"]; Результат = OPI_Dropbox.ПолучитьТокен(КлючПриложения, СекретПриложения, Код); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьТокен"); - + Токен = Результат["access_token"]; Рефреш = Результат["refresh_token"]; - + Если ЗначениеЗаполнено(Токен) Тогда OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Dropbox_Token", Токен); КонецЕсли; - + Если ЗначениеЗаполнено(Рефреш) Тогда OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Dropbox_Refresh", Рефреш); КонецЕсли; - + КонецПроцедуры Процедура Dropbox_ОбновитьТокен(ПараметрыФункции) @@ -5754,515 +5754,515 @@ КлючПриложения = ПараметрыФункции["Dropbox_Appkey"]; СекретПриложения = ПараметрыФункции["Dropbox_Appsecret"]; РефрешТокен = ПараметрыФункции["Dropbox_Refresh"]; - + Результат = OPI_Dropbox.ОбновитьТокен(КлючПриложения, СекретПриложения, РефрешТокен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОбновитьТокен"); - + Токен = Результат["access_token"]; - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Токен).Заполнено(); OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Dropbox_Token", Токен); - + КонецПроцедуры Процедура Dropbox_ПолучитьИнформациюОбОбъекте(ПараметрыФункции) - - Путь = "/New/pic.png"; + + Путь = "/New/pic.png"; Токен = ПараметрыФункции["Dropbox_Token"]; - + Результат = OPI_Dropbox.ПолучитьИнформациюОбОбъекте(Токен, Путь, Истина); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИнформациюОбОбъекте", "Dropbox"); Проверка_ДропБоксФайл(Результат, Путь); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_ПолучитьПревью(ПараметрыФункции) - + Токен = ПараметрыФункции["Dropbox_Token"]; - Путь = "/New/mydoc.docx"; - + Путь = "/New/mydoc.docx"; + Результат = OPI_Dropbox.ПолучитьПревью(Токен, Путь); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьПревью", "Dropbox"); - + Проверка_ДвоичныеДанные(Результат, 120000); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_ЗагрузитьФайл(ПараметрыФункции) - Путь = "/New/pic.png"; + Путь = "/New/pic.png"; Токен = ПараметрыФункции["Dropbox_Token"]; Картинка = ПараметрыФункции["Picture"]; - + КартинкаПуть = ПолучитьИмяВременногоФайла("png"); КопироватьФайл(Картинка, КартинкаПуть); - + Результат = OPI_Dropbox.ЗагрузитьФайл(Токен, КартинкаПуть, Путь, Истина); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗагрузитьФайл", "Dropbox"); - + Проверка_ДропБоксФайл(Результат, Путь); УдалитьФайлы(КартинкаПуть); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_ЗагрузитьФайлПоURL(ПараметрыФункции) - - Путь = "/New/url_doc.docx"; + + Путь = "/New/url_doc.docx"; Токен = ПараметрыФункции["Dropbox_Token"]; URL = ПараметрыФункции["Document"]; - + Результат = OPI_Dropbox.ЗагрузитьФайлПоURL(Токен, URL, Путь); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗагрузитьФайлПоURL", "Dropbox"); - + Проверка_ДропБоксРабота(Результат); - + Работа = Результат["async_job_id"]; - + ПараметрыФункции.Вставить("Dropbox_Job", Работа); OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Dropbox_Job", Работа); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_ПолучитьСтатусЗагрузкиПоURL(ПараметрыФункции) Токен = ПараметрыФункции["Dropbox_Token"]; ИДРаботы = ПараметрыФункции["Dropbox_Job"]; - Статус = "in_progress"; - - Пока Статус = "in_progress" Цикл - + Статус = "in_progress"; + + Пока Статус = "in_progress" Цикл + Результат = OPI_Dropbox.ПолучитьСтатусЗагрузкиПоURL(Токен, ИДРаботы); Статус = Результат[".tag"]; - + OPI_Инструменты.Пауза(5); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСтатусЗагрузкиПоURL", "Dropbox"); - + КонецЦикла; - + // END - + Проверка_ДропБоксСтатус(Результат); - + Путь = "/New/url_doc.docx"; Результат = OPI_Dropbox.УдалитьОбъект(Токен, Путь); - + Проверка_ДропБоксМетаданные(Результат, Путь); - OPI_Инструменты.Пауза(5); - + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_УдалитьОбъект(ПараметрыФункции) - - Путь = "/New/pic.png"; - Токен = ПараметрыФункции["Dropbox_Token"]; - + + Путь = "/New/pic.png"; + Токен = ПараметрыФункции["Dropbox_Token"]; + Результат = OPI_Dropbox.УдалитьОбъект(Токен, Путь); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьОбъект", "Dropbox"); Проверка_ДропБоксМетаданные(Результат, Путь); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_КопироватьОбъект(ПараметрыФункции) - + Оригинал = "/New/pic.png"; - Копия = "/New/pic_copy.png"; + Копия = "/New/pic_copy.png"; Токен = ПараметрыФункции["Dropbox_Token"]; - + Результат = OPI_Dropbox.КопироватьОбъект(Токен, Оригинал, Копия); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "КопироватьОбъект", "Dropbox"); - + Проверка_ДропБоксМетаданные(Результат, Копия); - + Результат = OPI_Dropbox.УдалитьОбъект(Токен, Копия); Проверка_ДропБоксМетаданные(Результат, Копия); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_ПереместитьОбъект(ПараметрыФункции) - + ОригиналныйПуть = "/New/pic.png"; - ЦелевойПуть = "/pic.png"; + ЦелевойПуть = "/pic.png"; Токен = ПараметрыФункции["Dropbox_Token"]; - + Результат = OPI_Dropbox.ПереместитьОбъект(Токен, ОригиналныйПуть, ЦелевойПуть); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереместитьОбъект", "Dropbox"); - + Проверка_ДропБоксМетаданные(Результат, ЦелевойПуть); - + Результат = OPI_Dropbox.ПереместитьОбъект(Токен, ЦелевойПуть, ОригиналныйПуть); Проверка_ДропБоксМетаданные(Результат, ОригиналныйПуть); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_СоздатьПапку(ПараметрыФункции) - + Токен = ПараметрыФункции["Dropbox_Token"]; Путь = "/Новый каталог"; - + Результат = OPI_Dropbox.СоздатьПапку(Токен, Путь); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьПапку", "Dropbox"); - + Проверка_ДропБоксМетаданные(Результат, Путь); - + Результат = OPI_Dropbox.УдалитьОбъект(Токен, Путь); Проверка_ДропБоксМетаданные(Результат, Путь); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_СкачатьФайл(ПараметрыФункции) Токен = ПараметрыФункции["Dropbox_Token"]; - Путь = "/New/pic.png"; - + Путь = "/New/pic.png"; + Результат = OPI_Dropbox.СкачатьФайл(Токен, Путь); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СкачатьФайл", "Dropbox"); - + Проверка_ДвоичныеДанные(Результат, 2000000); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_СкачатьПапку(ПараметрыФункции) - + Токен = ПараметрыФункции["Dropbox_Token"]; Путь = "/New"; - + Результат = OPI_Dropbox.СкачатьПапку(Токен, Путь); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СкачатьПапку", "Dropbox"); - + Проверка_ДвоичныеДанные(Результат); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_ПолучитьСписокФайловПапки(ПараметрыФункции) - - Путь = "/New"; + + Путь = "/New"; Токен = ПараметрыФункции["Dropbox_Token"]; - + Результат = OPI_Dropbox.ПолучитьСписокФайловПапки(Токен, Путь, Истина); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокФайловПапки", "Dropbox"); Проверка_ДропБоксМассив(Результат); - + OPI_Инструменты.Пауза(5); - -КонецПроцедуры + +КонецПроцедуры Процедура Dropbox_ПолучитьСписокВерсийОбъекта(ПараметрыФункции) Токен = ПараметрыФункции["Dropbox_Token"]; - Путь = "/New/pic.png"; - + Путь = "/New/pic.png"; + Результат = OPI_Dropbox.ПолучитьСписокВерсийОбъекта(Токен, Путь, 1); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокВерсийОбъекта", "Dropbox"); - + Проверка_ДропБоксМассив(Результат, 1); - + Ревизия = Результат["entries"][0]["rev"]; - + ПараметрыФункции.Вставить("Dropbox_FileRevision", Ревизия); OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Dropbox_FileRevision", Ревизия); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_ВосстановитьОбъектКВерсии(ПараметрыФункции) - + Версия = ПараметрыФункции["Dropbox_FileRevision"]; Токен = ПараметрыФункции["Dropbox_Token"]; - Путь = "/New/pic.png"; - + Путь = "/New/pic.png"; + Результат = OPI_Dropbox.ВосстановитьОбъектКВерсии(Токен, Путь, Версия); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВосстановитьОбъектКВерсии", "Dropbox"); - + Проверка_ДропБоксФайл(Результат, Путь); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_ПолучитьСписокТегов(ПараметрыФункции) Токен = ПараметрыФункции["Dropbox_Token"]; - + МассивПутей = Новый Массив; МассивПутей.Добавить("/New/Dogs.mp3"); - МассивПутей.Добавить("/New/mydoc.docx"); - + МассивПутей.Добавить("/New/mydoc.docx"); + Результат = OPI_Dropbox.ПолучитьСписокТегов(Токен, МассивПутей); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокТегов", "Dropbox"); - + Проверка_ДропБоксТеги(Результат, МассивПутей.Количество()); - + Результат = OPI_Dropbox.ПолучитьСписокТегов(Токен, "/New/mydoc.docx"); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокТегов (одиночный)"); - + Проверка_ДропБоксТеги(Результат, 1); - + ЕстьТег = Ложь; - + Для Каждого Тег Из Результат["paths_to_tags"][0]["tags"] Цикл Если Тег["tag_text"] = "важное" Тогда - ЕстьТег = Истина; + ЕстьТег = Истина; КонецЕсли; КонецЦикла; - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(ЕстьТег).Равно(Истина); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_ДобавитьТег(ПараметрыФункции) - + Тег = "Важное"; Токен = ПараметрыФункции["Dropbox_Token"]; - Путь = "/New/mydoc.docx"; - + Путь = "/New/mydoc.docx"; + Результат = OPI_Dropbox.ДобавитьТег(Токен, Путь, Тег); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьТег", "Dropbox"); - + Проверка_Пусто(Результат); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_УдалитьТег(ПараметрыФункции) - + Тег = "Важное"; Токен = ПараметрыФункции["Dropbox_Token"]; - Путь = "/New/mydoc.docx"; - + Путь = "/New/mydoc.docx"; + Результат = OPI_Dropbox.УдалитьТег(Токен, Путь, Тег); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьТег", "Dropbox"); - + Проверка_Пусто(Результат); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_ПолучитьИнформациюОбАккаунте(ПараметрыФункции) - + Токен = ПараметрыФункции["Dropbox_Token"]; - + Результат = OPI_Dropbox.ПолучитьИнформациюОбАккаунте(Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИнформациюОбАккаунте", "Dropbox"); - + Проверка_ДропбоксАккаунт(Результат); - + Результат = OPI_Dropbox.ПолучитьИнформациюОбАккаунте(Токен, Результат["account_id"]); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИнформациюОбАккаунте (сторонний)"); - + Проверка_ДропбоксАккаунт(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Dropbox_ПолучитьДанныеИспользованияПространства(ПараметрыФункции) - + Токен = ПараметрыФункции["Dropbox_Token"]; - + Результат = OPI_Dropbox.ПолучитьДанныеИспользованияПространства(Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьДанныеИспользованияПространства", "Dropbox"); - + Проверка_ДропбоксПространство(Результат); - + КонецПроцедуры Процедура Dropbox_ДобавитьПользователейКФайлу(ПараметрыФункции) - + Токен = ПараметрыФункции["Dropbox_Token"]; Почта = ПараметрыФункции["Dropbox_OtherUser"]; Файл = ПараметрыФункции["Dropbox_FileID"]; - + Результат = OPI_Dropbox.ДобавитьПользователейКФайлу(Токен, Файл, Почта, Ложь); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьПользователейКФайлу", "Dropbox"); - + Проверка_ДропбоксУчастник(Результат, Почта, Ложь); - + Почты = Новый Массив; Почты.Добавить(Почта); - + Результат = OPI_Dropbox.ДобавитьПользователейКФайлу(Токен, Файл, Почты, Истина); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьПользователейКФайлу (доп.) "); - + Проверка_ДропбоксУчастник(Результат, Почта, Истина); - + КонецПроцедуры Процедура Dropbox_ОпубликоватьПапку(ПараметрыФункции) - + Токен = ПараметрыФункции["Dropbox_Token"]; - Путь = "/New"; - + Путь = "/New"; + Результат = OPI_Dropbox.ОпубликоватьПапку(Токен, Путь); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОпубликоватьПапку", "Dropbox"); - + Проверка_ДропБоксПубличнаяПапка(Результат); - + IDПапки = Результат["shared_folder_id"]; - + ПараметрыФункции.Вставить("Dropbox_SharedFolder", IDПапки); OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Dropbox_SharedFolder", IDПапки); - - OPI_Инструменты.Пауза(5); + + OPI_Инструменты.Пауза(5); КонецПроцедуры Процедура Dropbox_ОтменитьПубликациюПапки(ПараметрыФункции) - + Токен = ПараметрыФункции["Dropbox_Token"]; Папка = ПараметрыФункции["Dropbox_SharedFolder"]; - + Результат = OPI_Dropbox.ОтменитьПубликациюПапки(Токен, Папка); ТекущийСтатус = "in_progress"; IDРаботы = Результат["async_job_id"]; - + Пока ТекущийСтатус = "in_progress" Цикл - Результат = OPI_Dropbox.ПолучитьСтатусАсинхронногоИзменения(Токен, IDРаботы); - ТекущийСтатус = Результат[".tag"]; + Результат = OPI_Dropbox.ПолучитьСтатусАсинхронногоИзменения(Токен, IDРаботы); + ТекущийСтатус = Результат[".tag"]; OPI_Инструменты.Пауза(3); КонецЦикла; - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтменитьПубликациюПапки", "Dropbox"); - + Проверка_ДропБоксСтатус(Результат); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_ДобавитьПользователейКПапке(ПараметрыФункции) - + Токен = ПараметрыФункции["Dropbox_Token"]; Почта = ПараметрыФункции["Dropbox_OtherUser"]; Папка = ПараметрыФункции["Dropbox_SharedFolder"]; // shared_folder_id - + Результат = OPI_Dropbox.ДобавитьПользователейКПапке(Токен, Папка, Почта, Ложь); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьПользователейКПапке", "Dropbox"); - + Проверка_Пусто(Результат); - + Почты = Новый Массив; Почты.Добавить(Почта); - + Результат = OPI_Dropbox.ДобавитьПользователейКПапке(Токен, Папка, Почты, Истина); - + Проверка_Пусто(Результат); - + КонецПроцедуры Процедура Dropbox_ОтменитьПубликациюФайла(ПараметрыФункции) - - Токен = ПараметрыФункции["Dropbox_Token"]; + + Токен = ПараметрыФункции["Dropbox_Token"]; Файл = ПараметрыФункции["Dropbox_FileID"]; - + Результат = OPI_Dropbox.ОтменитьПубликациюФайла(Токен, Файл); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтменитьПубликациюФайла", "Dropbox"); - + Проверка_Пусто(Результат); - + КонецПроцедуры #КонецОбласти @@ -6270,2230 +6270,2230 @@ #Область Bitrix24 Процедура Bitrix24_ПолучитьСсылкуАвторизацииПриложения(ПараметрыФункции) - + Домен = ПараметрыФункции["Bitrix24_Domain"]; ClientID = ПараметрыФункции["Bitrix24_ClientID"]; - + Результат = OPI_Bitrix24.ПолучитьСсылкуАвторизацииПриложения(Домен, ClientID); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСсылкуАвторизацииПриложения", "Bitrix24"); - + Проверка_Строка(Результат); - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_AuthURL", Результат); КонецПроцедуры Процедура Bitrix24_ПолучитьТокен(ПараметрыФункции) - + ClientID = ПараметрыФункции["Bitrix24_ClientID"]; ClientSecret = ПараметрыФункции["Bitrix24_ClientSecret"]; Code = ПараметрыФункции["Bitrix24_Code"]; - + Результат = OPI_Bitrix24.ПолучитьТокен(ClientID, ClientSecret, Code); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьТокен", "Bitrix24"); - + Если ЗначениеЗаполнено(Результат["access_token"]) И ЗначениеЗаполнено(Результат["refresh_token"]) Тогда OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_Token" , Результат["access_token"]); OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_Refresh", Результат["refresh_token"]); КонецЕсли; - + КонецПроцедуры Процедура Bitrix24_ОбновитьТокен(ПараметрыФункции) - + ClientID = ПараметрыФункции["Bitrix24_ClientID"]; ClientSecret = ПараметрыФункции["Bitrix24_ClientSecret"]; Refresh = ПараметрыФункции["Bitrix24_Refresh"]; - + Результат = OPI_Bitrix24.ОбновитьТокен(ClientID, ClientSecret, Refresh); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОбновитьТокен", "Bitrix24"); - + Проверка_БитриксАвторизация(Результат); - + Если ЗначениеЗаполнено(Результат["access_token"]) И ЗначениеЗаполнено(Результат["refresh_token"]) Тогда OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_Token" , Результат["access_token"]); OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_Refresh", Результат["refresh_token"]); КонецЕсли; - + КонецПроцедуры Процедура Bitrix24_СерверноеВремя(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.СерверноеВремя(URL); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СерверноеВремя (хук)", "Bitrix24"); - + Проверка_БитриксВремя(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.СерверноеВремя(URL, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СерверноеВремя", "Bitrix24"); - - Проверка_БитриксВремя(Результат); - + + Проверка_БитриксВремя(Результат); + КонецПроцедуры Процедура Bitrix24_СоздатьНовость(ПараметрыФункции) - + Текст = "Текст новости"; Заголовок = "Заголовок новости"; Картинка1 = ПараметрыФункции["Picture"]; // URL, Путь или Двоичные данные Картинка2 = ПараметрыФункции["Picture2"]; // URL, Путь или Двоичные данные - + Файлы = Новый Соответствие; Файлы.Вставить("1.png", Картинка1); Файлы.Вставить("2.png", Картинка2); - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.СоздатьНовость(URL, Текст, , Файлы, Заголовок, Истина); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьНовость (хук)", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); // SKIP - + IDНовости = Результат["result"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookPostID", IDНовости); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookPostID", IDНовости); // SKIP ПараметрыФункции.Вставить("Bitrix24_HookPostID", IDНовости); // SKIP URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.СоздатьНовость(URL, Текст, , Файлы, Заголовок, , Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьНовость", "Bitrix24"); - - Проверка_БитриксЧисло(Результат); - + + Проверка_БитриксЧисло(Результат); + IDНовости = Результат["result"]; - - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_PostID", IDНовости); + + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_PostID", IDНовости); ПараметрыФункции.Вставить("Bitrix24_PostID", IDНовости); - + КонецПроцедуры Процедура Bitrix24_ИзменитьНовость(ПараметрыФункции) - + Текст = "Новый текст новости"; Заголовок = "Новый заголовок новости"; Картинка1 = ПараметрыФункции["Picture"]; // URL, Путь или Двоичные данные IDНовости = ПараметрыФункции["Bitrix24_PostID"]; - + Файлы = Новый Соответствие; Файлы.Вставить("1.png", Картинка1); - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ИзменитьНовость(URL, IDНовости, Текст, , Файлы, Заголовок); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьНовость (хук)", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDНовости = ПараметрыФункции["Bitrix24_HookPostID"]; - + Результат = OPI_Bitrix24.ИзменитьНовость(URL, IDНовости, Текст, , Файлы, Заголовок, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьНовость", "Bitrix24"); - - Проверка_БитриксЧисло(Результат); - + + Проверка_БитриксЧисло(Результат); + КонецПроцедуры Процедура Bitrix24_УдалитьНовость(ПараметрыФункции) - - IDНовости = ПараметрыФункции["Bitrix24_HookPostID"]; + + IDНовости = ПараметрыФункции["Bitrix24_HookPostID"]; URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.УдалитьНовость(URL, IDНовости); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьНовость (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + IDНовости = ПараметрыФункции["Bitrix24_PostID"]; URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.УдалитьНовость(URL, IDНовости, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьНовость", "Bitrix24"); - - Проверка_БитриксИстина(Результат); - + + Проверка_БитриксИстина(Результат); + КонецПроцедуры Процедура Bitrix24_ПолучитьСписокПросмотревшихВажное(ПараметрыФункции) - - IDНовости = ПараметрыФункции["Bitrix24_HookPostID"]; + + IDНовости = ПараметрыФункции["Bitrix24_HookPostID"]; URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ПолучитьСписокПросмотревшихВажное(URL, IDНовости); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокПросмотревшихВажное (хук)", "Bitrix24"); - + Проверка_БитриксМассив(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьСписокПросмотревшихВажное(URL, IDНовости, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокПросмотревшихВажное", "Bitrix24"); - - Проверка_БитриксМассив(Результат); - + + Проверка_БитриксМассив(Результат); + КонецПроцедуры Процедура Bitrix24_ПолучитьНовости(ПараметрыФункции) - - IDНовости = ПараметрыФункции["Bitrix24_PostID"]; + + IDНовости = ПараметрыФункции["Bitrix24_PostID"]; URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ПолучитьНовости(URL, IDНовости); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьНовости (хук)", "Bitrix24"); - + Проверка_БитриксМассивОбъектов(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьНовости(URL, IDНовости, , Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьНовости", "Bitrix24"); - - Проверка_БитриксМассивОбъектов(Результат); - + + Проверка_БитриксМассивОбъектов(Результат); + КонецПроцедуры Процедура Bitrix24_ДобавитьКомментарийНовости(ПараметрыФункции) - + Текст = "Комментарий к новости"; - IDНовости = ПараметрыФункции["Bitrix24_PostID"]; + IDНовости = ПараметрыФункции["Bitrix24_PostID"]; URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ДобавитьКомментарийНовости(URL, IDНовости, Текст); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьКомментарийНовости (хук)", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); // SKIP - + Текст = "Другой комментарий к новости"; URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ДобавитьКомментарийНовости(URL, IDНовости, Текст, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьКомментарийНовости", "Bitrix24"); - - Проверка_БитриксЧисло(Результат); - + + Проверка_БитриксЧисло(Результат); + КонецПроцедуры Процедура Bitrix24_ДобавитьПолучателейКНовости(ПараметрыФункции) - + Видимость = "UA"; - IDНовости = ПараметрыФункции["Bitrix24_PostID"]; + IDНовости = ПараметрыФункции["Bitrix24_PostID"]; URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ДобавитьПолучателейКНовости(URL, IDНовости, Видимость); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьПолучателейКНовости (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ДобавитьПолучателейКНовости(URL, IDНовости, Видимость, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьПолучателейКНовости", "Bitrix24"); - - Проверка_БитриксИстина(Результат); - + + Проверка_БитриксИстина(Результат); + КонецПроцедуры Процедура Bitrix24_ПолучитьСтруктуруЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ПолучитьСтруктуруЗадачи(URL); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСтруктуруЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксПоля(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьСтруктуруЗадачи(URL, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСтруктуруЗадачи", "Bitrix24"); - - Проверка_БитриксПоля(Результат); - + + Проверка_БитриксПоля(Результат); + КонецПроцедуры Процедура Bitrix24_СоздатьЗадачу(ПараметрыФункции) - + // Полную структуру полей можно получить функцией ПолучитьСтруктуруЗадачи() - + ТекущаяДата = OPI_Инструменты.ПолучитьТекущуюДату(); Час = 3600; Сутки = 24; Исполнитель = 1; - + СтруктураЗадачи = Новый Структура; СтруктураЗадачи.Вставить("TITLE" , "Новая задача"); СтруктураЗадачи.Вставить("DESCRIPTION" , "Новое описание задачи"); СтруктураЗадачи.Вставить("PRIORITY" , "2"); СтруктураЗадачи.Вставить("DEADLINE" , ТекущаяДата + Час * Сутки); СтруктураЗадачи.Вставить("RESPONSIBLE_ID", Исполнитель); - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.СоздатьЗадачу(URL, СтруктураЗадачи); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьЗадачу (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + IDЗадачи = Результат["result"]["task"]["id"]; // SKIP - - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookTaskID", IDЗадачи); // SKIP + + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookTaskID", IDЗадачи); // SKIP ПараметрыФункции.Вставить("Bitrix24_HookTaskID", IDЗадачи); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.СоздатьЗадачу(URL, СтруктураЗадачи, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьЗадачу", "Bitrix24"); - - Проверка_БитриксЗадача(Результат); - + + Проверка_БитриксЗадача(Результат); + IDЗадачи = Результат["result"]["task"]["id"]; - - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_TaskID", IDЗадачи); + + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_TaskID", IDЗадачи); ПараметрыФункции.Вставить("Bitrix24_TaskID", IDЗадачи); - + OPI_Инструменты.Пауза(5); КонецПроцедуры Процедура Bitrix24_ИзменитьЗадачу(ПараметрыФункции) - + // Полную структуру полей можно получить функцией ПолучитьСтруктуруЗадачи() - + СтруктураЗадачи = Новый Структура; - СтруктураЗадачи.Вставить("TITLE", "Другой заголовок задачи"); + СтруктураЗадачи.Вставить("TITLE" , "Другой заголовок задачи"); СтруктураЗадачи.Вставить("DESCRIPTION", "Другое описание задачи"); - СтруктураЗадачи.Вставить("PRIORITY", "1"); - + СтруктураЗадачи.Вставить("PRIORITY" , "1"); + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ИзменитьЗадачу(URL, IDЗадачи, СтруктураЗадачи); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьЗадачу (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ИзменитьЗадачу(URL, IDЗадачи, СтруктураЗадачи, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьЗадачу", "Bitrix24"); - - Проверка_БитриксЗадача(Результат); - + + Проверка_БитриксЗадача(Результат); + КонецПроцедуры Процедура Bitrix24_ПолучитьЗадачу(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ПолучитьЗадачу(URL, IDЗадачи); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьЗадачу (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ПолучитьЗадачу(URL, IDЗадачи, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьЗадачу", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); - + КонецПроцедуры Процедура Bitrix24_ПринятьЗадачу(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ПринятьЗадачу(URL, IDЗадачи); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПринятьЗадачу (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ПринятьЗадачу(URL, IDЗадачи, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПринятьЗадачу", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); - + КонецПроцедуры Процедура Bitrix24_ОтклонитьЗадачу(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ОтклонитьЗадачу(URL, IDЗадачи); - + Проверка_Соответствие(Результат); // SKIP - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтклонитьЗадачу (хук)", "Bitrix24"); - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ОтклонитьЗадачу(URL, IDЗадачи, Токен); - + // END - + Проверка_Соответствие(Результат); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтклонитьЗадачу", "Bitrix24"); - + КонецПроцедуры Процедура Bitrix24_ЗавершитьЗадачу(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ЗавершитьЗадачу(URL, IDЗадачи); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗавершитьЗадачу (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ЗавершитьЗадачу(URL, IDЗадачи, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗавершитьЗадачу", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); - + КонецПроцедуры Процедура Bitrix24_ВозобновитьЗадачу(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ВозобновитьЗадачу(URL, IDЗадачи); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВозобновитьЗадачу (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ВозобновитьЗадачу(URL, IDЗадачи, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВозобновитьЗадачу", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); - + КонецПроцедуры Процедура Bitrix24_ОтложитьЗадачу(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ОтложитьЗадачу(URL, IDЗадачи); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтложитьЗадачу (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ОтложитьЗадачу(URL, IDЗадачи, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтложитьЗадачу", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); - + КонецПроцедуры Процедура Bitrix24_НачатьВыполнениеЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.НачатьВыполнениеЗадачи(URL, IDЗадачи); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "НачатьВыполнениеЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.НачатьВыполнениеЗадачи(URL, IDЗадачи, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "НачатьВыполнениеЗадачи", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); - + КонецПроцедуры Процедура Bitrix24_НачатьНаблюдатьЗаЗадачей(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.НачатьНаблюдатьЗаЗадачей(URL, IDЗадачи); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "НачатьНаблюдатьЗаЗадачей (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.НачатьНаблюдатьЗаЗадачей(URL, IDЗадачи, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "НачатьНаблюдатьЗаЗадачей", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); - + КонецПроцедуры Процедура Bitrix24_ПрекратитьНаблюдатьЗаЗадачей(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ПрекратитьНаблюдатьЗаЗадачей(URL, IDЗадачи); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПрекратитьНаблюдатьЗаЗадачей (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ПрекратитьНаблюдатьЗаЗадачей(URL, IDЗадачи, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПрекратитьНаблюдатьЗаЗадачей", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); - + КонецПроцедуры Процедура Bitrix24_ПриостановитьЗадачу(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ПриостановитьЗадачу(URL, IDЗадачи); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПриостановитьЗадачу (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ПриостановитьЗадачу(URL, IDЗадачи, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПриостановитьЗадачу", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); - + КонецПроцедуры Процедура Bitrix24_УдалитьЗадачу(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.УдалитьЗадачу(URL, IDЗадачи); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьЗадачу (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.УдалитьЗадачу(URL, IDЗадачи, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьЗадачу", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); - + КонецПроцедуры Процедура Bitrix24_ДелегироватьЗадачу(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; IDПользователя = ПараметрыФункции["Bitrix24_UserID"]; - + Результат = OPI_Bitrix24.ДелегироватьЗадачу(URL, IDЗадачи, IDПользователя); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДелегироватьЗадачу (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ДелегироватьЗадачу(URL, IDЗадачи, IDПользователя, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДелегироватьЗадачу", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); - + КонецПроцедуры Процедура Bitrix24_ДобавитьЗадачуВИзбранное(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ДобавитьЗадачуВИзбранное(URL, IDЗадачи); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьЗадачуВИзбранное (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ДобавитьЗадачуВИзбранное(URL, IDЗадачи, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьЗадачуВИзбранное", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_УбратьЗадачуИзИзбранного(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.УбратьЗадачуИзИзбранного(URL, IDЗадачи); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УбратьЗадачуИзИзбранного (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.УбратьЗадачуИзИзбранного(URL, IDЗадачи, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УбратьЗадачуИзИзбранного", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьИсториюЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ПолучитьИсториюЗадачи(URL, IDЗадачи); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИсториюЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксСписок(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ПолучитьИсториюЗадачи(URL, IDЗадачи, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИсториюЗадачи", "Bitrix24"); - + Проверка_БитриксСписок(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьСписокЗадач(ПараметрыФункции) - + // Полную структуру фильтра можно найти в функции ПолучитьСтруктуруФильтраЗадач Фильтр = Новый Структура; Фильтр.Вставить("CREATED_BY" , 1); Фильтр.Вставить("RESPONSIBLE_ID", 10); - + Отступ = 1; URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ПолучитьСписокЗадач(URL, Фильтр); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокЗадач (хук)", "Bitrix24"); - + Проверка_БитриксСписокЗадач(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьСписокЗадач(URL, , Отступ, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокЗадач", "Bitrix24"); - + Проверка_БитриксСписокЗадач(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьСписокХранилищ(ПараметрыФункции) - - URL = ПараметрыФункции["Bitrix24_URL"]; + + URL = ПараметрыФункции["Bitrix24_URL"]; Результат = OPI_Bitrix24.ПолучитьСписокХранилищ(URL); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокХранилищ (хук)", "Bitrix24"); - + Проверка_БитриксХранилища(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьСписокХранилищ(URL, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокХранилищ", "Bitrix24"); - + Проверка_БитриксХранилища(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьХранилищеПриложения(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьХранилищеПриложения(URL, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьХранилищеПриложения", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); - + IDХранилища = Результат["result"]["ID"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_StorageID", IDХранилища); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_StorageID", IDХранилища); // SKIP ПараметрыФункции.Вставить("Bitrix24_StorageID", IDХранилища); // SKIP - + КонецПроцедуры Процедура Bitrix24_ЗагрузитьФайлВХранилище(ПараметрыФункции) - - Наименование2 = "Картинка2.jpg"; + + Наименование2 = "Картинка2.jpg"; Наименование = "Картинка1.jpg"; - + Картинка2 = ПараметрыФункции["Picture"]; // Локальный путь, URL или Двоичные данные Картинка = ПараметрыФункции["Picture2"]; // Локальный путь, URL или Двоичные данные - + IDПриемника = 3; - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ЗагрузитьФайлВХранилище(URL, Наименование2, Картинка2, IDПриемника); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗагрузитьФайлВХранилище (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + IDФайла = Результат["result"]["ID"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookFileID", IDФайла); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookFileID", IDФайла); // SKIP ПараметрыФункции.Вставить("Bitrix24_HookFileID", IDФайла); // SKIP URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ЗагрузитьФайлВХранилище(URL, Наименование, Картинка, IDПриемника, , Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗагрузитьФайлВХранилище", "Bitrix24"); - - Проверка_БитриксОбъект(Результат); - - IDФайла = Результат["result"]["ID"]; - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_FileID", IDФайла); - ПараметрыФункции.Вставить("Bitrix24_FileID", IDФайла); - + + Проверка_БитриксОбъект(Результат); + + IDФайла = Результат["result"]["ID"]; + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_FileID", IDФайла); + ПараметрыФункции.Вставить("Bitrix24_FileID", IDФайла); + КонецПроцедуры Процедура Bitrix24_УдалитьФайл(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDФайла = ПараметрыФункции["Bitrix24_HookFileID"]; - + Результат = OPI_Bitrix24.УдалитьФайл(URL, IDФайла); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьФайл (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDФайла = ПараметрыФункции["Bitrix24_FileID"]; - + Результат = OPI_Bitrix24.УдалитьФайл(URL, IDФайла, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьФайл", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_СоздатьКаталогВХранилище(ПараметрыФункции) - + IDХранилища = 3; Наименование = "Новый каталог"; Наименование2 = "Новый каталог 2"; - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.СоздатьКаталогВХранилище(URL, IDХранилища, Наименование2); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьКаталогВХранилище (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + IDКаталога = Результат["result"]["ID"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookFolderID", IDКаталога); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookFolderID", IDКаталога); // SKIP ПараметрыФункции.Вставить("Bitrix24_HookFolderID", IDКаталога); // SKIP URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.СоздатьКаталогВХранилище(URL, IDХранилища, Наименование, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьКаталогВХранилище", "Bitrix24"); - - Проверка_БитриксОбъект(Результат); - + + Проверка_БитриксОбъект(Результат); + IDКаталога = Результат["result"]["ID"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_FolderID", IDКаталога); // SKIP - ПараметрыФункции.Вставить("Bitrix24_FolderID", IDКаталога); // SKIP - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_FolderID", IDКаталога); // SKIP + ПараметрыФункции.Вставить("Bitrix24_FolderID", IDКаталога); // SKIP + КонецПроцедуры Процедура Bitrix24_УдалитьКаталог(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDКаталога = ПараметрыФункции["Bitrix24_HookFolderID"]; - + Результат = OPI_Bitrix24.УдалитьКаталог(URL, IDКаталога); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьКаталог (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDКаталога = ПараметрыФункции["Bitrix24_FolderID"]; - + Результат = OPI_Bitrix24.УдалитьКаталог(URL, IDКаталога, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьКаталог", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьХранилище(ПараметрыФункции) - - URL = ПараметрыФункции["Bitrix24_URL"]; + + URL = ПараметрыФункции["Bitrix24_URL"]; IDХранилища = 3; - + Результат = OPI_Bitrix24.ПолучитьХранилище(URL, IDХранилища); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьХранилище (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьХранилище(URL, IDХранилища, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьХранилище", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьСодержимоеХранилища(ПараметрыФункции) - - URL = ПараметрыФункции["Bitrix24_URL"]; - IDХранилища = 3; - + + URL = ПараметрыФункции["Bitrix24_URL"]; + IDХранилища = 3; + Результат = OPI_Bitrix24.ПолучитьСодержимоеХранилища(URL, IDХранилища); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСодержимоеХранилища (хук)", "Bitrix24"); - + Проверка_БитриксМассив(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьСодержимоеХранилища(URL, IDХранилища, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСодержимоеХранилища", "Bitrix24"); - + Проверка_БитриксМассив(Результат); - + КонецПроцедуры Процедура Bitrix24_ПереименоватьХранилище(ПараметрыФункции) - - Наименование = "Новое имя хранилища"; + + Наименование = "Новое имя хранилища"; URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDХранилища = ПараметрыФункции["Bitrix24_StorageID"]; - + Результат = OPI_Bitrix24.ПереименоватьХранилище(URL, IDХранилища, Наименование, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереименоватьХранилище", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьИнформациюОКаталоге(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDКаталога = ПараметрыФункции["Bitrix24_FolderID"]; - + Результат = OPI_Bitrix24.ПолучитьИнформациюОКаталоге(URL, IDКаталога); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИнформациюОКаталоге (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьИнформациюОКаталоге(URL, IDКаталога, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИнформациюОКаталоге", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); - + КонецПроцедуры Процедура Bitrix24_СоздатьПодкаталог(ПараметрыФункции) - + IDКаталога = ПараметрыФункции["Bitrix24_FolderID"]; Наименование = "Новый подкаталог"; Наименование2 = "Новый подкаталог 2"; - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.СоздатьПодкаталог(URL, IDКаталога, Наименование2); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьПодкаталог (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + IDПодкаталога = Результат["result"]["ID"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookSubfolderID", IDПодкаталога); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookSubfolderID", IDПодкаталога); // SKIP ПараметрыФункции.Вставить("Bitrix24_HookSubfolderID", IDПодкаталога); // SKIP URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.СоздатьПодкаталог(URL, IDКаталога, Наименование, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьПодкаталог", "Bitrix24"); - - Проверка_БитриксОбъект(Результат); - + + Проверка_БитриксОбъект(Результат); + IDПодкаталога = Результат["result"]["ID"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_SubfolderID", IDПодкаталога); // SKIP - ПараметрыФункции.Вставить("Bitrix24_SubfolderID", IDПодкаталога); // SKIP - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_SubfolderID", IDПодкаталога); // SKIP + ПараметрыФункции.Вставить("Bitrix24_SubfolderID", IDПодкаталога); // SKIP + КонецПроцедуры Процедура Bitrix24_СкопироватьКаталог(ПараметрыФункции) - + IDПриемника = ПараметрыФункции["Bitrix24_HookSubfolderID"]; IDКаталога = ПараметрыФункции["Bitrix24_SubfolderID"]; - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.СкопироватьКаталог(URL, IDКаталога, IDПриемника); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СкопироватьКаталог (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + IDПриемника = ПараметрыФункции["Bitrix24_SubfolderID"]; IDКаталога = ПараметрыФункции["Bitrix24_HookSubfolderID"]; URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.СкопироватьКаталог(URL, IDКаталога, IDПриемника, Токен); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СкопироватьКаталог", "Bitrix24"); - - Проверка_БитриксОбъект(Результат); - + + Проверка_БитриксОбъект(Результат); + КонецПроцедуры Процедура Bitrix24_ПолучитьВнешнююСсылкуКаталога(ПараметрыФункции) - - URL = ПараметрыФункции["Bitrix24_URL"]; + + URL = ПараметрыФункции["Bitrix24_URL"]; IDКаталога = ПараметрыФункции["Bitrix24_FolderID"]; - + Результат = OPI_Bitrix24.ПолучитьВнешнююСсылкуКаталога(URL, IDКаталога); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьВнешнююСсылкуКаталога (хук)", "Bitrix24"); - + Проверка_БитриксСтрока(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьВнешнююСсылкуКаталога(URL, IDКаталога, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьВнешнююСсылкуКаталога", "Bitrix24"); - + Проверка_БитриксСтрока(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьСтруктуруФильтраКаталога(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ПолучитьСтруктуруФильтраКаталога(URL); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСтруктуруФильтраКаталога (хук)", "Bitrix24"); - + Проверка_Структура(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьСтруктуруФильтраКаталога(URL, Истина, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСтруктуруФильтраКаталога", "Bitrix24"); - + Проверка_Структура(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьДочерниеЭлементыКаталога(ПараметрыФункции) - - URL = ПараметрыФункции["Bitrix24_URL"]; + + URL = ПараметрыФункции["Bitrix24_URL"]; IDКаталога = ПараметрыФункции["Bitrix24_FolderID"]; - + Результат = OPI_Bitrix24.ПолучитьДочерниеЭлементыКаталога(URL, IDКаталога); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьДочерниеЭлементыКаталога (хук)", "Bitrix24"); - + Проверка_БитриксМассив(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьДочерниеЭлементыКаталога(URL, IDКаталога, , Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьДочерниеЭлементыКаталога", "Bitrix24"); - + Проверка_БитриксМассив(Результат); - + КонецПроцедуры Процедура Bitrix24_ПоместитьКаталогВКорзину(ПараметрыФункции) - - URL = ПараметрыФункции["Bitrix24_URL"]; + + URL = ПараметрыФункции["Bitrix24_URL"]; IDКаталога = ПараметрыФункции["Bitrix24_FolderID"]; - + Результат = OPI_Bitrix24.ПоместитьКаталогВКорзину(URL, IDКаталога); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПоместитьКаталогВКорзину (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПоместитьКаталогВКорзину(URL, IDКаталога, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПоместитьКаталогВКорзину", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); - + КонецПроцедуры Процедура Bitrix24_ВосстановитьКаталог(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDКаталога = ПараметрыФункции["Bitrix24_FolderID"]; - + Результат = OPI_Bitrix24.ВосстановитьКаталог(URL, IDКаталога); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВосстановитьКаталог (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ВосстановитьКаталог(URL, IDКаталога, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВосстановитьКаталог", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); - + КонецПроцедуры Процедура Bitrix24_ПереместитьКаталог(ПараметрыФункции) - + IDПриемника = ПараметрыФункции["Bitrix24_HookfolderID"]; IDКаталога = ПараметрыФункции["Bitrix24_SubfolderID"]; - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ПереместитьКаталог(URL, IDКаталога, IDПриемника); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереместитьКаталог (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + IDКаталога = ПараметрыФункции["Bitrix24_HookSubfolderID"]; URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПереместитьКаталог(URL, IDКаталога, IDПриемника, Токен); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереместитьКаталог", "Bitrix24"); - - Проверка_БитриксОбъект(Результат); - + + Проверка_БитриксОбъект(Результат); + КонецПроцедуры Процедура Bitrix24_ПереименоватьКаталог(ПараметрыФункции) - + Наименование = "Новый каталог"; Наименование2 = "Новый каталог 2"; - + IDКаталога2 = ПараметрыФункции["Bitrix24_HookFolderID"]; URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ПереименоватьКаталог(URL, IDКаталога2, Наименование2); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереименоватьКаталог (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP IDКаталога = ПараметрыФункции["Bitrix24_FolderID"]; URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПереименоватьКаталог(URL, IDКаталога, Наименование, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереименоватьКаталог", "Bitrix24"); - - Проверка_БитриксОбъект(Результат); - + + Проверка_БитриксОбъект(Результат); + КонецПроцедуры Процедура Bitrix24_ЗагрузитьФайлВКаталог(ПараметрыФункции) - - Наименование2 = "Картинка2.jpg"; + + Наименование2 = "Картинка2.jpg"; Наименование = "Картинка1.jpg"; - + Картинка2 = ПараметрыФункции["Picture"]; // Локальный путь, URL или Двоичные данные Картинка = ПараметрыФункции["Picture2"]; // Локальный путь, URL или Двоичные данные - + IDПриемника = ПараметрыФункции["Bitrix24_FolderID"]; - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ЗагрузитьФайлВКаталог(URL, Наименование2, Картинка2, IDПриемника); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗагрузитьФайлВКаталог (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + IDФайла = Результат["result"]["ID"]; // SKIP OPI_Bitrix24.УдалитьФайл(URL, IDФайла); // SKIP URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ЗагрузитьФайлВКаталог(URL, Наименование, Картинка, IDПриемника, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗагрузитьФайлВКаталог", "Bitrix24"); - - Проверка_БитриксОбъект(Результат); - + + Проверка_БитриксОбъект(Результат); + IDФайла = Результат["result"]["ID"]; - Результат = OPI_Bitrix24.УдалитьФайл(URL, IDФайла, Токен); - + Результат = OPI_Bitrix24.УдалитьФайл(URL, IDФайла, Токен); + КонецПроцедуры Процедура Bitrix24_СкопироватьФайл(ПараметрыФункции) - + IDКаталога = ПараметрыФункции["Bitrix24_HookFolderID"]; IDФайла = ПараметрыФункции["Bitrix24_FileID"]; - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.СкопироватьФайл(URL, IDФайла, IDКаталога); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СкопироватьФайл (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + IDКаталога = ПараметрыФункции["Bitrix24_FolderID"]; URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.СкопироватьФайл(URL, IDФайла, IDКаталога, Токен); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СкопироватьФайл", "Bitrix24"); - - Проверка_БитриксОбъект(Результат); - + + Проверка_БитриксОбъект(Результат); + КонецПроцедуры Процедура Bitrix24_ПолучитьИнформациюОФайле(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDФайла = ПараметрыФункции["Bitrix24_FileID"]; - + Результат = OPI_Bitrix24.ПолучитьИнформациюОФайле(URL, IDФайла); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИнформациюОФайле (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьИнформациюОФайле(URL, IDФайла, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИнформациюОФайле", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьВнешнююСсылкуФайла(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDФайла = ПараметрыФункции["Bitrix24_FileID"]; - + Результат = OPI_Bitrix24.ПолучитьВнешнююСсылкуФайла(URL, IDФайла); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьВнешнююСсылкуФайла (хук)", "Bitrix24"); - + Проверка_БитриксСтрока(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьВнешнююСсылкуФайла(URL, IDФайла, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьВнешнююСсылкуФайла", "Bitrix24"); - + Проверка_БитриксСтрока(Результат); - + КонецПроцедуры Процедура Bitrix24_ПоместитьФайлВКорзину(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDФайла = ПараметрыФункции["Bitrix24_FileID"]; - + Результат = OPI_Bitrix24.ПоместитьФайлВКорзину(URL, IDФайла); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПоместитьФайлВКорзину (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПоместитьФайлВКорзину(URL, IDФайла, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПоместитьФайлВКорзину", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); - + КонецПроцедуры Процедура Bitrix24_ВосстановитьФайл(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDФайла = ПараметрыФункции["Bitrix24_FileID"]; - + Результат = OPI_Bitrix24.ВосстановитьФайл(URL, IDФайла); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВосстановитьФайл (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ВосстановитьФайл(URL, IDФайла, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВосстановитьФайл", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); - + КонецПроцедуры Процедура Bitrix24_ПереименоватьФайл(ПараметрыФункции) - + Наименование = "Новое имя файла.jpg"; Наименование2 = "Новое имя файла 2.jpg"; - + IDФайла2 = ПараметрыФункции["Bitrix24_HookFileID"]; URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ПереименоватьФайл(URL, IDФайла2, Наименование2); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереименоватьФайл (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP IDФайла = ПараметрыФункции["Bitrix24_FileID"]; URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПереименоватьФайл(URL, IDФайла, Наименование, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереименоватьФайл", "Bitrix24"); - - Проверка_БитриксОбъект(Результат); - + + Проверка_БитриксОбъект(Результат); + КонецПроцедуры Процедура Bitrix24_ПереместитьФайлВКаталог(ПараметрыФункции) - + IDКаталога = ПараметрыФункции["Bitrix24_HookSubFolderID"]; IDФайла = ПараметрыФункции["Bitrix24_FileID"]; - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ПереместитьФайлВКаталог(URL, IDФайла, IDКаталога); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереместитьФайлВКаталог (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + IDКаталога = ПараметрыФункции["Bitrix24_SubFolderID"]; URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПереместитьФайлВКаталог(URL, IDФайла, IDКаталога, Токен); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереместитьФайлВКаталог", "Bitrix24"); - - Проверка_БитриксОбъект(Результат); - + + Проверка_БитриксОбъект(Результат); + КонецПроцедуры Процедура Bitrix24_ДобавитьФайлВЗадачу(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; IDФайла = ПараметрыФункции["Bitrix24_TaskFileID"]; - + Результат = OPI_Bitrix24.ДобавитьФайлВЗадачу(URL, IDЗадачи, IDФайла); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьФайлВЗадачу (хук)", "Bitrix24"); - + Проверка_БитриксВложение(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ДобавитьФайлВЗадачу(URL, IDЗадачи, IDФайла, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьФайлВЗадачу", "Bitrix24"); - + Проверка_БитриксВложение(Результат); - + КонецПроцедуры Процедура Bitrix24_ПроверитьДоступКЗадаче(ПараметрыФункции) - + МассивПользователей = Новый Массив; МассивПользователей.Добавить("1"); МассивПользователей.Добавить("10"); - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ПроверитьДоступКЗадаче(URL, IDЗадачи, МассивПользователей); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПроверитьДоступКЗадаче (хук)", "Bitrix24"); - + Проверка_БитриксДоступныеДействия(Результат, МассивПользователей.Количество()); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ПроверитьДоступКЗадаче(URL, IDЗадачи, МассивПользователей, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПроверитьДоступКЗадаче", "Bitrix24"); - + Проверка_БитриксДоступныеДействия(Результат, МассивПользователей.Количество()); - + КонецПроцедуры Процедура Bitrix24_ОтключитьЗвукЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ОтключитьЗвукЗадачи(URL, IDЗадачи); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтключитьЗвукЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ОтключитьЗвукЗадачи(URL, IDЗадачи, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтключитьЗвукЗадачи", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); - + КонецПроцедуры Процедура Bitrix24_ВключитьЗвукЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ВключитьЗвукЗадачи(URL, IDЗадачи); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВключитьЗвукЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ВключитьЗвукЗадачи(URL, IDЗадачи, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВключитьЗвукЗадачи", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); - + КонецПроцедуры Процедура Bitrix24_ДобавитьКомментарийЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_CommentsTaskID"]; - + Текст = "Задача невыполнима, расходимся"; - + Результат = OPI_Bitrix24.ДобавитьКомментарийЗадачи(URL, IDЗадачи, Текст); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьКомментарийЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); // SKIP - + IDКомментария = Результат["result"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookCommentID", IDКомментария); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookCommentID", IDКомментария); // SKIP ПараметрыФункции.Вставить("Bitrix24_HookCommentID", IDКомментария); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Текст = "Задача выполнима, не расходимся"; - + Результат = OPI_Bitrix24.ДобавитьКомментарийЗадачи(URL, IDЗадачи, Текст, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьКомментарийЗадачи", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); - + IDКомментария = Результат["result"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_CommentID", IDКомментария); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_CommentID", IDКомментария); // SKIP ПараметрыФункции.Вставить("Bitrix24_CommentID", IDКомментария); // SKIP - + КонецПроцедуры Процедура Bitrix24_УдалитьКомментарийЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_CommentsTaskID"]; IDКомментария = ПараметрыФункции["Bitrix24_HookCommentID"]; - + Результат = OPI_Bitrix24.УдалитьКомментарийЗадачи(URL, IDЗадачи, IDКомментария); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьКомментарийЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDКомментария = ПараметрыФункции["Bitrix24_CommentID"]; - + Результат = OPI_Bitrix24.УдалитьКомментарийЗадачи(URL, IDЗадачи, IDКомментария, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьКомментарийЗадачи", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_СоздатьРезультатИзКомментария(ПараметрыФункции) URL = ПараметрыФункции["Bitrix24_URL"]; IDКомментария = ПараметрыФункции["Bitrix24_HookCommentID"]; - + Результат = OPI_Bitrix24.СоздатьРезультатИзКомментария(URL, IDКомментария); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьРезультатИзКомментария (хук)", "Bitrix24"); - + Проверка_БитриксРезультат(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDКомментария = ПараметрыФункции["Bitrix24_CommentID"]; - + Результат = OPI_Bitrix24.СоздатьРезультатИзКомментария(URL, IDКомментария, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьРезультатИзКомментария", "Bitrix24"); - + Проверка_БитриксРезультат(Результат); - + КонецПроцедуры Процедура Bitrix24_УдалитьРезультатИзКомментария(ПараметрыФункции) Экспорт URL = ПараметрыФункции["Bitrix24_URL"]; IDКомментария = ПараметрыФункции["Bitrix24_HookCommentID"]; - + Результат = OPI_Bitrix24.УдалитьРезультатИзКомментария(URL, IDКомментария); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьРезультатИзКомментария (хук)", "Bitrix24"); - + Проверка_БитриксНеопределено(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDКомментария = ПараметрыФункции["Bitrix24_CommentID"]; - + Результат = OPI_Bitrix24.УдалитьРезультатИзКомментария(URL, IDКомментария, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьРезультатИзКомментария", "Bitrix24"); - + Проверка_БитриксНеопределено(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьСписокРезультатов(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_CommentsTaskID"]; - + Результат = OPI_Bitrix24.ПолучитьСписокРезультатов(URL, IDЗадачи); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокРезультатов (хук)", "Bitrix24"); - + Проверка_БитриксСписокРезультатов(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьСписокРезультатов(URL, IDЗадачи, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокРезультатов", "Bitrix24"); - + Проверка_БитриксСписокРезультатов(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьСписокКомментариевЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_CommentsTaskID"]; - + Результат = OPI_Bitrix24.ПолучитьСписокКомментариевЗадачи(URL, IDЗадачи); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокКомментариевЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксСписокКомментариев(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьСписокКомментариевЗадачи(URL, IDЗадачи, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокКомментариевЗадачи", "Bitrix24"); - + Проверка_БитриксСписокКомментариев(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьКомменатрийЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDКомментария = ПараметрыФункции["Bitrix24_HookCommentID"]; IDЗадачи = ПараметрыФункции["Bitrix24_CommentsTaskID"]; - + Результат = OPI_Bitrix24.ПолучитьКомменатрийЗадачи(URL, IDЗадачи, IDКомментария); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьКомменатрийЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксКомментарий(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDКомментария = ПараметрыФункции["Bitrix24_CommentID"]; - + Результат = OPI_Bitrix24.ПолучитьКомменатрийЗадачи(URL, IDЗадачи, IDКомментария, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьКомменатрийЗадачи", "Bitrix24"); - + Проверка_БитриксКомментарий(Результат); - + КонецПроцедуры Процедура Bitrix24_ИзменитьКомментарийЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_CommentsTaskID"]; IDКомментария = ПараметрыФункции["Bitrix24_HookCommentID"]; - + Текст = "Задача изменена, не расходимся"; - + Результат = OPI_Bitrix24.ИзменитьКомментарийЗадачи(URL, IDЗадачи, IDКомментария, Текст); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьКомментарийЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDКомментария = ПараметрыФункции["Bitrix24_CommentID"]; - + Текст = "Задача изменена, расходимся"; - + Результат = OPI_Bitrix24.ИзменитьКомментарийЗадачи(URL, IDЗадачи, IDКомментария, Текст, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьКомментарийЗадачи", "Bitrix24"); - + Проверка_БитриксИстина(Результат); КонецПроцедуры Процедура Bitrix24_СоздатьЗависимостьЗадач(ПараметрыФункции) - + IDИсточника = ПараметрыФункции["Bitrix24_HookTaskID"]; IDПриемника = ПараметрыФункции["Bitrix24_TaskID"]; ТипСвязи = 0; - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.СоздатьЗависимостьЗадач(URL, IDИсточника, IDПриемника, ТипСвязи); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьЗависимостьЗадач (хук)", "Bitrix24"); - + Проверка_БитриксМассив(Результат); // SKIP - + Результат = OPI_Bitrix24.УдалитьЗависимостьЗадач(URL, IDИсточника, IDПриемника, ТипСвязи); // SKIP - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьЗависимостьЗадач (хук)", "Bitrix24"); - + IDИсточника = ПараметрыФункции["Bitrix24_TaskID"]; IDПриемника = ПараметрыФункции["Bitrix24_HookTaskID"]; ТипСвязи = 2; - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.СоздатьЗависимостьЗадач(URL, IDИсточника, IDПриемника, ТипСвязи, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьЗависимостьЗадач", "Bitrix24"); - - Проверка_БитриксМассив(Результат); - + + Проверка_БитриксМассив(Результат); + Результат = OPI_Bitrix24.УдалитьЗависимостьЗадач(URL, IDИсточника, IDПриемника, ТипСвязи, Токен); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьЗависимостьЗадач", "Bitrix24"); - + КонецПроцедуры Процедура Bitrix24_ДобавитьСтадиюКанбана(ПараметрыФункции) - + Наименование = "Новая стадия"; Цвет = "0026FF"; - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ДобавитьСтадиюКанбана(URL, Наименование, Цвет, 6); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьСтадиюКанбана (хук)", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); // SKIP - + IDПредыдущей = Результат["result"]; - - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookStageID", IDПредыдущей); // SKIP + + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookStageID", IDПредыдущей); // SKIP ПараметрыФункции.Вставить("Bitrix24_HookStageID", IDПредыдущей); // SKIP - + Наименование = "Новая стадия 2"; Цвет = "0026FF"; - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ДобавитьСтадиюКанбана(URL, Наименование, Цвет, IDПредыдущей, , Истина, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьСтадиюКанбана", "Bitrix24"); - - Проверка_БитриксЧисло(Результат); - + + Проверка_БитриксЧисло(Результат); + IDСтадии = Результат["result"]; - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_StageID", IDСтадии); - ПараметрыФункции.Вставить("Bitrix24_StageID", IDСтадии); - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_StageID", IDСтадии); + ПараметрыФункции.Вставить("Bitrix24_StageID", IDСтадии); + КонецПроцедуры Процедура Bitrix24_УдалитьСтадиюКанбана(ПараметрыФункции) - + IDСтадии = ПараметрыФункции["Bitrix24_HookStageID"]; - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.УдалитьСтадиюКанбана(URL, IDСтадии, Истина); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьСтадиюКанбана (хук)", "Bitrix24"); - - Проверка_БитриксИстина(Результат); // SKIP - + + Проверка_БитриксИстина(Результат); // SKIP + IDСтадии = ПараметрыФункции["Bitrix24_StageID"]; - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.УдалитьСтадиюКанбана(URL, IDСтадии, , Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьСтадиюКанбана", "Bitrix24"); - - Проверка_БитриксИстина(Результат); - + + Проверка_БитриксИстина(Результат); + КонецПроцедуры Процедура Bitrix24_ПолучитьСтадииКанбана(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ПолучитьСтадииКанбана(URL, , Истина); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСтадииКанбана (хук)", "Bitrix24"); - - Проверка_БитриксСоответствие(Результат); // SKIP - + + Проверка_БитриксСоответствие(Результат); // SKIP + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьСтадииКанбана(URL, , , Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСтадииКанбана", "Bitrix24"); - - Проверка_БитриксСоответствие(Результат); - + + Проверка_БитриксСоответствие(Результат); + КонецПроцедуры Процедура Bitrix24_ПеренестиЗадачуВСтадиюКанбана(ПараметрыФункции) - - IDЗадачи = ПараметрыФункции["Bitrix24_KanbanTaskID"]; + + IDЗадачи = ПараметрыФункции["Bitrix24_KanbanTaskID"]; IDСтадии = ПараметрыФункции["Bitrix24_HookStageID"]; - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ПеренестиЗадачуВСтадиюКанбана(URL, IDЗадачи, IDСтадии); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПеренестиЗадачуВСтадиюКанбана (хук)", "Bitrix24"); - - Проверка_БитриксИстина(Результат); // SKIP - + + Проверка_БитриксИстина(Результат); // SKIP + IDСтадии = ПараметрыФункции["Bitrix24_StageID"]; - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПеренестиЗадачуВСтадиюКанбана(URL, IDЗадачи, IDСтадии, , , Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПеренестиЗадачуВСтадиюКанбана", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + OPI_Bitrix24.ПеренестиЗадачуВСтадиюКанбана(URL, IDЗадачи, 2, , , Токен); - + КонецПроцедуры Процедура Bitrix24_ИзменитьСтадиюКанбана(ПараметрыФункции) - + Наименование = "Новое имя стадии стадии"; Цвет = "000000"; IDСтадии = ПараметрыФункции["Bitrix24_HookStageID"]; - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ИзменитьСтадиюКанбана(URL, Наименование, IDСтадии, Цвет); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьСтадиюКанбана (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + Наименование = "Новое имя стадии стадии 2"; Цвет = "000000"; IDСтадии = ПараметрыФункции["Bitrix24_StageID"]; - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ИзменитьСтадиюКанбана(URL, Наименование, IDСтадии, Цвет, 6, Истина, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьСтадиюКанбана", "Bitrix24"); - - Проверка_БитриксИстина(Результат); - + + Проверка_БитриксИстина(Результат); + КонецПроцедуры Процедура Bitrix24_ДобавитьЭлементЧеклистаЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Текст = "Пункт чек-листа"; - + Результат = OPI_Bitrix24.ДобавитьЭлементЧеклистаЗадачи(URL, IDЗадачи, Текст, Истина); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьЭлементЧеклистаЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); // SKIP - + IDЭлемента = Результат["result"]; // SKIP - - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookCheckElementID", IDЭлемента); // SKIP + + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookCheckElementID", IDЭлемента); // SKIP ПараметрыФункции.Вставить("Bitrix24_HookCheckElementID", IDЭлемента); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ДобавитьЭлементЧеклистаЗадачи(URL, IDЗадачи, Текст, , Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьЭлементЧеклистаЗадачи", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); - - IDЭлемента = Результат["result"]; - - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_CheckElementID", IDЭлемента); - ПараметрыФункции.Вставить("Bitrix24_CheckElementID", IDЭлемента); - + + IDЭлемента = Результат["result"]; + + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_CheckElementID", IDЭлемента); + ПараметрыФункции.Вставить("Bitrix24_CheckElementID", IDЭлемента); + КонецПроцедуры Процедура Bitrix24_ИзменитьЭлементЧеклистаЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; IDЭлемента = ПараметрыФункции["Bitrix24_HookCheckElementID"]; - + Текст = "Новый текст пункта чек-листа"; - + Результат = OPI_Bitrix24.ИзменитьЭлементЧеклистаЗадачи(URL, IDЗадачи, IDЭлемента, Текст); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьЭлементЧеклистаЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксНеопределено(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; IDЭлемента = ПараметрыФункции["Bitrix24_CheckElementID"]; - + Результат = OPI_Bitrix24.ИзменитьЭлементЧеклистаЗадачи(URL, IDЗадачи, IDЭлемента, Текст, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьЭлементЧеклистаЗадачи", "Bitrix24"); - + Проверка_БитриксНеопределено(Результат); - + КонецПроцедуры Процедура Bitrix24_УдалитьЭлементЧеклистаЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; IDЭлемента = ПараметрыФункции["Bitrix24_HookCheckElementID"]; - + Результат = OPI_Bitrix24.УдалитьЭлементЧеклистаЗадачи(URL, IDЗадачи, IDЭлемента); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьЭлементЧеклистаЗадачи (хук)", "Bitrix24"); - - Проверка_БитриксИстина(Результат); // SKIP - + + Проверка_БитриксИстина(Результат); // SKIP + IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; IDЭлемента = ПараметрыФункции["Bitrix24_CheckElementID"]; - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.УдалитьЭлементЧеклистаЗадачи(URL, IDЗадачи, IDЭлемента, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьЭлементЧеклистаЗадачи", "Bitrix24"); - - Проверка_БитриксИстина(Результат); - + + Проверка_БитриксИстина(Результат); + КонецПроцедуры Процедура Bitrix24_ПолучитьЧеклистЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ПолучитьЧеклистЗадачи(URL, IDЗадачи); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьЧеклистЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксМассив(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ПолучитьЧеклистЗадачи(URL, IDЗадачи, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьЧеклистЗадачи", "Bitrix24"); - + Проверка_БитриксМассив(Результат); КонецПроцедуры Процедура Bitrix24_ПолучитьЭлементЧеклистаЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; IDЭлемента = ПараметрыФункции["Bitrix24_HookCheckElementID"]; - + Результат = OPI_Bitrix24.ПолучитьЭлементЧеклистаЗадачи(URL, IDЗадачи, IDЭлемента); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьЭлементЧеклистаЗадачи (хук)", "Bitrix24"); - - Проверка_БитриксОбъект(Результат); // SKIP - + + Проверка_БитриксОбъект(Результат); // SKIP + IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; IDЭлемента = ПараметрыФункции["Bitrix24_CheckElementID"]; - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьЭлементЧеклистаЗадачи(URL, IDЗадачи, IDЭлемента, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьЭлементЧеклистаЗадачи", "Bitrix24"); - - Проверка_БитриксОбъект(Результат); - + + Проверка_БитриксОбъект(Результат); + КонецПроцедуры Процедура Bitrix24_ВыполнитьЭлементЧеклистаЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; IDЭлемента = ПараметрыФункции["Bitrix24_HookCheckElementID"]; - + Результат = OPI_Bitrix24.ВыполнитьЭлементЧеклистаЗадачи(URL, IDЗадачи, IDЭлемента); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВыполнитьЭлементЧеклистаЗадачи (хук)", "Bitrix24"); - - Проверка_БитриксИстина(Результат); // SKIP - + + Проверка_БитриксИстина(Результат); // SKIP + IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; IDЭлемента = ПараметрыФункции["Bitrix24_CheckElementID"]; - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ВыполнитьЭлементЧеклистаЗадачи(URL, IDЗадачи, IDЭлемента, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВыполнитьЭлементЧеклистаЗадачи", "Bitrix24"); - - Проверка_БитриксИстина(Результат); - + + Проверка_БитриксИстина(Результат); + КонецПроцедуры Процедура Bitrix24_ВозобновитьЭлементЧеклистаЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; IDЭлемента = ПараметрыФункции["Bitrix24_HookCheckElementID"]; - + Результат = OPI_Bitrix24.ВозобновитьЭлементЧеклистаЗадачи(URL, IDЗадачи, IDЭлемента); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВозобновитьЭлементЧеклистаЗадачи (хук)", "Bitrix24"); - - Проверка_БитриксИстина(Результат); // SKIP - + + Проверка_БитриксИстина(Результат); // SKIP + IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; IDЭлемента = ПараметрыФункции["Bitrix24_CheckElementID"]; - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ВозобновитьЭлементЧеклистаЗадачи(URL, IDЗадачи, IDЭлемента, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВозобновитьЭлементЧеклистаЗадачи", "Bitrix24"); - - Проверка_БитриксИстина(Результат); - + + Проверка_БитриксИстина(Результат); + КонецПроцедуры Процедура Bitrix24_ДобавитьТрудозатратыЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_ElapsedTaskID"]; - + Время = 3600; - + Результат = OPI_Bitrix24.ДобавитьТрудозатратыЗадачи(URL, IDЗадачи, Время); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьТрудозатратыЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); // SKIP - + IDЗатрат = Результат["result"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookTimeID", IDЗатрат); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookTimeID", IDЗатрат); // SKIP ПараметрыФункции.Вставить("Bitrix24_HookTimeID", IDЗатрат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Текст = "Трудозатраты по обработке"; IDПользователя = 10; Время = 7200; ДатаУстановки = ДобавитьМесяц(OPI_Инструменты.ПолучитьТекущуюДату(), -1); - + Результат = OPI_Bitrix24.ДобавитьТрудозатратыЗадачи(URL , IDЗадачи , Время @@ -8501,42 +8501,42 @@ , Текст , ДатаУстановки , Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьТрудозатратыЗадачи", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); - - IDЗатрат = Результат["result"]; - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_TimeID", IDЗатрат); - ПараметрыФункции.Вставить("Bitrix24_TimeID", IDЗатрат); - + + IDЗатрат = Результат["result"]; + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_TimeID", IDЗатрат); + ПараметрыФункции.Вставить("Bitrix24_TimeID", IDЗатрат); + КонецПроцедуры Процедура Bitrix24_ИзменитьТрудозатратыЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_ElapsedTaskID"]; IDЗаписи = ПараметрыФункции["Bitrix24_HookTimeID"]; - + Текст = "Забытый в прошлый раз текст"; Время = 4800; - + Результат = OPI_Bitrix24.ИзменитьТрудозатратыЗадачи(URL, IDЗадачи, IDЗаписи, Время, Текст); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьТрудозатратыЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксНеопределено(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗаписи = ПараметрыФункции["Bitrix24_TimeID"]; - + Текст = "Новые трудозатраты по обработке"; Время = 4800; ДатаУстановки = ДобавитьМесяц(OPI_Инструменты.ПолучитьТекущуюДату(), -1); - + Результат = OPI_Bitrix24.ИзменитьТрудозатратыЗадачи(URL , IDЗадачи , IDЗаписи @@ -8544,125 +8544,125 @@ , Текст , ДатаУстановки , Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьТрудозатратыЗадачи", "Bitrix24"); - - Проверка_БитриксНеопределено(Результат); - + + Проверка_БитриксНеопределено(Результат); + КонецПроцедуры Процедура Bitrix24_УдалитьТрудозатратыЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_ElapsedTaskID"]; IDЗаписи = ПараметрыФункции["Bitrix24_HookTimeID"]; - + Результат = OPI_Bitrix24.УдалитьТрудозатратыЗадачи(URL, IDЗадачи, IDЗаписи); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьТрудозатратыЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксНеопределено(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗаписи = ПараметрыФункции["Bitrix24_TimeID"]; - + Результат = OPI_Bitrix24.УдалитьТрудозатратыЗадачи(URL, IDЗадачи, IDЗаписи, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьТрудозатратыЗадачи", "Bitrix24"); - + Проверка_БитриксНеопределено(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьТрудозатратыЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_ElapsedTaskID"]; IDЗаписи = ПараметрыФункции["Bitrix24_HookTimeID"]; - + Результат = OPI_Bitrix24.ПолучитьТрудозатратыЗадачи(URL, IDЗадачи, IDЗаписи); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьТрудозатратыЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗаписи = ПараметрыФункции["Bitrix24_TimeID"]; - + Результат = OPI_Bitrix24.ПолучитьТрудозатратыЗадачи(URL, IDЗадачи, IDЗаписи, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьТрудозатратыЗадачи", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьСписокТрудозатратЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_ElapsedTaskID"]; - + Результат = OPI_Bitrix24.ПолучитьСписокТрудозатратЗадачи(URL, IDЗадачи); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокТрудозатратЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксМассивОбъектов(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьСписокТрудозатратЗадачи(URL, IDЗадачи, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокТрудозатратЗадачи", "Bitrix24"); - + Проверка_БитриксМассивОбъектов(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьПланЗадачНаДень(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ПолучитьПланЗадачНаДень(URL); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьПланЗадачНаДень (хук)", "Bitrix24"); - + Проверка_БитриксМассив(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьПланЗадачНаДень(URL, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьПланЗадачНаДень", "Bitrix24"); - + Проверка_БитриксМассив(Результат); - + КонецПроцедуры Процедура Bitrix24_СоздатьЧат(ПараметрыФункции) - + Картинка = ПараметрыФункции["Picture"]; OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Картинка); - + B64Картинка = ПолучитьBase64СтрокуИзДвоичныхДанных(Картинка); - + МассивУчастников = Новый Массив; МассивУчастников.Добавить(10); МассивУчастников.Добавить(1); - + СтруктураЧата = Новый Структура; СтруктураЧата.Вставить("TYPE" , "OPEN"); СтруктураЧата.Вставить("TITLE" , "Новый чат"); @@ -8672,866 +8672,866 @@ СтруктураЧата.Вставить("USERS" , МассивУчастников); СтруктураЧата.Вставить("AVATAR" , B64Картинка); СтруктураЧата.Вставить("OWNER_ID" , 1); - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.СоздатьЧат(URL, СтруктураЧата); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьЧат (хук)", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); // SKIP - + IDЧата = Результат["result"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookChatID", IDЧата); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookChatID", IDЧата); // SKIP ПараметрыФункции.Вставить("Bitrix24_HookChatID", IDЧата); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + СтруктураЧата = Новый Структура; СтруктураЧата.Вставить("TYPE" , "CHAT"); СтруктураЧата.Вставить("TITLE" , "Закрытый чат"); СтруктураЧата.Вставить("USERS" , МассивУчастников); - + Результат = OPI_Bitrix24.СоздатьЧат(URL, СтруктураЧата, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьЧат", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); - + IDЧата = Результат["result"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_ChatID", IDЧата); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_ChatID", IDЧата); // SKIP ПараметрыФункции.Вставить("Bitrix24_ChatID", IDЧата); // SKIP - + КонецПроцедуры Процедура Bitrix24_ПолучитьСписокПользователейЧата(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; - + Результат = OPI_Bitrix24.ПолучитьСписокПользователейЧата(URL, IDЧата); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокПользователейЧата (хук)", "Bitrix24"); - + Проверка_БитриксМассив(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЧата = ПараметрыФункции["Bitrix24_ChatID"]; - + Результат = OPI_Bitrix24.ПолучитьСписокПользователейЧата(URL, IDЧата, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокПользователейЧата", "Bitrix24"); - + Проверка_БитриксМассив(Результат); - + КонецПроцедуры Процедура Bitrix24_ПокинутьЧат(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; - + Результат = OPI_Bitrix24.ПокинутьЧат(URL, IDЧата); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПокинутьЧат (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЧата = ПараметрыФункции["Bitrix24_ChatID"]; - + Результат = OPI_Bitrix24.ПокинутьЧат(URL, IDЧата, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПокинутьЧат", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ИсключитьПользователяИзЧата(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; - + IDПользователя = 10; - + Результат = OPI_Bitrix24.ИсключитьПользователяИзЧата(URL, IDЧата, IDПользователя); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИсключитьПользователяИзЧата (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЧата = ПараметрыФункции["Bitrix24_ChatID"]; - + Результат = OPI_Bitrix24.ИсключитьПользователяИзЧата(URL, IDЧата, IDПользователя, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИсключитьПользователяИзЧата", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ДобавитьПользователейВЧат(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; - + IDПользователей = Новый Массив; IDПользователей.Добавить(10); IDПользователей.Добавить(12); - + Результат = OPI_Bitrix24.ДобавитьПользователейВЧат(URL, IDЧата, IDПользователей); OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьПользователейВЧат (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЧата = ПараметрыФункции["Bitrix24_ChatID"]; IDПользователя = 10; - + Результат = OPI_Bitrix24.ДобавитьПользователейВЧат(URL, IDЧата, IDПользователя, Истина, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьПользователейВЧат", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ИзменитьЗаголовокЧата(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; - + Заголовок = "Новый заголовок чата"; - + Результат = OPI_Bitrix24.ИзменитьЗаголовокЧата(URL, IDЧата, Заголовок); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьЗаголовокЧата (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЧата = ПараметрыФункции["Bitrix24_ChatID"]; - + Заголовок = "Другой заголовок чата"; - + Результат = OPI_Bitrix24.ИзменитьЗаголовокЧата(URL, IDЧата, Заголовок, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьЗаголовокЧата", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ИзменитьЦветЧата(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; - + Цвет = "AZURE"; - + Результат = OPI_Bitrix24.ИзменитьЦветЧата(URL, IDЧата, Цвет); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьЦветЧата (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЧата = ПараметрыФункции["Bitrix24_ChatID"]; - + Цвет = "PURPLE"; - + Результат = OPI_Bitrix24.ИзменитьЦветЧата(URL, IDЧата, Цвет, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьЦветЧата", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ИзменитьКартинкуЧата(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; Картинка = ПараметрыФункции["Picture2"]; - + Результат = OPI_Bitrix24.ИзменитьКартинкуЧата(URL, IDЧата, Картинка); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьКартинкуЧата (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЧата = ПараметрыФункции["Bitrix24_ChatID"]; Результат = OPI_Bitrix24.ИзменитьКартинкуЧата(URL, IDЧата, Картинка, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьКартинкуЧата", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ОтключитьУведомленияЧата(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; - + Результат = OPI_Bitrix24.ОтключитьУведомленияЧата(URL, IDЧата); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтключитьУведомленияЧата (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЧата = ПараметрыФункции["Bitrix24_ChatID"]; - + Результат = OPI_Bitrix24.ОтключитьУведомленияЧата(URL, IDЧата, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтключитьУведомленияЧата", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ВключитьУведомленияЧата(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; - + Результат = OPI_Bitrix24.ВключитьУведомленияЧата(URL, IDЧата); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВключитьУведомленияЧата (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЧата = ПараметрыФункции["Bitrix24_ChatID"]; - + Результат = OPI_Bitrix24.ВключитьУведомленияЧата(URL, IDЧата, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВключитьУведомленияЧата", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_СменитьВладельцаЧата(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; - + IDПользователя = 10; - + Результат = OPI_Bitrix24.СменитьВладельцаЧата(URL, IDЧата, IDПользователя); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СменитьВладельцаЧата (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЧата = ПараметрыФункции["Bitrix24_ChatID"]; - + Результат = OPI_Bitrix24.СменитьВладельцаЧата(URL, IDЧата, IDПользователя, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СменитьВладельцаЧата", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьСписокСообщенийЧата(ПараметрыФункции) URL = ПараметрыФункции["Bitrix24_URL"]; - IDЧата = "chat4"; - + IDЧата = "chat4"; + Результат = OPI_Bitrix24.ПолучитьСписокСообщенийЧата(URL, IDЧата); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокСообщенийЧата (хук)", "Bitrix24"); - + Проверка_БитриксСообщения(Результат); // SKIP - + IDСообщения = Результат["result"]["messages"][0]["id"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_ChatMessageID", IDСообщения); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_ChatMessageID", IDСообщения); // SKIP ПараметрыФункции.Вставить("Bitrix24_ChatMessageID", IDСообщения); // SKIP URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDПользователя = 10; - + Результат = OPI_Bitrix24.ПолучитьСписокСообщенийЧата(URL, IDПользователя, , 0, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокСообщенийЧата", "Bitrix24"); - + Проверка_БитриксСообщения(Результат); - - IDСообщения = Результат["result"]["messages"][0]["id"]; - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_UserMessageID", IDСообщения); - ПараметрыФункции.Вставить("Bitrix24_UserMessageID", IDСообщения); - + + IDСообщения = Результат["result"]["messages"][0]["id"]; + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_UserMessageID", IDСообщения); + ПараметрыФункции.Вставить("Bitrix24_UserMessageID", IDСообщения); + КонецПроцедуры Процедура Bitrix24_ОтметитьСообщениеКакПрочитанное(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; - IDЧата = "chat" + ПараметрыФункции["Bitrix24_HookChatID"]; + IDЧата = "chat" + ПараметрыФункции["Bitrix24_HookChatID"]; IDСообщения = ПараметрыФункции["Bitrix24_ChatMessageID"]; - + Результат = OPI_Bitrix24.ОтметитьСообщениеКакПрочитанное(URL, IDЧата, IDСообщения); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтметитьСообщениеКакПрочитанное (хук)", "Bitrix24"); - + Проверка_БитриксДиалог(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDПользователя = 10; IDСообщения = ПараметрыФункции["Bitrix24_UserMessageID"]; - + Результат = OPI_Bitrix24.ОтметитьСообщениеКакПрочитанное(URL, IDПользователя, IDСообщения, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтметитьСообщениеКакПрочитанное", "Bitrix24"); - + Проверка_БитриксДиалог(Результат); - + КонецПроцедуры Процедура Bitrix24_ОтметитьСообщениеКакНепрочитанное(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; - IDЧата = "chat" + ПараметрыФункции["Bitrix24_HookChatID"]; + IDЧата = "chat" + ПараметрыФункции["Bitrix24_HookChatID"]; IDСообщения = ПараметрыФункции["Bitrix24_ChatMessageID"]; - + Результат = OPI_Bitrix24.ОтметитьСообщениеКакНепрочитанное(URL, IDЧата, IDСообщения); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтметитьСообщениеКакНепрочитанное (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDПользователя = 10; IDСообщения = ПараметрыФункции["Bitrix24_UserMessageID"]; - + Результат = OPI_Bitrix24.ОтметитьСообщениеКакНепрочитанное(URL, IDПользователя, IDСообщения, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтметитьСообщениеКакНепрочитанное", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьДиалог(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; - IDЧата = "chat" + ПараметрыФункции["Bitrix24_HookChatID"]; + IDЧата = "chat" + ПараметрыФункции["Bitrix24_HookChatID"]; Результат = OPI_Bitrix24.ПолучитьДиалог(URL, IDЧата); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьДиалог (хук)", "Bitrix24"); - + Проверка_БитриксСообщение(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDПользователя = 10; - + Результат = OPI_Bitrix24.ПолучитьДиалог(URL, IDПользователя, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьДиалог", "Bitrix24"); - + Проверка_БитриксСообщение(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьСписокПользователейДиалога(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; - IDЧата = "chat" + ПараметрыФункции["Bitrix24_HookChatID"]; + IDЧата = "chat" + ПараметрыФункции["Bitrix24_HookChatID"]; Результат = OPI_Bitrix24.ПолучитьСписокПользователейДиалога(URL, IDЧата); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокПользователейДиалога (хук)", "Bitrix24"); - + Проверка_БитриксМассив(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDПользователя = 10; - + Результат = OPI_Bitrix24.ПолучитьСписокПользователейДиалога(URL, IDПользователя, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокПользователейДиалога", "Bitrix24"); - + Проверка_БитриксМассив(Результат); - + КонецПроцедуры Процедура Bitrix24_ОтправитьУведомлениеОВводе(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; - IDЧата = "chat" + ПараметрыФункции["Bitrix24_HookChatID"]; + IDЧата = "chat" + ПараметрыФункции["Bitrix24_HookChatID"]; Результат = OPI_Bitrix24.ОтправитьУведомлениеОВводе(URL, IDЧата); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьУведомлениеОВводе (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDПользователя = 10; - + Результат = OPI_Bitrix24.ОтправитьУведомлениеОВводе(URL, IDПользователя, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьУведомлениеОВводе", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ПрочитатьВсе(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; Результат = OPI_Bitrix24.ПрочитатьВсе(URL); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПрочитатьВсе (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПрочитатьВсе(URL, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПрочитатьВсе", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ОтправитьСообщение(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; - IDЧата = "chat" + ПараметрыФункции["Bitrix24_HookChatID"]; + IDЧата = "chat" + ПараметрыФункции["Bitrix24_HookChatID"]; Текст = "Текст сообщения"; Картинка = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/service/test_data/picture.jpg"; - Файл = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; - + Файл = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; + Вложения = Новый Массив; Вложения.Добавить(OPI_Bitrix24.ПолучитьБлокКартинки("Картинка1", Картинка)); - Вложения.Добавить(OPI_Bitrix24.ПолучитьБлокФайла("Файл1.docx", Файл)); + Вложения.Добавить(OPI_Bitrix24.ПолучитьБлокФайла("Файл1.docx" , Файл)); Результат = OPI_Bitrix24.ОтправитьСообщение(URL, IDЧата, Текст, Вложения); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьСообщение (хук)", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); // SKIP - + IDСообщения = Результат["result"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_ChatMessageID", IDСообщения); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_ChatMessageID", IDСообщения); // SKIP ПараметрыФункции.Вставить("Bitrix24_ChatMessageID", IDСообщения); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDПользователя = 10; - + Результат = OPI_Bitrix24.ОтправитьСообщение(URL, IDПользователя, Текст, , Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьСообщение", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); - - IDСообщения = Результат["result"]; - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_UserMessageID", IDСообщения); - ПараметрыФункции.Вставить("Bitrix24_UserMessageID", IDСообщения); - + + IDСообщения = Результат["result"]; + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_UserMessageID", IDСообщения); + ПараметрыФункции.Вставить("Bitrix24_UserMessageID", IDСообщения); + КонецПроцедуры Процедура Bitrix24_ИзменитьСообщение(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDСообщения = ПараметрыФункции["Bitrix24_ChatMessageID"]; - + Текст = "Новый текст сообщения"; Результат = OPI_Bitrix24.ИзменитьСообщение(URL, IDСообщения, Текст); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьСообщение (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDСообщения = ПараметрыФункции["Bitrix24_UserMessageID"]; - + Картинка = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/service/test_data/picture.jpg"; - Файл = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; - + Файл = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; + Вложения = Новый Массив; Вложения.Добавить(OPI_Bitrix24.ПолучитьБлокКартинки("Картинка1", Картинка)); - Вложения.Добавить(OPI_Bitrix24.ПолучитьБлокФайла("Файл1.docx", Файл)); - + Вложения.Добавить(OPI_Bitrix24.ПолучитьБлокФайла("Файл1.docx" , Файл)); + Результат = OPI_Bitrix24.ИзменитьСообщение(URL, IDСообщения, Текст, Вложения, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьСообщение", "Bitrix24"); - - Проверка_БитриксИстина(Результат); - + + Проверка_БитриксИстина(Результат); + КонецПроцедуры Процедура Bitrix24_УдалитьСообщение(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDСообщения = ПараметрыФункции["Bitrix24_ChatMessageID"]; Результат = OPI_Bitrix24.УдалитьСообщение(URL, IDСообщения); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьСообщение (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDСообщения = ПараметрыФункции["Bitrix24_UserMessageID"]; - + Результат = OPI_Bitrix24.УдалитьСообщение(URL, IDСообщения, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьСообщение", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_УстановитьРеакциюНаСообщение(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDСообщения = ПараметрыФункции["Bitrix24_ChatMessageID"]; Результат = OPI_Bitrix24.УстановитьРеакциюНаСообщение(URL, IDСообщения); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УстановитьРеакциюНаСообщение (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDСообщения = ПараметрыФункции["Bitrix24_UserMessageID"]; - + Результат = OPI_Bitrix24.УстановитьРеакциюНаСообщение(URL, IDСообщения, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УстановитьРеакциюНаСообщение", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьКаталогФайловЧата(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; - IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; + IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; Результат = OPI_Bitrix24.ПолучитьКаталогФайловЧата(URL, IDЧата); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьКаталогФайловЧата (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЧата = ПараметрыФункции["Bitrix24_ChatID"]; - + Результат = OPI_Bitrix24.ПолучитьКаталогФайловЧата(URL, IDЧата, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьКаталогФайловЧата", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); - + КонецПроцедуры Процедура Bitrix24_ОтправитьФайл(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; - IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; + IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; Файл = ПараметрыФункции["Document"]; // Двоичные данные, URL или путь к файлу Описание = "Очень важный файл"; - + Каталог = OPI_Bitrix24.ПолучитьКаталогФайловЧата(URL, IDЧата); IDКаталога = Каталог["result"]["ID"]; - + ЗагруженныйФайл = OPI_Bitrix24.ЗагрузитьФайлВКаталог(URL, "Важный документ.docx", Файл, IDКаталога); IDФайла = ЗагруженныйФайл["result"]["ID"]; Результат = OPI_Bitrix24.ОтправитьФайл(URL, IDЧата, IDФайла, Описание); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьФайл (хук)", "Bitrix24"); - + Проверка_БитриксФайлСообщение(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЧата = ПараметрыФункции["Bitrix24_ChatID"]; - + Каталог = OPI_Bitrix24.ПолучитьКаталогФайловЧата(URL, IDЧата, Токен); IDКаталога = Каталог["result"]["ID"]; - + ЗагруженныйФайл = OPI_Bitrix24.ЗагрузитьФайлВКаталог(URL, "Важный документ.docx", Файл, IDКаталога, Токен); IDФайла = ЗагруженныйФайл["result"]["ID"]; Результат = OPI_Bitrix24.ОтправитьФайл(URL, IDЧата, IDФайла, Описание, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьФайл", "Bitrix24"); - + Проверка_БитриксФайлСообщение(Результат); КонецПроцедуры Процедура Bitrix24_ПолучитьПользователей(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; МассивПользователей = Новый Массив; - + МассивПользователей.Добавить(1); МассивПользователей.Добавить(10); Результат = OPI_Bitrix24.ПолучитьПользователей(URL, МассивПользователей); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьПользователей (хук)", "Bitrix24"); - + Проверка_БитриксСоответствие(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDПользователей = 10; - + Результат = OPI_Bitrix24.ПолучитьПользователей(URL, IDПользователей, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьПользователей", "Bitrix24"); - + Проверка_БитриксСоответствие(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьСтатусПользователя(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; Результат = OPI_Bitrix24.ПолучитьСтатусПользователя(URL); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСтатусПользователя (хук)", "Bitrix24"); - + Проверка_БитриксСтрока(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьСтатусПользователя(URL, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСтатусПользователя", "Bitrix24"); - + Проверка_БитриксСтрока(Результат); - + КонецПроцедуры Процедура Bitrix24_УстановитьСтатусПользователя(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; Статус = "dnd"; Результат = OPI_Bitrix24.УстановитьСтатусПользователя(URL, Статус); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УстановитьСтатусПользователя (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; Статус = "away"; - + Результат = OPI_Bitrix24.УстановитьСтатусПользователя(URL, Статус, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УстановитьСтатусПользователя", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_СоздатьПерсональноеУведомление(ПараметрыФункции) - + IDПользователя = 1; - - URL = ПараметрыФункции["Bitrix24_URL"]; + + URL = ПараметрыФункции["Bitrix24_URL"]; Текст = "Текст сообщения"; Картинка = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/service/test_data/picture.jpg"; - Файл = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; - + Файл = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; + Вложения = Новый Массив; Вложения.Добавить(OPI_Bitrix24.ПолучитьБлокКартинки("Картинка1", Картинка)); - Вложения.Добавить(OPI_Bitrix24.ПолучитьБлокФайла("Файл1.docx", Файл)); + Вложения.Добавить(OPI_Bitrix24.ПолучитьБлокФайла("Файл1.docx" , Файл)); Результат = OPI_Bitrix24.СоздатьПерсональноеУведомление(URL, IDПользователя, Текст, ,Вложения); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьПерсональноеУведомление (хук)", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); // SKIP - + IDСообщения = Результат["result"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_PersoalHookNotifyID", IDСообщения); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_PersoalHookNotifyID", IDСообщения); // SKIP ПараметрыФункции.Вставить("Bitrix24_PersoalHookNotifyID", IDСообщения); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; Тег = "Новый"; IDПользователя = 10; - + Результат = OPI_Bitrix24.СоздатьПерсональноеУведомление(URL, IDПользователя, Текст, Тег, , Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьПерсональноеУведомление", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); - - IDСообщения = Результат["result"]; - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_PersoalNotifyID", IDСообщения); - ПараметрыФункции.Вставить("Bitrix24_PersoalNotifyID", IDСообщения); - + + IDСообщения = Результат["result"]; + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_PersoalNotifyID", IDСообщения); + ПараметрыФункции.Вставить("Bitrix24_PersoalNotifyID", IDСообщения); + КонецПроцедуры Процедура Bitrix24_СоздатьСистемноеУведомление(ПараметрыФункции) - + IDПользователя = 1; - - URL = ПараметрыФункции["Bitrix24_URL"]; + + URL = ПараметрыФункции["Bitrix24_URL"]; Текст = "Текст сообщения"; Картинка = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/service/test_data/picture.jpg"; - Файл = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; - + Файл = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; + Вложения = Новый Массив; Вложения.Добавить(OPI_Bitrix24.ПолучитьБлокКартинки("Картинка1", Картинка)); - Вложения.Добавить(OPI_Bitrix24.ПолучитьБлокФайла("Файл1.docx", Файл)); + Вложения.Добавить(OPI_Bitrix24.ПолучитьБлокФайла("Файл1.docx" , Файл)); Результат = OPI_Bitrix24.СоздатьСистемноеУведомление(URL, IDПользователя, Текст, ,Вложения); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьСистемноеУведомление (хук)", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); // SKIP - + IDСообщения = Результат["result"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_SystemHookNotifyID", IDСообщения); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_SystemHookNotifyID", IDСообщения); // SKIP ПараметрыФункции.Вставить("Bitrix24_SystemHookNotifyID", IDСообщения); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; Тег = "Новый"; IDПользователя = 10; - + Результат = OPI_Bitrix24.СоздатьСистемноеУведомление(URL, IDПользователя, Текст, Тег, , Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьСистемноеУведомление", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); - - IDСообщения = Результат["result"]; - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_SystemNotifyID", IDСообщения); - ПараметрыФункции.Вставить("Bitrix24_SystemNotifyID", IDСообщения); - + + IDСообщения = Результат["result"]; + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_SystemNotifyID", IDСообщения); + ПараметрыФункции.Вставить("Bitrix24_SystemNotifyID", IDСообщения); + КонецПроцедуры Процедура Bitrix24_УдалитьУведомление(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDУведомления = ПараметрыФункции["Bitrix24_PersoalHookNotifyID"]; - + Результат = OPI_Bitrix24.УдалитьУведомление(URL, IDУведомления); - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьУведомление", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDУведомления = ПараметрыФункции["Bitrix24_PersoalNotifyID"]; - + Результат = OPI_Bitrix24.УдалитьУведомление(URL, IDУведомления, Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьУведомление (приложение)", "Bitrix24"); - + Проверка_БитриксБулево(Результат); - + КонецПроцедуры #КонецОбласти @@ -9542,34 +9542,34 @@ Токен = ПараметрыФункции["YandexDisk_Token"]; Результат = OPI_YandexDisk.ПолучитьИнформациюОДиске(Токен); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИнформациюОДиске", "YandexDisk"); - + Проверка_ЯДискДиск(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура YandexDisk_СоздатьПапку(ПараметрыФункции) Токен = ПараметрыФункции["YandexDisk_Token"]; Путь = "/" + Строка(Новый УникальныйИдентификатор); - + Результат = OPI_YandexDisk.СоздатьПапку(Токен, Путь); - + // END - + OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьПапку", "YandexDisk"); - + Проверка_ЯДискКаталог(Результат, Путь); - + OPI_YandexDisk.УдалитьОбъект(Токен, Путь, Ложь); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры #КонецОбласти diff --git a/src/ru/OInt/tools/Modules/OPI_ПолучениеДанныхТестов.os b/src/ru/OInt/tools/Modules/OPI_ПолучениеДанныхТестов.os index 6bbfde7431..4231e3676a 100644 --- a/src/ru/OInt/tools/Modules/OPI_ПолучениеДанныхТестов.os +++ b/src/ru/OInt/tools/Modules/OPI_ПолучениеДанныхТестов.os @@ -46,10 +46,10 @@ #Область СлужебныйПрограммныйИнтерфейс Функция ПолучитьСоответствиеРазделовТестирования() Экспорт - + СтандартныеЗависимости = "[Decode, Build]"; ЗависимостиГугл = "Testing-GoogleWorkspace"; - + Разделы = Новый Структура; Разделы.Вставить("Telegram" , СтандартныеЗависимости); Разделы.Вставить("VK" , СтандартныеЗависимости); @@ -57,7 +57,7 @@ Разделы.Вставить("Twitter" , СтандартныеЗависимости); Разделы.Вставить("YandexDisk" , СтандартныеЗависимости); Разделы.Вставить("GoogleWorkspace", СтандартныеЗависимости); - Разделы.Вставить("GoogleCalendar" , ЗависимостиГугл); + Разделы.Вставить("GoogleCalendar" , ЗависимостиГугл); Разделы.Вставить("GoogleDrive" , ЗависимостиГугл); Разделы.Вставить("GoogleSheets" , ЗависимостиГугл); Разделы.Вставить("Notion" , СтандартныеЗависимости); @@ -65,13 +65,13 @@ Разделы.Вставить("Airtable" , СтандартныеЗависимости); Разделы.Вставить("Dropbox" , СтандартныеЗависимости); Разделы.Вставить("Bitrix24" , СтандартныеЗависимости); - + Возврат Разделы; - + КонецФункции Функция ПолучитьТаблицуТестов() Экспорт - + Телеграм = "Telegram"; ВКонтакте = "VK"; ЯДиск = "YandexDisk"; @@ -86,13 +86,13 @@ АирТ = "Airtable"; ДропБокс = "Dropbox"; Битрикс = "Bitrix24"; - + ТаблицаТестов = Новый ТаблицаЗначений; ТаблицаТестов.Колонки.Добавить("Метод"); ТаблицаТестов.Колонки.Добавить("Синоним"); ТаблицаТестов.Колонки.Добавить("Раздел"); - - НовыйТест(ТаблицаТестов, "Телеграм_ПолучитьИнформациюБота" , "Получить информацию бота" , Телеграм); + + НовыйТест(ТаблицаТестов, "Телеграм_ПолучитьИнформациюБота" , "Получить информацию бота" , Телеграм); НовыйТест(ТаблицаТестов, "Телеграм_ПолучитьОбновления" , "Получить обновления" , Телеграм); НовыйТест(ТаблицаТестов, "Телеграм_УстановитьWebhook" , "Установить Webhook" , Телеграм); НовыйТест(ТаблицаТестов, "Телеграм_ОтправитьТекстовоеСообщение" , "Отправить текстовое сообщение" , Телеграм); @@ -114,7 +114,7 @@ НовыйТест(ТаблицаТестов, "Телеграм_СоздатьУдалитьТемуФорума" , "Создать/Удалить тему форума" , Телеграм); НовыйТест(ТаблицаТестов, "Телеграм_ИзменитьИмяГлавнойТемы" , "Изменить имя главной темы" , Телеграм); НовыйТест(ТаблицаТестов, "Телеграм_СкрытьПоказатьГлавнуюТему" , "Скрыть/Показать главную тему" , Телеграм); - + НовыйТест(ТаблицаТестов, "ВК_СоздатьСсылкуТокена" , "Создать ссылку получения токена", ВКонтакте); НовыйТест(ТаблицаТестов, "ВК_СоздатьУдалитьПост" , "Создать/Удалить пост" , ВКонтакте); НовыйТест(ТаблицаТестов, "ВК_СоздатьСоставнойПост" , "Создать/Удалить составной пост" , ВКонтакте); @@ -135,7 +135,7 @@ НовыйТест(ТаблицаТестов, "ВК_ПолучитьСписокСвойств" , "Получить список свойств" , ВКонтакте); НовыйТест(ТаблицаТестов, "ВК_ПолучитьСписокЗаказов" , "Получить список заказов" , ВКонтакте); НовыйТест(ТаблицаТестов, "ВК_ЗагрузитьВидео" , "Загрузить видео" , ВКонтакте); - + НовыйТест(ТаблицаТестов, "ЯДиск_ПолучитьИнформациюОДиске" , "Получить информацию о диске" , ЯДиск); НовыйТест(ТаблицаТестов, "ЯДиск_СоздатьПапку" , "Создать папку" , ЯДиск); НовыйТест(ТаблицаТестов, "ЯДиск_ЗагрузитьПоАдресуПолучитьОбъект", "Загрузить по URL и получить" , ЯДиск); @@ -146,25 +146,25 @@ НовыйТест(ТаблицаТестов, "ЯДиск_ПереместитьОбъект" , "Переместить объект" , ЯДиск); НовыйТест(ТаблицаТестов, "ЯДиск_ДействияПубличныхОбъектов" , "Действия с публичными объектами", ЯДиск); НовыйТест(ТаблицаТестов, "ЯДиск_ПолучитьСписокОпубликованных" , "Получить список опубликованных" , ЯДиск); - + НовыйТест(ТаблицаТестов, "ГВ_ПолучитьСсылкуАвторизации" , "Получить ссылку авторизации" , ВСпейс); НовыйТест(ТаблицаТестов, "ГВ_ПолучитьТокен" , "Получить токен" , ВСпейс); НовыйТест(ТаблицаТестов, "ГВ_ОбновитьТокен" , "Обновить токен" , ВСпейс); - + НовыйТест(ТаблицаТестов, "ГК_ПолучитьСписокКалендарей" , "Получить список календарей" , Календарь); НовыйТест(ТаблицаТестов, "ГК_СоздатьУдалитьКалендарь" , "Создать/Удалить календарь" , Календарь); НовыйТест(ТаблицаТестов, "ГК_СоздатьУдалитьСобытие" , "Создать/Удалить событие" , Календарь); НовыйТест(ТаблицаТестов, "ГК_ПолучитьСписокСобытий" , "Получить список событий" , Календарь); - + НовыйТест(ТаблицаТестов, "ГД_ПолучитьСписокКаталогов" , "Получить список каталогов" , Драйв); НовыйТест(ТаблицаТестов, "ГД_ЗагрузитьУдалитьФайл" , "Загрузить/Удалить Файл" , Драйв); НовыйТест(ТаблицаТестов, "ГД_СоздатьУдалитьКомментарий" , "Создать/Удалить кооментарий" , Драйв); НовыйТест(ТаблицаТестов, "ГД_СоздатьКаталог" , "Создать/Удалить каталог" , Драйв); - + НовыйТест(ТаблицаТестов, "ГТ_СоздатьТаблицу" , "Создать таблицу" , Таблицы); НовыйТест(ТаблицаТестов, "ГТ_ПолучитьТаблицу" , "Получить таблицу" , Таблицы); НовыйТест(ТаблицаТестов, "ГТ_ЗаполнитьОчиститьЯчейки" , "Заполнить/Очистить ячейки" , Таблицы); - + НовыйТест(ТаблицаТестов, "Твиттер_ПолучитьСсылкуАвторизации" , "Получить ссылку авторизации" , Твиттер); НовыйТест(ТаблицаТестов, "Твиттер_ОбновитьТокен" , "Обновить токен" , Твиттер); НовыйТест(ТаблицаТестов, "Твиттер_СоздатьТекстовыйТвит" , "Текстовый твит" , Твиттер); @@ -172,7 +172,7 @@ НовыйТест(ТаблицаТестов, "Твиттер_СоздатьТвитСВидео" , "Твит с видео" , Твиттер); НовыйТест(ТаблицаТестов, "Твиттер_СоздатьТвитСГиф" , "Твит с гиф" , Твиттер); НовыйТест(ТаблицаТестов, "Твиттер_СоздатьТвитСОпросом" , "Твит с опросом" , Твиттер); - + НовыйТест(ТаблицаТестов, "Вайбер_ПолучитьИнформациюОКанале" , "Получить информацию канала" , Вайбер); НовыйТест(ТаблицаТестов, "Вайбер_ПолучитьДанныеПользователя" , "Получить данные пользователя" , Вайбер); НовыйТест(ТаблицаТестов, "Вайбер_ПолучитьОнлайнПользователей" , "Получить онлайн пользователей" , Вайбер); @@ -182,7 +182,7 @@ НовыйТест(ТаблицаТестов, "Вайбер_ОтправитьКонтакт" , "Отправить контакт" , Вайбер); НовыйТест(ТаблицаТестов, "Вайбер_ОтправитьЛокацию" , "Отправить локацию" , Вайбер); НовыйТест(ТаблицаТестов, "Вайбер_ОтправитьСсылку" , "Отправить ссылку" , Вайбер); - + НовыйТест(ТаблицаТестов, "Ноушн_СоздатьСтраницу" , "Создать страницу" , Ноушн); НовыйТест(ТаблицаТестов, "Ноушн_СоздатьИзменитьБазу" , "Создать/Изменить базу" , Ноушн); НовыйТест(ТаблицаТестов, "Ноушн_ПолучитьИнформациюОСтранице" , "Получить информацию о странице" , Ноушн); @@ -192,7 +192,7 @@ НовыйТест(ТаблицаТестов, "Ноушн_СоздатьУдалитьБлок" , "Создать/Удалить блок" , Ноушн); НовыйТест(ТаблицаТестов, "Ноушн_ПолучитьПользователей" , "Получить пользователей" , Ноушн); НовыйТест(ТаблицаТестов, "Ноушн_ПолучитьДанныеПользователя" , "Получить данные пользователя" , Ноушн); - + НовыйТест(ТаблицаТестов, "Слак_ПолучитьИнформациюОБоте" , "Получить информацию о боте" , Слак); НовыйТест(ТаблицаТестов, "Слак_ПолучитьСписокПользователей" , "Получить список пользователей" , Слак); НовыйТест(ТаблицаТестов, "Слак_ПолучитьСписокОбластей" , "Получить список областей" , Слак); @@ -206,12 +206,12 @@ НовыйТест(ТаблицаТестов, "Слак_ЗагрузитьУдалитьФайл" , "Загрузить/Удалить файл" , Слак); НовыйТест(ТаблицаТестов, "Слак_ПолучитьСписокВФ" , "Получить список внеш. файлов" , Слак); НовыйТест(ТаблицаТестов, "Слак_ЗагрузитьУдалитьВФ" , "Загрузить/Удалить внеш. файл" , Слак); - + НовыйТест(ТаблицаТестов, "АТ_СоздатьБазу" , "Создать/Изменить базу" , АирТ); НовыйТест(ТаблицаТестов, "АТ_СоздатьТаблицу" , "Создать/Изменить таблицу" , АирТ); НовыйТест(ТаблицаТестов, "АТ_СоздатьПоле" , "Создать/Изменить поле" , АирТ); НовыйТест(ТаблицаТестов, "АТ_СоздатьУдалитьЗаписи" , "Создать/Удалить записи" , АирТ); - + НовыйТест(ТаблицаТестов, "ДропБокс_ПолучитьОбновитьТокен" , "Получить/Обновить токен" , ДропБокс); НовыйТест(ТаблицаТестов, "ДропБокс_ЗагрузитьФайл" , "Загрузить файл" , ДропБокс); НовыйТест(ТаблицаТестов, "ДропБокс_ЗагрузитьФайлПоURL" , "Загрузить файл по URL" , ДропБокс); @@ -220,7 +220,7 @@ НовыйТест(ТаблицаТестов, "ДропБокс_ПолучитьАккаунт" , "Получить данные аккаунта" , ДропБокс); НовыйТест(ТаблицаТестов, "ДропБокс_РаботаСДоступами" , "Работа с доступами" , ДропБокс); НовыйТест(ТаблицаТестов, "ДропБокс_ПолучитьСписокФайловПапки" , "Получить список файлов папки" , ДропБокс); - + НовыйТест(ТаблицаТестов, "Б24_РаботаСТокеном" , "Работа с токеном" , Битрикс); НовыйТест(ТаблицаТестов, "Б24_СерверноеВремя" , "Серверное время" , Битрикс); НовыйТест(ТаблицаТестов, "Б24_РаботаСНовостями" , "Работа с новостями" , Битрикс); @@ -231,215 +231,215 @@ НовыйТест(ТаблицаТестов, "Б24_УчетРабочегоВремени" , "Учет рабочего времени" , Битрикс); НовыйТест(ТаблицаТестов, "Б24_РаботаСЧатами" , "Работа с чатами" , Битрикс); НовыйТест(ТаблицаТестов, "Б24_РаботаСУведомлениями" , "Работа с уведомлениями" , Битрикс); - + Возврат ТаблицаТестов; - -КонецФункции + +КонецФункции Функция ОжидаетЧто(Значение) Экспорт - + Попытка - + Модуль = ПолучитьОбщийМодуль("ЮТест"); Ожидаем = ТипЗнч(Модуль) = Тип("ОбщийМодуль"); - Возврат Модуль.ОжидаетЧто(Значение); - + Возврат Модуль.ОжидаетЧто(Значение); + Исключение Возврат Ожидаем.Что(Значение); КонецПопытки; - + КонецФункции Функция СформироватьТестыЯкс() Экспорт - + Модуль = ПолучитьОбщийМодуль("ЮТТесты"); Разделы = ПолучитьСоответствиеРазделовТестирования(); ТаблицаТестов = ПолучитьТаблицуТестов(); - + Для Каждого Раздел Из Разделы Цикл - + ТекущийРаздел = Раздел.Ключ; Отбор = Новый Структура("Раздел", ТекущийРаздел); ТестыРаздела = ТаблицаТестов.НайтиСтроки(Отбор); - + Набор = Модуль.ДобавитьТестовыйНабор(ТекущийРаздел); - + Для Каждого Тест Из ТестыРаздела Цикл Набор.ДобавитьСерверныйТест(Тест.Метод, Тест.Синоним); КонецЦикла; - + КонецЦикла; - + Возврат ""; - + КонецФункции Функция СформироватьТестыАссертс() Экспорт - + ТаблицаТестов = ПолучитьТаблицуТестов(); МассивТестов = Новый Массив; - - Для Каждого Тест Из ТаблицаТестов Цикл + + Для Каждого Тест Из ТаблицаТестов Цикл МассивТестов.Добавить(Тест.Метод); КонецЦикла; - + Возврат МассивТестов; - + КонецФункции -Функция ПолучитьПараметр(Параметр) Экспорт +Функция ПолучитьПараметр(Параметр) Экспорт - Путь = ПутьКФайлуДанных(); + Путь = ПутьКФайлуДанных(); Возврат ПолучитьЗначениеИзФайла(Параметр, Путь); КонецФункции Функция ПолучитьДвоичные(Параметр) Экспорт - - Путь = ПутьКФайлуДанных(); + + Путь = ПутьКФайлуДанных(); ПараметрЛокальный = Параметр + "Local"; ЗначениеОсновной = ПолучитьЗначениеИзФайла(Параметр , Путь); ЗначениеЛокальный = ПолучитьЗначениеИзФайла(ПараметрЛокальный, Путь); - + ФайлЛокальный = Новый Файл(ЗначениеЛокальный); - + Если ФайлЛокальный.Существует() Тогда Значение = Новый ДвоичныеДанные(ЗначениеЛокальный); Иначе Значение = ЗначениеОсновной; КонецЕсли; - + Если ТипЗнч(Значение) = Тип("Строка") Тогда - Значение = ПолучитьФайлПути(Значение, ПараметрЛокальный); + Значение = ПолучитьФайлПути(Значение, ПараметрЛокальный); КонецЕсли; - + Возврат Значение; - + КонецФункции Функция ПолучитьФайлПути(Знач Путь, ПараметрЛокальный, Знач СохранятьЛокально = Истина) Экспорт - - Если СтрНайти(Путь, "http") > 0 + + Если СтрНайти(Путь, "http") > 0 Или СтрНайти(Путь, "www") > 0 Тогда - - ИВФ = ПолучитьИмяВременногоФайла(); + + ИВФ = ПолучитьИмяВременногоФайла(); КопироватьФайл(Путь, ИВФ); - Путь = ИВФ; + Путь = ИВФ; Двоичные = Новый ДвоичныеДанные(Путь); - + Если СохранятьЛокально Тогда ЗаписатьПараметр(ПараметрЛокальный, ИВФ); Иначе УдалитьФайлы(ИВФ); КонецЕсли; - + Иначе - + Двоичные = Новый ДвоичныеДанные(Путь); - + КонецЕсли; - + Возврат Двоичные; - + КонецФункции Процедура ПараметрВКоллекцию(Параметр, Коллекция) Экспорт Значение = ПолучитьПараметр(Параметр); Коллекция.Вставить(Параметр, Значение); - + КонецПроцедуры Процедура ДвоичныеВКоллекцию(Параметр, Коллекция) Экспорт Значение = ПолучитьДвоичные(Параметр); Коллекция.Вставить(Параметр, Значение); - + КонецПроцедуры Процедура ЗаписатьПараметр(Параметр, Значение) Экспорт - - Путь = ПутьКФайлуДанных(); + + Путь = ПутьКФайлуДанных(); ЗаписатьПараметрВФайл(Параметр, Значение, Путь); - + КонецПроцедуры Процедура ЗаписатьЛог(Знач Результат, Знач Метод, Знач Библиотека = "") Экспорт - + Шапка = Строка(OPI_Инструменты.ПолучитьТекущуюДату()) + " | " + Метод; - + Попытка Данные = OPI_Инструменты.JSONСтрокой(Результат); Исключение Данные = "Не JSON: " + Строка(Результат); КонецПопытки; - - Данные = " " + Данные; - + + Данные = " " + Данные; + Сообщить(Шапка); Сообщить(Символы.ПС); Сообщить(Данные); Сообщить(Символы.ПС); Сообщить("---------------------------------"); Сообщить(Символы.ПС); - + Если ЗначениеЗаполнено(Библиотека) Тогда ЗаписатьФайлЛога(Данные, Метод, Библиотека); КонецЕсли; - + КонецПроцедуры #КонецОбласти #Область СлужебныеПроцедурыИФункции -Функция ПолучитьЗначениеИзФайла(Параметр, Путь) - - Значения = OPI_Инструменты.ПрочитатьJSONФайл(Путь); +Функция ПолучитьЗначениеИзФайла(Параметр, Путь) + + Значения = OPI_Инструменты.ПрочитатьJSONФайл(Путь); Возврат ?(Значения.Свойство(Параметр), Значения[Параметр], ""); - + КонецФункции Функция ПутьКФайлуДанных() - - Путь = ""; + + Путь = ""; ВозможныеПути = Новый Массив; ВозможныеПути.Добавить("./data.json"); ВозможныеПути.Добавить("C:\GDrive\Мой диск\data.json"); ВозможныеПути.Добавить("D:\GD\Мой диск\data.json"); - + Для Каждого ВозможныйПуть Из ВозможныеПути Цикл - + ФайлРепозитория = Новый Файл(ВозможныйПуть); - + Если ФайлРепозитория.Существует() Тогда Путь = ВозможныйПуть; - КонецЕсли; - + КонецЕсли; + КонецЦикла; - + Возврат Путь; - + КонецФункции Функция ПолучитьОбщийМодуль(Знач Имя) - - Модуль = Вычислить(Имя); - - Возврат Модуль; + + Модуль = Вычислить(Имя); + + Возврат Модуль; КонецФункции Процедура НовыйТест(ТаблицаЗначений, Знач Метод, Знач Синоним, Знач Раздел) - - НовыйТест = ТаблицаЗначений.Добавить(); + + НовыйТест = ТаблицаЗначений.Добавить(); НовыйТест.Метод = Метод; НовыйТест.Синоним = Синоним; НовыйТест.Раздел = Раздел; - + КонецПроцедуры Процедура ЗаписатьПараметрВФайл(Знач Параметр, Знач Значение, Знач Путь) - + Значения = OPI_Инструменты.ПрочитатьJSONФайл(Путь); Значения.Вставить(Параметр, Значение); @@ -452,37 +452,37 @@ КонецПроцедуры Процедура ЗаписатьФайлЛога(Знач Данные, Знач Метод, Знач Библиотека) - + Попытка - + ПутьЛогов = "./docs/ru/results"; ПутьЛоговБиблиотеки = ПутьЛогов + "/" + Библиотека; - + КаталогЛогов = Новый Файл(ПутьЛогов); - + Если Не КаталогЛогов.Существует() Тогда СоздатьКаталог(ПутьЛогов); КонецЕсли; - + КаталогЛоговБиблиотеки = Новый Файл(ПутьЛоговБиблиотеки); - + Если Не КаталогЛоговБиблиотеки.Существует() Тогда СоздатьКаталог(ПутьЛоговБиблиотеки); КонецЕсли; - + ПутьКФайлу = ПутьЛоговБиблиотеки + "/" + Метод + ".log"; ФайлЛога = Новый Файл(ПутьКФайлу); - + Если Не ФайлЛога.Существует() Тогда ДокументЛога = Новый ТекстовыйДокумент; ДокументЛога.УстановитьТекст(Данные); ДокументЛога.Записать(ПутьКФайлу); КонецЕсли; - + Исключение - Сообщить("Не удалось записать файл лога!: " + ОписаниеОшибки()); + Сообщить("Не удалось записать файл лога!: " + ОписаниеОшибки()); КонецПопытки; - + КонецПроцедуры #КонецОбласти diff --git a/src/ru/OInt/tools/Modules/OPI_ПреобразованиеТипов.os b/src/ru/OInt/tools/Modules/OPI_ПреобразованиеТипов.os index 7ae28df9e3..c474e3cb3c 100644 --- a/src/ru/OInt/tools/Modules/OPI_ПреобразованиеТипов.os +++ b/src/ru/OInt/tools/Modules/OPI_ПреобразованиеТипов.os @@ -39,268 +39,268 @@ #Область СлужебныйПрограммныйИнтерфейс Процедура ПолучитьДвоичныеДанные(Значение) Экспорт - + Если Значение = Неопределено Тогда Возврат; КонецЕсли; - - Попытка - + + Попытка + Если ТипЗнч(Значение) = Тип("ДвоичныеДанные") Тогда Возврат; Иначе - + Файл = Новый Файл(Значение); - + Если Файл.Существует() Тогда Значение = Новый ДвоичныеДанные(Значение); - + ИначеЕсли СтрНайти(Значение, "//") Тогда - + Значение = OPI_Инструменты.Get(Значение); - + Иначе - + Значение = Base64Значение(Значение); - + КонецЕсли; - + КонецЕсли; - + Исключение ВызватьИсключение "Ошибка получения двоичных данных из параметра: " + ОписаниеОшибки(); КонецПопытки; - + КонецПроцедуры Процедура ПолучитьДвоичныеИлиПоток(Значение) Экспорт - + Если Значение = Неопределено Тогда Возврат; КонецЕсли; - + Если ТипЗнч(Значение) <> Тип("Строка") Тогда ПолучитьДвоичныеДанные(Значение); Возврат; КонецЕсли; - + Файл = Новый Файл(Значение); - + Если Файл.Существует() Тогда - Значение = Новый ФайловыйПоток(Значение, РежимОткрытияФайла.Открыть); + Значение = Новый ФайловыйПоток(Значение, РежимОткрытияФайла.Открыть); Иначе ПолучитьДвоичныеДанные(Значение); КонецЕсли; - + КонецПроцедуры Процедура ПолучитьКоллекцию(Значение) Экспорт - + Если Значение = Неопределено Тогда Возврат; КонецЕсли; - - Попытка - + + Попытка + ИсходноеЗначение = Значение; - + Если ЭтоКоллекция(Значение) Тогда Возврат; Иначе - + Если ТипЗнч(Значение) = Тип("ДвоичныеДанные") Тогда - Значение = ПолучитьСтрокуИзДвоичныхДанных(Значение); + Значение = ПолучитьСтрокуИзДвоичныхДанных(Значение); Иначе - Значение = OPI_Инструменты.ЧислоВСтроку(Значение); + Значение = OPI_Инструменты.ЧислоВСтроку(Значение); КонецЕсли; - + Файл = Новый Файл(Значение); ЧтениеJSON = Новый ЧтениеJSON; - + Если Файл.Существует() Тогда - + ЧтениеJSON.ОткрытьФайл(Значение); - + ИначеЕсли СтрНачинаетсяС(нРег(Значение), "http") Тогда - + ИВФ = ПолучитьИмяВременногоФайла(); КопироватьФайл(Значение, ИВФ); ЧтениеJSON.ОткрытьФайл(ИВФ); ЧтениеJSON.Прочитать(); - + УдалитьФайлы(ИВФ); - + Иначе - + ЧтениеJSON.УстановитьСтроку(СокрЛП(Значение)); - + КонецЕсли; - + Значение = ПрочитатьJSON(ЧтениеJSON, Истина, Неопределено, ФорматДатыJSON.ISO); ЧтениеJSON.Закрыть(); - + Если (Не ЭтоКоллекция(Значение)) Или Не ЗначениеЗаполнено(Значение) Тогда - + Значение = ИсходноеЗначение; ПолучитьМассив(Значение); - + КонецЕсли; - + КонецЕсли; - + Исключение - + Значение = ИсходноеЗначение; - ПолучитьМассив(Значение); - + ПолучитьМассив(Значение); + КонецПопытки; - + КонецПроцедуры Процедура ПолучитьМассив(Значение) Экспорт - + Если ТипЗнч(Значение) = Тип("Массив") Тогда Возврат; КонецЕсли; - - Если ТипЗнч(Значение) = Тип("Строка") + + Если ТипЗнч(Значение) = Тип("Строка") И СтрНачинаетсяС(Значение, "[") И СтрЗаканчиваетсяНа(Значение, "]") Тогда - + ЗапятаяВКавычках = "','"; - + Значение = СтрЗаменить(Значение, "['" , ""); Значение = СтрЗаменить(Значение, "']" , ""); Значение = СтрЗаменить(Значение, "', '" , ЗапятаяВКавычках); Значение = СтрЗаменить(Значение, "' , '", ЗапятаяВКавычках); Значение = СтрЗаменить(Значение, "' ,'" , ЗапятаяВКавычках); - + Значение = СтрРазделить(Значение, ЗапятаяВКавычках, Ложь); - - Для Н = 0 По Значение.ВГраница() Цикл + + Для Н = 0 По Значение.ВГраница() Цикл Значение[Н] = СокрЛП(Значение[Н]); КонецЦикла; - + Иначе - + Если ТипЗнч(Значение) = Тип("Число") Тогда - Значение = OPI_Инструменты.ЧислоВСтроку(Значение); + Значение = OPI_Инструменты.ЧислоВСтроку(Значение); КонецЕсли; - + OPI_Инструменты.ЗначениеВМассив(Значение); - + КонецЕсли; - + КонецПроцедуры Процедура ПолучитьБулево(Значение) Экспорт - + Если Значение = Неопределено Тогда Возврат; КонецЕсли; - - Попытка - + + Попытка + Если ТипЗнч(Значение) = Тип("Булево") Тогда Возврат; Иначе - Значение = Булево(Значение); + Значение = Булево(Значение); КонецЕсли; - + Исключение ВызватьИсключение "Ошибка получения данных булево из параметра"; КонецПопытки; - + КонецПроцедуры Процедура ПолучитьСтроку(Значение, Знач ИзИсточника = Ложь) Экспорт - + Если Значение = Неопределено Тогда Возврат; КонецЕсли; - - Попытка - + + Попытка + Если ЭтоСимвольное(Значение) Тогда - + Если Не ИзИсточника Тогда Значение = OPI_Инструменты.ЧислоВСтроку(Значение); - Возврат; + Возврат; КонецЕсли; - - Значение = OPI_Инструменты.ЧислоВСтроку(Значение); + + Значение = OPI_Инструменты.ЧислоВСтроку(Значение); Файл = Новый Файл(Значение); - + Если Файл.Существует() Тогда - + ЧтениеТекста = Новый ЧтениеТекста(Значение); Значение = ЧтениеТекста.Прочитать(); ЧтениеТекста.Закрыть(); - + ИначеЕсли СтрНачинаетсяС(нРег(Значение), "http") Тогда - + ИВФ = ПолучитьИмяВременногоФайла(); КопироватьФайл(Значение, ИВФ); - + ЧтениеТекста = Новый ЧтениеТекста(ИВФ); Значение = ЧтениеТекста.Прочитать(); ЧтениеТекста.Закрыть(); - + УдалитьФайлы(ИВФ); - + Иначе - + Возврат; - + КонецЕсли; - + ИначеЕсли ТипЗнч(Значение) = Тип("ДвоичныеДанные") Тогда - + Значение = ПолучитьСтрокуИзДвоичныхДанных(Значение); - + ИначеЕсли ЭтоКоллекция(Значение) Тогда - - Значение = OPI_Инструменты.JSONСтрокой(Значение); - + + Значение = OPI_Инструменты.JSONСтрокой(Значение); + Иначе Возврат; КонецЕсли; - + Исключение Значение = Строка(Значение); Возврат; КонецПопытки; - + КонецПроцедуры Процедура ПолучитьДату(Значение) Экспорт - + Если Значение = Неопределено Тогда Возврат; КонецЕсли; - + Дата = "Дата"; - - Попытка - + + Попытка + Если ТипЗнч(Значение) = Тип(Дата) Тогда Возврат; - Иначе - Значение = XMLЗначение(Тип(Дата), Значение); + Иначе + Значение = XMLЗначение(Тип(Дата), Значение); КонецЕсли; - + Исключение - ООД = Новый ОписаниеТипов(Дата); + ООД = Новый ОписаниеТипов(Дата); Значение = ООД.ПривестиЗначение(Значение); КонецПопытки; - + КонецПроцедуры Процедура ПолучитьЧисло(Значение) Экспорт - + ОписаниеТипа = Новый ОписаниеТипов("Число"); - Значение = ОписаниеТипа.ПривестиЗначение(Значение); - + Значение = ОписаниеТипа.ПривестиЗначение(Значение); + КонецПроцедуры #КонецОбласти @@ -308,19 +308,19 @@ #Область СлужебныеПроцедурыИФункции Функция ЭтоКоллекция(Знач Значение) - - Возврат ТипЗнч(Значение) = Тип("Массив") + + Возврат ТипЗнч(Значение) = Тип("Массив") Или ТипЗнч(Значение) = Тип("Структура") Или ТипЗнч(Значение) = Тип("Соответствие"); - -КонецФункции + +КонецФункции Функция ЭтоСимвольное(Знач Значение) - - Возврат ТипЗнч(Значение) = Тип("Строка") - Или ТипЗнч(Значение) = Тип("Число") + + Возврат ТипЗнч(Значение) = Тип("Строка") + Или ТипЗнч(Значение) = Тип("Число") Или ТипЗнч(Значение) = Тип("Дата"); - -КонецФункции + +КонецФункции #КонецОбласти diff --git a/src/ru/OInt/tools/Modules/internal/Modules/OPI_Инструменты.os b/src/ru/OInt/tools/Modules/internal/Modules/OPI_Инструменты.os index 33bdf54b6b..bf12e3d929 100644 --- a/src/ru/OInt/tools/Modules/internal/Modules/OPI_Инструменты.os +++ b/src/ru/OInt/tools/Modules/internal/Modules/OPI_Инструменты.os @@ -56,169 +56,169 @@ #Область ЗапросыСТелом Функция Post(Знач URL - , Знач Параметры = "" + , Знач Параметры = "" , Знач ДопЗаголовки = "" - , Знач JSON = Истина - , Знач ПолныйОтвет = Ложь - , Знач ФайлОтвета = Неопределено) Экспорт - + , Знач JSON = Истина + , Знач ПолныйОтвет = Ложь + , Знач ФайлОтвета = Неопределено) Экспорт + Возврат ВыполнитьЗапросСТелом(URL, "POST", Параметры, ДопЗаголовки, JSON, ПолныйОтвет, ФайлОтвета); - + КонецФункции Функция Patch(Знач URL - , Знач Параметры = "" + , Знач Параметры = "" , Знач ДопЗаголовки = "" - , Знач JSON = Истина - , Знач ПолныйОтвет = Ложь - , Знач ФайлОтвета = Неопределено) Экспорт - + , Знач JSON = Истина + , Знач ПолныйОтвет = Ложь + , Знач ФайлОтвета = Неопределено) Экспорт + Возврат ВыполнитьЗапросСТелом(URL, "PATCH", Параметры, ДопЗаголовки, JSON, ПолныйОтвет, ФайлОтвета); - + КонецФункции Функция Put(Знач URL - , Знач Параметры = "" + , Знач Параметры = "" , Знач ДопЗаголовки = "" - , Знач JSON = Истина - , Знач ПолныйОтвет = Ложь - , Знач ФайлОтвета = Неопределено) Экспорт - + , Знач JSON = Истина + , Знач ПолныйОтвет = Ложь + , Знач ФайлОтвета = Неопределено) Экспорт + Возврат ВыполнитьЗапросСТелом(URL, "PUT", Параметры, ДопЗаголовки, JSON, ПолныйОтвет, ФайлОтвета); - + КонецФункции Функция PostBinary(Знач URL , Знач Тело , Знач ДопЗаголовки , Знач ПолныйОтвет = Ложь - , Знач ТипДанных = "application/octet-stream") Экспорт - + , Знач ТипДанных = "application/octet-stream") Экспорт + Возврат ВыполнитьЗапросСДвоичнымиДанными(URL, "POST", Тело, ДопЗаголовки, ПолныйОтвет, ТипДанных); - + КонецФункции -#КонецОбласти +#КонецОбласти #Область ЗапросыMultipart Функция PostMultipart(Знач URL - , Знач Параметры = "" - , Знач Файлы = "" - , Знач ТипКонтента = "image/jpeg" + , Знач Параметры = "" + , Знач Файлы = "" + , Знач ТипКонтента = "image/jpeg" , Знач ДопЗаголовки = "" - , Знач ФайлОтвета = Неопределено) Экспорт + , Знач ФайлОтвета = Неопределено) Экспорт Возврат ВыполнитьЗапросМультипарт(URL, "POST", Параметры, Файлы, ТипКонтента, ДопЗаголовки, ФайлОтвета); КонецФункции Функция PutMultipart(Знач URL - , Знач Параметры = "" - , Знач Файлы = "" - , Знач ТипКонтента = "image/jpeg" + , Знач Параметры = "" + , Знач Файлы = "" + , Знач ТипКонтента = "image/jpeg" , Знач ДопЗаголовки = "" - , Знач ФайлОтвета = Неопределено) Экспорт + , Знач ФайлОтвета = Неопределено) Экспорт Возврат ВыполнитьЗапросМультипарт(URL, "PUT", Параметры, Файлы, ТипКонтента, ДопЗаголовки, ФайлОтвета); КонецФункции Функция PostMultipartRelated(Знач URL - , Знач JSON = "" - , Знач Файлы = "" + , Знач JSON = "" + , Знач Файлы = "" , Знач ДопЗаголовки = "" - , Знач ФайлОтвета = Неопределено) Экспорт - + , Знач ФайлОтвета = Неопределено) Экспорт + Возврат ВыполнитьЗапросМультипартРелэйтед(URL, "POST", JSON, Файлы, ДопЗаголовки, ФайлОтвета); - + КонецФункции Функция PatchMultipartRelated(Знач URL - , Знач JSON = "" - , Знач Файлы = "" + , Знач JSON = "" + , Знач Файлы = "" , Знач ДопЗаголовки = "" - , Знач ФайлОтвета = Неопределено) Экспорт - + , Знач ФайлОтвета = Неопределено) Экспорт + Возврат ВыполнитьЗапросМультипартРелэйтед(URL, "PATCH", JSON, Файлы, ДопЗаголовки, ФайлОтвета); - + КонецФункции #КонецОбласти #Область Прочее -Процедура ОбработатьОтвет(Ответ, Знач ПолныйОтвет = Ложь) Экспорт - +Процедура ОбработатьОтвет(Ответ, Знач ПолныйОтвет = Ложь) Экспорт + Если ПолныйОтвет Или ТипЗнч(Ответ) <> Тип("HTTPОтвет") Тогда Возврат; КонецЕсли; - + ФайлТела = Ответ.ПолучитьИмяФайлаТела(); - + Если Не ФайлТела = Неопределено Тогда - Ответ = ФайлТела; + Ответ = ФайлТела; Возврат; КонецЕсли; - - GZip = "gzip"; - НужнаРаспаковка = - Ответ.Заголовки.Получить("Content-Encoding") = GZip + + GZip = "gzip"; + НужнаРаспаковка = + Ответ.Заголовки.Получить("Content-Encoding") = GZip Или Ответ.Заголовки.Получить("content-encoding") = GZip; - + Если НужнаРаспаковка Тогда Ответ = РаспаковатьОтвет(Ответ); КонецЕсли; - + Ответ = ?(ТипЗнч(Ответ) = Тип("HTTPОтвет"), Ответ.ПолучитьТелоКакДвоичныеДанные(), Ответ); - + Если ТипЗнч(Ответ) = Тип("ДвоичныеДанные") Тогда - + Попытка Ответ = JsonВСтруктуру(Ответ); Исключение Возврат; КонецПопытки; - + КонецЕсли; - + КонецПроцедуры Функция СоздатьЗапрос(Знач Адрес, Знач ДопЗаголовки = "", Знач ТипДанных = "") Экспорт - + Заголовки = Новый Соответствие; Заголовки.Вставить("Accept-Encoding", "gzip"); Заголовки.Вставить("Accept" , "*/*"); Заголовки.Вставить("Connection" , "keep-alive"); Заголовки.Вставить("Accept-Charset" , "utf-8"); - + Если ЗначениеЗаполнено(ТипДанных) Тогда Заголовки.Вставить("Content-Type", ТипДанных); КонецЕсли; - + Если ТипЗнч(ДопЗаголовки) = Тип("Соответствие") Тогда - + Для Каждого Заголовок Из ДопЗаголовки Цикл Заголовки.Вставить(Заголовок.Ключ, Заголовок.Значение); КонецЦикла; - + КонецЕсли; - + НовыйЗапрос = Новый HTTPЗапрос(Адрес, Заголовки); - + Возврат НовыйЗапрос; - + КонецФункции Функция СоздатьСоединение(Знач Сервер, Знач Пользователь = "", Знач Пароль = "") Экспорт - - Попытка + + Попытка SSL = Новый ЗащищенноеСоединениеOpenSSL; Возврат Новый HTTPСоединение(Сервер, 443, Пользователь, Пароль, , 3000, SSL); Исключение Возврат Новый HTTPСоединение(Сервер, 443, Пользователь, Пароль, , 3000); КонецПопытки; - + КонецФункции #КонецОбласти @@ -236,12 +236,12 @@ СтрокаПараметров = "?"; Для Каждого Параметр Из Параметры Цикл - + ЗначениеПараметра = ПреобразоватьПараметрВСтроку(Параметр.Значение); - - СтрокаПараметров = СтрокаПараметров - + Параметр.Ключ - + "=" + + СтрокаПараметров = СтрокаПараметров + + Параметр.Ключ + + " =" + ЗначениеПараметра + "&"; КонецЦикла; @@ -255,18 +255,18 @@ Функция РазбитьURL(Знач URL) Экспорт URL = СтрЗаменить(URL, "https://", ""); - URL = СтрЗаменить(URL, "http://", ""); - URL = СтрЗаменить(URL, ":443", ""); + URL = СтрЗаменить(URL, "http://" , ""); + URL = СтрЗаменить(URL, ":443" , ""); Адрес = Прав(URL, СтрДлина(URL) - СтрНайти(URL, "/", НаправлениеПоиска.СНачала) + 1); Сервер = Лев(URL, СтрНайти(URL, "/", НаправлениеПоиска.СНачала) - 1); - - Попытка - SSL = Новый ЗащищенноеСоединениеOpenSSL; + + Попытка + SSL = Новый ЗащищенноеСоединениеOpenSSL; Исключение Сервер = "https://" + Сервер; КонецПопытки; - + СтруктураВозврата = Новый Структура; СтруктураВозврата.Вставить("Сервер", Сервер); СтруктураВозврата.Вставить("Адрес" , Адрес); @@ -280,7 +280,7 @@ Если Не ЗначениеЗаполнено(Текст) Тогда Возврат ""; КонецЕсли; - + Текст = ?(ТипЗнч(Текст) = Тип("ДвоичныеДанные"), ПолучитьСтрокуИзДвоичныхДанных(Текст), Текст); ЧтениеJSON = Новый ЧтениеJSON; @@ -305,14 +305,14 @@ , Ложь); Попытка - + ЗаписьJSON = Новый ЗаписьJSON; ЗаписьJSON.УстановитьСтроку(ПараметрыJSON); - + ЗаписатьJSON(ЗаписьJSON, Данные); Возврат ЗаписьJSON.Закрыть(); - - Исключение + + Исключение Возврат "НЕ JSON: " + Строка(Данные); КонецПопытки; @@ -323,15 +323,15 @@ КонецФункции Функция ПрочитатьJSONФайл(Знач Путь) Экспорт - + ЧтениеJSON = Новый ЧтениеJSON; - ЧтениеJSON.ОткрытьФайл(Путь); - Значения = ПрочитатьJSON(ЧтениеJSON); - + ЧтениеJSON.ОткрытьФайл(Путь); + Значения = ПрочитатьJSON(ЧтениеJSON); + ЧтениеJSON.Закрыть(); - + Возврат Значения; - + КонецФункции Функция ПараметрыЗапросаВСоответствие(Знач СтрокаПараметров) Экспорт @@ -355,104 +355,104 @@ КонецФункции Функция ПолучитьТекущуюДату() Экспорт - Возврат МестноеВремя(ТекущаяУниверсальнаяДата()); + Возврат МестноеВремя(ТекущаяУниверсальнаяДата()); КонецФункции Функция UNIXTime(Знач Дата) Экспорт - + ОТД = Новый ОписаниеТипов("Дата"); Дата = ОТД.ПривестиЗначение(Дата); - + UNIX = Формат(Дата - Дата(1970, 1, 1, 1, 0, 0), "ЧЦ=10; ЧДЦ=0; ЧГ=0"); - UNIX = СтрЗаменить(UNIX, ",", ""); + UNIX = СтрЗаменить(UNIX, "," , ""); UNIX = СтрЗаменить(UNIX, Символы.НПП, ""); - UNIX = СтрЗаменить(UNIX, " ", ""); + UNIX = СтрЗаменить(UNIX, " " , ""); UNIX = Лев(UNIX, 10); - + Возврат UNIX; - + КонецФункции Функция ИнформацияОПрогрессе(Знач Текущее, Знач Всего, Знач ЕдИзм, Знач Делитель = 1) Экспорт - + Целое = 100; Текущее = Окр(Текущее / Делитель, 2); - Всего = Окр(Всего / Делитель, 2); + Всего = Окр(Всего / Делитель, 2); Процент = Цел(Текущее / Всего * Целое); - + СтрТекущее = ЧислоВСтроку(Текущее); СтрВсего = ЧислоВСтроку(Всего); СтрПроцент = ЧислоВСтроку(Процент); - + Информация = СтрТекущее + "/" + СтрВсего + " " + ЕдИзм + " ( " + СтрПроцент + "% )"; - + Возврат Информация; - + КонецФункции Функция ПреобразоватьДанныеСПолучениемРазмера(Данные, Знач МинимальныйРазмерДляПотока = 0) Экспорт - + Размер = 0; - + Если ТипЗнч(Данные) = Тип("Строка") Тогда - + ФайлНаДиске = Новый Файл(Данные); - - Если ФайлНаДиске.Существует() Тогда - Размер = ФайлНаДиске.Размер(); + + Если ФайлНаДиске.Существует() Тогда + Размер = ФайлНаДиске.Размер(); Иначе OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Данные); Размер = Данные.Размер(); КонецЕсли; - + Иначе OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Данные); Размер = Данные.Размер(); КонецЕсли; - + Если ЗначениеЗаполнено(МинимальныйРазмерДляПотока) Тогда Если Размер < МинимальныйРазмерДляПотока Тогда OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Данные); Иначе - OPI_ПреобразованиеТипов.ПолучитьДвоичныеИлиПоток(Данные); - КонецЕсли; + OPI_ПреобразованиеТипов.ПолучитьДвоичныеИлиПоток(Данные); + КонецЕсли; Иначе OPI_ПреобразованиеТипов.ПолучитьДвоичныеИлиПоток(Данные); КонецЕсли; - + Возврат Размер; - + КонецФункции Процедура ЗначениеВМассив(Значение) Экспорт - + Значение_ = Новый Массив; Значение_.Добавить(Значение); - Значение = Значение_; + Значение = Значение_; КонецПроцедуры Процедура ЗаменитьСпецСимволы(Текст, Разметка = "Markdown") Экспорт - + СоответствиеСимволов = Новый Соответствие; - + Если Разметка = "HTML" Тогда - + СоответствиеСимволов.Вставить("&", "&"); - + ИначеЕсли Разметка = "MarkdownV2" Тогда - + СоответствиеСимволов.Вставить("-", "\-"); СоответствиеСимволов.Вставить("+", "\+"); - СоответствиеСимволов.Вставить("#", "\#"); + СоответствиеСимволов.Вставить("#", "\#"); СоответствиеСимволов.Вставить("=", "\="); - СоответствиеСимволов.Вставить("{", "\{"); - СоответствиеСимволов.Вставить("}", "\}"); + СоответствиеСимволов.Вставить("{", "\{"); + СоответствиеСимволов.Вставить("}", "\}"); СоответствиеСимволов.Вставить(".", "\."); - + Иначе Возврат; - КонецЕсли; + КонецЕсли; Для Каждого СимволМассива Из СоответствиеСимволов Цикл Текст = СтрЗаменить(Текст, СимволМассива.Ключ, СимволМассива.Значение); @@ -461,80 +461,80 @@ КонецПроцедуры Процедура УдалитьПустыеПоляКоллекции(Коллекция) Экспорт - + ТипКоллекции = ТипЗнч(Коллекция); ВыходнаяКоллекция = Новый(ТипКоллекции); - + Если ТипКоллекции = Тип("Соответствие") Или ТипКоллекции = Тип("Структура") Тогда - + УдалитьПустыеКлючиЗначения(Коллекция, ВыходнаяКоллекция); - + ИначеЕсли ТипКоллекции = Тип("Массив") Тогда - + УдалитьПустыеЭлементыМассива(Коллекция, ВыходнаяКоллекция); - + Иначе - + ВыходнаяКоллекция = Коллекция; - + КонецЕсли; - + Коллекция = ВыходнаяКоллекция; - + КонецПроцедуры Процедура Пауза(Знач Секунды) Экспорт - + Соединение = Новый HTTPСоединение("1C.ru", 11111, , , , Секунды); Попытка Соединение.Получить(Новый HTTPЗапрос("")); Исключение - Возврат; + Возврат; КонецПопытки; - + КонецПроцедуры Процедура ДобавитьПоле(Знач Имя, Знач Значение, Знач Тип, Коллекция) Экспорт - + Заполнено = ЗначениеЗаполнено(Значение); - + Если Не Заполнено Тогда Возврат; КонецЕсли; - - Если Тип = "Дата" Тогда + + Если Тип = "Дата" Тогда OPI_ПреобразованиеТипов.ПолучитьДату(Значение); Значение = UNIXTime(Значение); - + ИначеЕсли Тип = "ДатаISO" Тогда OPI_ПреобразованиеТипов.ПолучитьДату(Значение); - Значение = XMLСтрока(Значение); - + Значение = XMLСтрока(Значение); + ИначеЕсли Тип = "Коллекция" Тогда - OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Значение); - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Значение); + ИначеЕсли Тип = "Булево" Тогда - OPI_ПреобразованиеТипов.ПолучитьБулево(Значение); - + OPI_ПреобразованиеТипов.ПолучитьБулево(Значение); + ИначеЕсли Тип = "СтрокаФайла" Тогда OPI_ПреобразованиеТипов.ПолучитьСтроку(Значение, Истина); - + ИначеЕсли Тип = "Массив" Тогда OPI_ПреобразованиеТипов.ПолучитьМассив(Значение); - + ИначеЕсли Тип = "ДвоичныеДанные" Тогда OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Значение); - + ИначеЕсли Тип = "Число" Тогда OPI_ПреобразованиеТипов.ПолучитьЧисло(Значение); - + Иначе OPI_ПреобразованиеТипов.ПолучитьСтроку(Значение); - + КонецЕсли; - + Коллекция.Вставить(Имя, Значение); - + КонецПроцедуры #КонецОбласти @@ -545,24 +545,24 @@ Функция ВыполнитьЗапросСТелом(Знач URL , Знач Вид - , Знач Параметры = "" + , Знач Параметры = "" , Знач ДопЗаголовки = "" - , Знач JSON = Истина - , Знач ПолныйОтвет = Ложь - , Знач ФайлОтвета = Неопределено) - + , Знач JSON = Истина + , Знач ПолныйОтвет = Ложь + , Знач ФайлОтвета = Неопределено) + Если Не ЗначениеЗаполнено(Параметры) Тогда Параметры = Новый Структура; КонецЕсли; - - ТипДанных = ?(JSON, "application/json; charset=utf-8", "application/x-www-form-urlencoded; charset=utf-8"); + + ТипДанных = ?(JSON, "application/json; charset=utf-8", "application/x-www-form-urlencoded; charset=utf-8"); СтруктураURL = РазбитьURL(URL); Сервер = СтруктураURL["Сервер"]; Адрес = СтруктураURL["Адрес"]; - + Запрос = СоздатьЗапрос(Адрес, ДопЗаголовки, ТипДанных); Соединение = СоздатьСоединение(Сервер); - + УстановитьТелоЗапроса(Запрос, Параметры, JSON); Если ЗначениеЗаполнено(ФайлОтвета) Тогда @@ -570,17 +570,17 @@ Иначе Ответ = Соединение.ВызватьHTTPМетод(Вид, Запрос); КонецЕсли; - - Если ЭтоПереадресация(Ответ) Тогда + + Если ЭтоПереадресация(Ответ) Тогда Ответ = ВыполнитьЗапросСТелом(Ответ.Заголовки["Location"] , Вид , Параметры , ДопЗаголовки , JSON , ПолныйОтвет - , ФайлОтвета); - Иначе - ОбработатьОтвет(Ответ, ПолныйОтвет); + , ФайлОтвета); + Иначе + ОбработатьОтвет(Ответ, ПолныйОтвет); КонецЕсли; Возврат Ответ; @@ -593,29 +593,29 @@ , Знач ДопЗаголовки , Знач ПолныйОтвет , Знач ТипДанных) - + СтруктураURL = РазбитьURL(URL); Сервер = СтруктураURL["Сервер"]; Адрес = СтруктураURL["Адрес"]; - + Запрос = СоздатьЗапрос(Адрес, ДопЗаголовки, ТипДанных); Соединение = СоздатьСоединение(Сервер); - + Если Не Данные.Размер() = 0 Тогда Запрос.УстановитьТелоИзДвоичныхДанных(Данные); КонецЕсли; - + Ответ = Соединение.ВызватьHTTPМетод(Вид, Запрос); - Если ЭтоПереадресация(Ответ) Тогда + Если ЭтоПереадресация(Ответ) Тогда Ответ = ВыполнитьЗапросСДвоичнымиДанными(Ответ.Заголовки["Location"] , Вид , Данные , ДопЗаголовки , ПолныйОтвет - , ТипДанных); - Иначе - ОбработатьОтвет(Ответ, ПолныйОтвет); + , ТипДанных); + Иначе + ОбработатьОтвет(Ответ, ПолныйОтвет); КонецЕсли; Возврат Ответ; @@ -624,10 +624,10 @@ Функция ВыполнитьЗапросБезТела(Знач URL , Знач Вид - , Знач Параметры = "" + , Знач Параметры = "" , Знач ДопЗаголовки = "" - , Знач ФайлОтвета = Неопределено) - + , Знач ФайлОтвета = Неопределено) + Если Не ЗначениеЗаполнено(Параметры) Тогда Параметры = Новый Структура; КонецЕсли; @@ -635,34 +635,34 @@ СтруктураURL = РазбитьURL(URL); Сервер = СтруктураURL["Сервер"]; Адрес = СтруктураURL["Адрес"] + ПараметрыЗапросаВСтроку(Параметры); - + Запрос = СоздатьЗапрос(Адрес, ДопЗаголовки); - Соединение = СоздатьСоединение(Сервер); - + Соединение = СоздатьСоединение(Сервер); + Если ЗначениеЗаполнено(ФайлОтвета) Тогда Ответ = Соединение.ВызватьHTTPМетод(Вид, Запрос, ФайлОтвета); Иначе Ответ = Соединение.ВызватьHTTPМетод(Вид, Запрос); КонецЕсли; - - Если ЭтоПереадресация(Ответ) Тогда - Ответ = ВыполнитьЗапросБезТела(Ответ.Заголовки["Location"], Вид, Параметры, ДопЗаголовки, ФайлОтвета); - Иначе - ОбработатьОтвет(Ответ); + + Если ЭтоПереадресация(Ответ) Тогда + Ответ = ВыполнитьЗапросБезТела(Ответ.Заголовки["Location"], Вид, Параметры, ДопЗаголовки, ФайлОтвета); + Иначе + ОбработатьОтвет(Ответ); КонецЕсли; Возврат Ответ; - + КонецФункции Функция ВыполнитьЗапросМультипарт(Знач URL , Знач Вид - , Знач Параметры = "" - , Знач Файлы = "" - , Знач ТипКонтента = "image/jpeg" + , Знач Параметры = "" + , Знач Файлы = "" + , Знач ТипКонтента = "image/jpeg" , Знач ДопЗаголовки = "" - , Знач ФайлОтвета = Неопределено) - + , Знач ФайлОтвета = Неопределено) + Если Не ЗначениеЗаполнено(Параметры) Тогда Параметры = Новый Структура; КонецЕсли; @@ -679,10 +679,10 @@ СтруктураURL = РазбитьURL(URL); Сервер = СтруктураURL["Сервер"]; Адрес = СтруктураURL["Адрес"]; - + Запрос = СоздатьЗапрос(Адрес, ДопЗаголовки, ТипДанных); Соединение = СоздатьСоединение(Сервер); - + ТелоЗапроса = ПолучитьИмяВременногоФайла(); ЗаписьТекста = Новый ЗаписьДанных(ТелоЗапроса , КодировкаТекста.UTF8 @@ -694,47 +694,47 @@ ЗаписатьПараметрыМультипарт(ЗаписьТекста, Boundary, Параметры); ЗаписатьФайлыМультипарт(ЗаписьТекста, Boundary, ТипКонтента, Файлы); - + ЗаписьТекста.ЗаписатьСтроку("--" + boundary + "--" + РазделительСтрок); ЗаписьТекста.Закрыть(); Запрос.УстановитьИмяФайлаТела(ТелоЗапроса); - + Если ЗначениеЗаполнено(ФайлОтвета) Тогда Ответ = Соединение.ВызватьHTTPМетод(Вид, Запрос, ФайлОтвета); Иначе Ответ = Соединение.ВызватьHTTPМетод(Вид, Запрос); КонецЕсли; - + ЭтоПереадресация = Ответ.КодСостояния >= Переадресация И Ответ.КодСостояния < Ошибка; - - Если ЭтоПереадресация Тогда + + Если ЭтоПереадресация Тогда Ответ = ВыполнитьЗапросМультипарт(Ответ.Заголовки["Location"] , Вид , Параметры , Файлы , ТипКонтента , ДопЗаголовки - , ФайлОтвета); - Иначе - ОбработатьОтвет(Ответ); + , ФайлОтвета); + Иначе + ОбработатьОтвет(Ответ); КонецЕсли; - + Запрос = Неопределено; ЗаписьТекста = Неопределено; - + УдалитьФайлы(ТелоЗапроса); Возврат Ответ; - + КонецФункции Функция ВыполнитьЗапросМультипартРелэйтед(Знач URL , Знач Вид - , Знач JSON = "" - , Знач Файлы = "" + , Знач JSON = "" + , Знач Файлы = "" , Знач ДопЗаголовки = "" - , Знач ФайлОтвета = Неопределено) - + , Знач ФайлОтвета = Неопределено) + Переадресация = 300; Ошибка = 400; Boundary = СтрЗаменить(Строка(Новый УникальныйИдентификатор), "-", ""); @@ -743,10 +743,10 @@ СтруктураURL = РазбитьURL(URL); Сервер = СтруктураURL["Сервер"]; Адрес = СтруктураURL["Адрес"]; - + Запрос = СоздатьЗапрос(Адрес, ДопЗаголовки, ТипДанных); Соединение = СоздатьСоединение(Сервер); - + ТелоЗапроса = ПолучитьИмяВременногоФайла(); ЗаписьТекста = Новый ЗаписьДанных(ТелоЗапроса , КодировкаТекста.UTF8 @@ -755,36 +755,36 @@ , Ложь , "" , Ложь); - + ЗаписатьJSONМультипарт(ЗаписьТекста, Boundary, JSON); - ЗаписатьФайлыРелэйтед(ЗаписьТекста, Boundary, Файлы); - + ЗаписатьФайлыРелэйтед(ЗаписьТекста, Boundary, Файлы); + ЗаписьТекста.ЗаписатьСтроку("--" + boundary + "--" + РазделительСтрок); ЗаписьТекста.Закрыть(); - + ДобавитьContentLength(Запрос); - + Запрос.УстановитьИмяФайлаТела(ТелоЗапроса); - + Если ЗначениеЗаполнено(ФайлОтвета) Тогда Ответ = Соединение.ВызватьHTTPМетод(Вид, Запрос, ФайлОтвета); Иначе Ответ = Соединение.ВызватьHTTPМетод(Вид, Запрос); КонецЕсли; - + ЭтоПереадресация = Ответ.КодСостояния >= Переадресация И Ответ.КодСостояния < Ошибка; - - Если ЭтоПереадресация Тогда + + Если ЭтоПереадресация Тогда Ответ = ВыполнитьЗапросМультипартРелэйтед(Ответ.Заголовки["Location"] , Вид , JSON , Файлы , ДопЗаголовки - , ФайлОтвета); - Иначе - ОбработатьОтвет(Ответ); + , ФайлОтвета); + Иначе + ОбработатьОтвет(Ответ); КонецЕсли; - + Запрос = Неопределено; ЗаписьТекста = Неопределено; @@ -794,31 +794,31 @@ КонецФункции Функция ЭтоПереадресация(Знач Ответ) - + Переадресация = 300; Ошибка = 400; - ЭтоПереадресация = Ответ.КодСостояния >= Переадресация + ЭтоПереадресация = Ответ.КодСостояния >= Переадресация И Ответ.КодСостояния < Ошибка И ЗначениеЗаполнено(Ответ.Заголовки["Location"]); - + Возврат ЭтоПереадресация; - + КонецФункции Функция ПреобразоватьПараметрВСтроку(Знач Значение) Если ТипЗнч(Значение) = Тип("Массив") Тогда - Значение = СтрСоединить(Значение, ","); - Значение = КодироватьСтроку(Значение, СпособКодированияСтроки.URLВКодировкеURL); - Значение = "[" + Значение + "]"; + Значение = СтрСоединить(Значение, ","); + Значение = КодироватьСтроку(Значение, СпособКодированияСтроки.URLВКодировкеURL); + Значение = "[" + Значение + "]"; Иначе - Значение = ЧислоВСтроку(Значение); - Значение = КодироватьСтроку(Значение, СпособКодированияСтроки.URLВКодировкеURL); + Значение = ЧислоВСтроку(Значение); + Значение = КодироватьСтроку(Значение, СпособКодированияСтроки.URLВКодировкеURL); КонецЕсли; - + Возврат Значение; - + КонецФункции Функция РазобратьКлючФайла(Знач ДанныеФайла, Знач ТипКонтента) @@ -827,134 +827,134 @@ ИмяФайла = СтрЗаменить(ДанныеФайла, ЗаменаТочки, "."); МассивИмени = СтрРазделить(ИмяФайла, "|", Ложь); ЧастейИмени = 2; - + Если МассивИмени.Количество() = ЧастейИмени Тогда ИмяПоля = МассивИмени[0]; ИмяФайла = МассивИмени[1]; Иначе - + Если ТипКонтента = "image/jpeg" Тогда - ИмяПоля = "photo"; + ИмяПоля = "photo"; Иначе - ИмяПоля = Лев(ИмяФайла, СтрНайти(ИмяФайла, ".") - 1); - ИмяПоля = ?(ЗначениеЗаполнено(ИмяПоля), ИмяПоля, СтрЗаменить(ДанныеФайла, + ИмяПоля = Лев(ИмяФайла, СтрНайти(ИмяФайла, ".") - 1); + ИмяПоля = ?(ЗначениеЗаполнено(ИмяПоля), ИмяПоля, СтрЗаменить(ДанныеФайла, ЗаменаТочки, ".")); КонецЕсли; - + КонецЕсли; - + СтруктураВозврата = Новый Структура("ИмяПоля,ИмяФайла", ИмяПоля, ИмяФайла); - + Возврат СтруктураВозврата; - + КонецФункции Процедура УстановитьТелоЗапроса(Запрос, Знач Параметры, Знач JSON) - - Коллекция = ТипЗнч(Параметры) = Тип("Структура") + + Коллекция = ТипЗнч(Параметры) = Тип("Структура") Или ТипЗнч(Параметры) = Тип("Соответствие") Или ТипЗнч(Параметры) = Тип("Массив"); - + Если JSON Тогда Данные = JSONСтрокой(Параметры); ИначеЕсли Не Коллекция Тогда - Данные = Параметры; + Данные = Параметры; Иначе СтрокаПараметров = ПараметрыЗапросаВСтроку(Параметры); Данные = Прав(СтрокаПараметров, СтрДлина(СтрокаПараметров) - 1); КонецЕсли; - + Если ТипЗнч(Данные) = Тип("Строка") Тогда Запрос.УстановитьТелоИзСтроки(Данные); Иначе //@skip-check wrong-type-expression Запрос.УстановитьТелоИзДвоичныхДанных(Данные); КонецЕсли; - + КонецПроцедуры Процедура ЗаписатьПараметрыМультипарт(ЗаписьТекста, Знач Boundary, Знач Параметры) - + РазделительСтрок = Символы.ВК + Символы.ПС; - + Для Каждого Параметр Из Параметры Цикл - - Если Параметр.Значение = Неопределено + + Если Параметр.Значение = Неопределено Или Параметр.Значение = NULL Тогда Продолжить; КонецЕсли; - + ЗаписьТекста.ЗаписатьСтроку("--" + boundary + РазделительСтрок); ЗаписьТекста.ЗаписатьСтроку("Content-Disposition: form-data; name=""" + Параметр.Ключ + """"); ЗаписьТекста.ЗаписатьСтроку(РазделительСтрок); ЗаписьТекста.ЗаписатьСтроку(РазделительСтрок); - - Если ТипЗнч(Параметр.Значение) = Тип("Строка") + + Если ТипЗнч(Параметр.Значение) = Тип("Строка") Или ТипЗнч(Параметр.Значение) = Тип("Число") Тогда - + ЗначениеСтрокой = ЧислоВСтроку(Параметр.Значение); ЗаписьТекста.ЗаписатьСтроку(ЗначениеСтрокой); - + ИначеЕсли ТипЗнч(Параметр.Значение) = Тип("Булево") Тогда - + ЗаписьТекста.ЗаписатьСтроку(?(Параметр.Значение, "true", "false")); - + Иначе - + ЗаписьТекста.Записать(Параметр.Значение); - + КонецЕсли; - + ЗаписьТекста.ЗаписатьСтроку(РазделительСтрок); - + КонецЦикла; - + КонецПроцедуры Процедура ЗаписатьФайлыМультипарт(ЗаписьТекста, Знач Boundary, Знач ТипКонтента, Знач Файлы) - + ТипКонтента = СокрЛП(ТипКонтента); РазделительСтрок = Символы.ВК + Символы.ПС; - + Для Каждого Файл Из Файлы Цикл - + СтруктураИнформации = РазобратьКлючФайла(Файл.Ключ, ТипКонтента); - + ИмяПоля = СтруктураИнформации["ИмяПоля"]; ИмяФайла = СтруктураИнформации["ИмяФайла"]; - + ЗаписьТекста.ЗаписатьСтроку("--" + boundary + РазделительСтрок); - ЗаписьТекста.ЗаписатьСтроку("Content-Disposition: form-data; name=""" - + ИмяПоля - + """; filename=""" + ЗаписьТекста.ЗаписатьСтроку("Content-Disposition: form-data; name=""" + + ИмяПоля + + """; filename=""" + ИмяФайла + """"); - ЗаписьТекста.ЗаписатьСтроку(РазделительСтрок); - + ЗаписьТекста.ЗаписатьСтроку(РазделительСтрок); + Если ЗначениеЗаполнено(ТипКонтента) Тогда ЗаписьТекста.ЗаписатьСтроку("Content-Type: " + ТипКонтента); КонецЕсли; - + ЗаписьТекста.ЗаписатьСтроку(РазделительСтрок); ЗаписьТекста.ЗаписатьСтроку(РазделительСтрок); ЗаписатьДвоичныеДанные(ЗаписьТекста, Файл.Значение); ЗаписьТекста.ЗаписатьСтроку(РазделительСтрок); - + КонецЦикла; КонецПроцедуры Процедура ЗаписатьФайлыРелэйтед(ЗаписьТекста, Знач Boundary, Знач Файлы) - + Если Не ЗначениеЗаполнено(Файлы) Тогда Возврат; КонецЕсли; - + РазделительСтрок = Символы.ВК + Символы.ПС; - + Если ТипЗнч(Файлы) = Тип("Соответствие") Тогда Для Каждого Файл Из Файлы Цикл - + ЗаписьТекста.ЗаписатьСтроку("--" + boundary + РазделительСтрок); ЗаписьТекста.ЗаписатьСтроку("Content-Type: " + Файл.Значение); ЗаписьТекста.ЗаписатьСтроку(РазделительСтрок); @@ -962,51 +962,51 @@ ЗаписатьДвоичныеДанные(ЗаписьТекста, Файл.Ключ); ЗаписьТекста.ЗаписатьСтроку(РазделительСтрок); ЗаписьТекста.ЗаписатьСтроку(РазделительСтрок); - + КонецЦикла; - + КонецЕсли; КонецПроцедуры Процедура ЗаписатьДвоичныеДанные(ЗаписьДанных, Знач ДвоичныеДанные) - + РазмерЧасти = 268435456; ПрочитанноБайт = 0; ТекущаяПозиция = 0; ОбщийРазмер = ДвоичныеДанные.Размер(); Пока ПрочитанноБайт < ОбщийРазмер Цикл - + ЧтениеДанных = Новый ЧтениеДанных(ДвоичныеДанные); ПрочитанноБайт = ЧтениеДанных.Пропустить(ТекущаяПозиция); Результат = ЧтениеДанных.Прочитать(РазмерЧасти); ТекущиеДанные = Результат.ПолучитьДвоичныеДанные(); РазмерТекущих = ТекущиеДанные.Размер(); - + Если Не ЗначениеЗаполнено(ТекущиеДанные) Тогда Прервать; КонецЕсли; ЗаписьДанных.Записать(ТекущиеДанные); - + ОсвободитьОбъект(ТекущиеДанные); ВыполнитьСборкуМусора(); ТекущаяПозиция = ТекущаяПозиция + РазмерТекущих; - + КонецЦикла; КонецПроцедуры Процедура ЗаписатьJSONМультипарт(ЗаписьТекста, Знач Boundary, Знач JSON) - + Если Не ЗначениеЗаполнено(JSON) Тогда Возврат; КонецЕсли; - + РазделительСтрок = Символы.ВК + Символы.ПС; - + ЗаписьТекста.ЗаписатьСтроку("--" + boundary + РазделительСтрок); ЗаписьТекста.ЗаписатьСтроку("Content-Type: application/json; charset=UTF-8"); ЗаписьТекста.ЗаписатьСтроку(РазделительСтрок); @@ -1018,46 +1018,46 @@ КонецПроцедуры Процедура ДобавитьContentLength(Запрос) - + ТелоЗапроса = Запрос.ПолучитьТелоКакДвоичныеДанные(); - + Если ЗначениеЗаполнено(ТелоЗапроса) Тогда - + Размер = ТелоЗапроса.Размер(); Запрос.Заголовки.Вставить("Content-Length", ЧислоВСтроку(Размер)); - + КонецЕсли; КонецПроцедуры Процедура УдалитьПустыеКлючиЗначения(Знач Коллекция, ВыходнаяКоллекция) - + Для Каждого ЭлементКоллекции Из Коллекция Цикл - + Если Не ЭлементКоллекции.Значение = Неопределено И Не ЭлементКоллекции.Значение = NULL Тогда ВыходнаяКоллекция.Вставить(ЭлементКоллекции.Ключ, ЭлементКоллекции.Значение); КонецЕсли; - + КонецЦикла; - + КонецПроцедуры Процедура УдалитьПустыеЭлементыМассива(Знач Коллекция, ВыходнаяКоллекция) - + Для Каждого ЭлементКоллекции Из Коллекция Цикл - + Если Не ЭлементКоллекции = Неопределено И Не ЭлементКоллекции = NULL Тогда ВыходнаяКоллекция.Добавить(ЭлементКоллекции); КонецЕсли; - + КонецЦикла; - + КонецПроцедуры #Область GZip // Описание структур см. здесь https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT -// Источник: https://github.com/vbondarevsky/Connector +// Источник: https://github.com/vbondarevsky/Connector // Коннектор: удобный HTTP-клиент для 1С:Предприятие 8 // @@ -1096,22 +1096,22 @@ РазмерПрефиксаGZip = 10; РазмерПостфиксаGZip = 8; - + РазмерДД = ZipРазмерDD(); РазмерСДХ = ZipРазмерCDH(); РазмерЕСД = ZipРазмерEOCD(); РазмерЛФХ = ZipРазмерLFH(); - ЧтениеДанных = Новый ЧтениеДанных(СжатыеДанные); + ЧтениеДанных = Новый ЧтениеДанных(СжатыеДанные); ЧтениеДанных.Пропустить(РазмерПрефиксаGZip); РазмерСжатыхДанных = ЧтениеДанных.ИсходныйПоток().Размер() - РазмерПрефиксаGZip - РазмерПостфиксаGZip; - ПотокZip = Новый ПотокВПамяти(РазмерЛФХ - + РазмерСжатыхДанных - + РазмерДД - + РазмерСДХ + ПотокZip = Новый ПотокВПамяти(РазмерЛФХ + + РазмерСжатыхДанных + + РазмерДД + + РазмерСДХ + РазмерЕСД); - + ЗаписьДанных = Новый ЗаписьДанных(ПотокZip); ЗаписьДанных.ЗаписатьБуферДвоичныхДанных(ZipLFH()); ЧтениеДанных.КопироватьВ(ЗаписьДанных, РазмерСжатыхДанных); @@ -1123,7 +1123,7 @@ РазмерНесжатыхДанных = ЧтениеДанных.ПрочитатьЦелое32(); ЧтениеДанных.Закрыть(); - ЗаписьДанных.ЗаписатьБуферДвоичныхДанных(ZipDD(CRC32, РазмерСжатыхДанных, РазмерНесжатыхДанных)); + ЗаписьДанных.ЗаписатьБуферДвоичныхДанных(ZipDD(CRC32 , РазмерСжатыхДанных, РазмерНесжатыхДанных)); ЗаписьДанных.ЗаписатьБуферДвоичныхДанных(ZipCDH(CRC32, РазмерСжатыхДанных, РазмерНесжатыхДанных)); ЗаписьДанных.ЗаписатьБуферДвоичныхДанных(ZipEOCD(РазмерСжатыхДанных)); ЗаписьДанных.Закрыть(); @@ -1134,9 +1134,9 @@ Функция ПрочитатьZip(СжатыеДанные, ТекстОшибки = Неопределено) - Каталог = ПолучитьИмяВременногоФайла(); - ЧтениеZip = Новый ЧтениеZipФайла(СжатыеДанные); - ИмяФайла = ЧтениеZip.Элементы[0].Имя; + Каталог = ПолучитьИмяВременногоФайла(); + ЧтениеZip = Новый ЧтениеZipФайла(СжатыеДанные); + ИмяФайла = ЧтениеZip.Элементы[0].Имя; Попытка ЧтениеZip.Извлечь(ЧтениеZip.Элементы[0], Каталог, РежимВосстановленияПутейФайловZIP.НеВосстанавливать); Исключение @@ -1177,12 +1177,12 @@ КонецФункции Функция ZipLFH() - + // Local file header Буфер = Новый БуферДвоичныхДанных(ZipРазмерLFH()); Буфер.ЗаписатьЦелое32(0, 67324752); // signature 0x04034b50 Буфер.ЗаписатьЦелое16(4, 20); // version - Буфер.ЗаписатьЦелое16(6, 10); // bit flags + Буфер.ЗаписатьЦелое16(6, 10); // bit flags Буфер.ЗаписатьЦелое16(8, 8); // compression method Буфер.ЗаписатьЦелое16(10, 0); // time Буфер.ЗаписатьЦелое16(12, 0); // date @@ -1198,7 +1198,7 @@ КонецФункции Функция ZipDD(CRC32, РазмерСжатыхДанных, РазмерНесжатыхДанных) - + // Data descriptor Буфер = Новый БуферДвоичныхДанных(ZipРазмерDD()); Буфер.ЗаписатьЦелое32(0, 134695760); @@ -1211,7 +1211,7 @@ КонецФункции Функция ZipCDH(CRC32, РазмерСжатыхДанных, РазмерНесжатыхДанных) - + // Central directory header Буфер = Новый БуферДвоичныхДанных(ZipРазмерCDH()); Буфер.ЗаписатьЦелое32(0, 33639248); // signature 0x02014b50 @@ -1238,7 +1238,7 @@ КонецФункции Функция ZipEOCD(РазмерСжатыхДанных) - + // End of central directory РазмерCDH = 50; Буфер = Новый БуферДвоичныхДанных(ZipРазмерEOCD()); @@ -1247,7 +1247,7 @@ Буфер.ЗаписатьЦелое16(6, 0); // number of the disk with the start of the central directory Буфер.ЗаписатьЦелое16(8, 1); // total number of entries in the central directory on this disk Буфер.ЗаписатьЦелое16(10, 1); // total number of entries in the central directory - Буфер.ЗаписатьЦелое32(12, РазмерCDH); // size of the central directory + Буфер.ЗаписатьЦелое32(12, РазмерCDH); // size of the central directory // offset of start of central directory with respect to the starting disk number Буфер.ЗаписатьЦелое32(16, ZipРазмерLFH() + РазмерСжатыхДанных + ZipРазмерDD()); Буфер.ЗаписатьЦелое16(20, 0); // the starting disk number diff --git a/src/ru/OInt/tools/Modules/internal/Modules/OPI_Криптография.os b/src/ru/OInt/tools/Modules/internal/Modules/OPI_Криптография.os index 2ea8dac553..887cae5011 100644 --- a/src/ru/OInt/tools/Modules/internal/Modules/OPI_Криптография.os +++ b/src/ru/OInt/tools/Modules/internal/Modules/OPI_Криптография.os @@ -39,75 +39,75 @@ /////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2019, ООО 1С-Софт -// Все права защищены. Эта программа и сопроводительные материалы предоставляются +// Все права защищены. Эта программа и сопроводительные материалы предоставляются // в соответствии с условиями лицензии Attribution 4.0 International (CC BY 4.0) // Текст лицензии доступен по ссылке: // https://creativecommons.org/licenses/by/4.0/legalcode /////////////////////////////////////////////////////////////////////////////////////////////////////// Функция HMACSHA256(Знач Ключ, Знач Данные) Экспорт - + Возврат HMAC(Ключ, Данные, ХешФункция.SHA256, 64); - + КонецФункции Функция Хеш(ДвоичныеДанные, Тип) Экспорт - + Хеширование = Новый ХешированиеДанных(Тип); Хеширование.Добавить(ДвоичныеДанные); - + Возврат Хеширование.ХешСумма; - + КонецФункции Функция HMAC(Знач Ключ, Знач Данные, Тип, РазмерБлока) Экспорт - + Дважды = 2; - + Если Ключ.Размер() > РазмерБлока Тогда Ключ = Хеш(Ключ, Тип); КонецЕсли; - + Если Ключ.Размер() <= РазмерБлока Тогда - Ключ = ПолучитьHexСтрокуИзДвоичныхДанных(Ключ); - Ключ = Лев(Ключ + ПовторитьСтроку("00", РазмерБлока), РазмерБлока * Дважды); + Ключ = ПолучитьHexСтрокуИзДвоичныхДанных(Ключ); + Ключ = Лев(Ключ + ПовторитьСтроку("00", РазмерБлока), РазмерБлока * Дважды); КонецЕсли; - + Ключ = ПолучитьБуферДвоичныхДанныхИзДвоичныхДанных(ПолучитьДвоичныеДанныеИзHexСтроки(Ключ)); - + Ipad = ПолучитьБуферДвоичныхДанныхИзHexСтроки(ПовторитьСтроку("36", РазмерБлока)); Opad = ПолучитьБуферДвоичныхДанныхИзHexСтроки(ПовторитьСтроку("5c", РазмерБлока)); - + Ipad.ЗаписатьПобитовоеИсключительноеИли(0, Ключ); Ikeypad = ПолучитьДвоичныеДанныеИзБуфераДвоичныхДанных(ipad); - + Opad.ЗаписатьПобитовоеИсключительноеИли(0, Ключ); Okeypad = ПолучитьДвоичныеДанныеИзБуфераДвоичныхДанных(opad); - + Возврат Хеш(СклеитьДвоичныеДанные(okeypad, Хеш(СклеитьДвоичныеДанные(ikeypad, Данные), Тип)), Тип); - + КонецФункции Функция СклеитьДвоичныеДанные(ДвоичныеДанные1, ДвоичныеДанные2) Экспорт - + МассивДвоичныхДанных = Новый Массив; МассивДвоичныхДанных.Добавить(ДвоичныеДанные1); МассивДвоичныхДанных.Добавить(ДвоичныеДанные2); - + Возврат СоединитьДвоичныеДанные(МассивДвоичныхДанных); - + КонецФункции Функция ПовторитьСтроку(Строка, Количество) Экспорт - + Части = Новый Массив(Количество); - + Для К = 1 По Количество Цикл Части.Добавить(Строка); КонецЦикла; Возврат СтрСоединить(Части, ""); - + КонецФункции #КонецОбласти diff --git a/src/ru/OPI/src/CommonModules/OPI_Airtable/Module.bsl b/src/ru/OPI/src/CommonModules/OPI_Airtable/Module.bsl index f4bc46865f..c7175ef672 100644 --- a/src/ru/OPI/src/CommonModules/OPI_Airtable/Module.bsl +++ b/src/ru/OPI/src/CommonModules/OPI_Airtable/Module.bsl @@ -1,4 +1,4 @@ -// OneScript: ./OInt/core/Modules/OPI_Airtable.os +// OneScript: ./OInt/core/Modules/OPI_Airtable.os // Lib: Airtable // CLI: airtable @@ -42,91 +42,91 @@ // Получить список баз // Получает список доступных баз -// +// // Параметры: // Токен - Строка - Токен - token // Отступ - Строка - Идентификатор следующей страницы списка баз из перыдудщего запроса - offset -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция ПолучитьСписокБаз(Знач Токен, Знач Отступ = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Отступ); - + URL = "https://api.airtable.com/v0/meta/bases"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); Параметры = Новый Структура; - + OPI_Инструменты.ДобавитьПоле("offset", Отступ, "Строка", Параметры); - + Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить таблицы базы // Получает схему таблиц базы -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - Идентификатор базы - base -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция ПолучитьТаблицыБазы(Знач Токен, Знач База) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(База); - + URL = "https://api.airtable.com/v0/meta/bases/" + База + "/tables"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Ответ = OPI_Инструменты.Get(URL, , Заголовки); - + Возврат Ответ; - + КонецФункции // Создать базу // Создает новую базу данных -// +// // Параметры: // Токен - Строка - Токен - token // РабочееПространство - Строка - Идентификатор рабочего пространства - ws // Наименование - Строка - Наименование новой базы - title // КоллекцияТаблиц - Соответствие Из КлючИЗначение - Описание таблиц: Ключ > имя, Значение > массив полей - tablesdata -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция СоздатьБазу(Знач Токен, Знач РабочееПространство, Знач Наименование, Знач КоллекцияТаблиц) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(КоллекцияТаблиц); - - Если Не ТипЗнч(КоллекцияТаблиц) = Тип("Структура") + + Если Не ТипЗнч(КоллекцияТаблиц) = Тип("Структура") И Не ТипЗнч(КоллекцияТаблиц) = Тип("Соответствие") Тогда - + ВызватьИсключение "Ошибка в данных коллекции таблиц"; - + КонецЕсли; - + URL = "https://api.airtable.com/v0/meta/bases"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); МассивТаблиц = Новый Массив; - + Для Каждого Таблица Из КоллекцияТаблиц Цикл - + Описание = СформироватьОписаниеТаблицы(Таблица.Ключ, Таблица.Значение); МассивТаблиц.Добавить(Описание); - + КонецЦикла; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("name" , Наименование , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("tables" , МассивТаблиц , "Массив", Параметры); OPI_Инструменты.ДобавитьПоле("workspaceId", РабочееПространство, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции @@ -137,56 +137,56 @@ // Создать таблицу // Создает новую таблицу в базе -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - Идентификатор базы - base // Наименование - Строка - Наименование новой таблицы - title // МассивПолей - Массив Из Структура - Массив описаний полей - fieldsdata // Описание - Строка - Описание таблицы - description -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция СоздатьТаблицу(Знач Токен, Знач База, Знач Наименование, Знач МассивПолей, Знач Описание = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(База); - + URL = "https://api.airtable.com/v0/meta/bases/" + База + "/tables"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - Параметры = СформироватьОписаниеТаблицы(Наименование, МассивПолей, Описание); - + Параметры = СформироватьОписаниеТаблицы(Наименование, МассивПолей, Описание); + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Изменить таблицу // Изменяет наименование и|или описание базы -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - Идентификатор базы - base // Таблица - Строка - Идентификатор таблицы - table // Наименование - Строка - Новое наименование - title // Описание - Строка - Новое описание - description -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция ИзменитьТаблицу(Знач Токен, Знач База, Знач Таблица, Знач Наименование = "", Знач Описание = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(База); OPI_ПреобразованиеТипов.ПолучитьСтроку(Таблица); - + URL = "https://api.airtable.com/v0/meta/bases/" + База + "/tables/" + Таблица; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - Параметры = Новый Структура; - + Параметры = Новый Структура; + OPI_Инструменты.ДобавитьПоле("name" , Наименование, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("description", Описание , "Строка", Параметры); - + Ответ = OPI_Инструменты.Patch(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции @@ -197,40 +197,40 @@ // Создать поле // Создет новое поле в таблице -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - Идентификатор базы - base // Таблица - Строка - Идентификатор таблицы - table // СтруктураПоля - Структура Из КлючИЗначение - Описание нового поля - fielddata -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция СоздатьПоле(Знач Токен, Знач База, Знач Таблица, Знач СтруктураПоля) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(База); OPI_ПреобразованиеТипов.ПолучитьСтроку(Таблица); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(СтруктураПоля); - - Если Не ТипЗнч(СтруктураПоля) = Тип("Структура") + + Если Не ТипЗнч(СтруктураПоля) = Тип("Структура") И Не ТипЗнч(СтруктураПоля) = Тип("Соответствие") Тогда - + ВызватьИсключение "Ошибка в данных описания поля"; - + КонецЕсли; - + URL = "https://api.airtable.com/v0/meta/bases/" + База + "/tables/" + Таблица + "/fields"; - Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Заголовки = ПолучитьЗаголовокАвторизации(Токен); + Ответ = OPI_Инструменты.Post(URL, СтруктураПоля, Заголовки); - + Возврат Ответ; КонецФункции // Изменить поле // Изменяет имя и|или описание существующего поля таблицы -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - Идентификатор базы База - base @@ -238,152 +238,152 @@ // Поле - Строка - Идентификатор поля - field // Наименование - Строка - Новое наименование - title // Описание - Строка - Новое описание - description -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция ИзменитьПоле(Знач Токен, Знач База, Знач Таблица, Знач Поле, Знач Наименование = "", Знач Описание = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(База); OPI_ПреобразованиеТипов.ПолучитьСтроку(Таблица); OPI_ПреобразованиеТипов.ПолучитьСтроку(Поле); - - URL = "https://api.airtable.com/v0/meta/bases/" - + База - + "/tables/" - + Таблица - + "/fields/" + + URL = "https://api.airtable.com/v0/meta/bases/" + + База + + "/tables/" + + Таблица + + "/fields/" + Поле; - + Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура(); OPI_Инструменты.ДобавитьПоле("name" , Наименование, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("description", Описание , "Строка", Параметры); - + Ответ = OPI_Инструменты.Patch(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Получить поле (строковое) // Получает описание поля строкового типа -// +// // Параметры: // Наименование - Строка - Наименование нового поля - title -// +// // Возвращаемое значение: // Структура - Описание поля Функция ПолучитьПолеСтроковое(Знач Наименование) Экспорт - + Возврат ОписаниеПримитивногоПоля(Наименование, "richText"); - + КонецФункции // Получить поле (числовое) // Получает описание поля числового типа -// +// // Параметры: // Наименование - Строка - Наименование нового поля - title // Точность - Число,Строка - Число знаков после запятой - precision -// +// // Возвращаемое значение: // Структура - Описание поля Функция ПолучитьПолеНомера(Знач Наименование, Знач Точность = 0) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьЧисло(Точность); - + СтруктураОпций = Новый Структура("precision", Точность); Возврат ОписаниеПримитивногоПоля(Наименование, "number", СтруктураОпций); - + КонецФункции // Получить поле (файл) // Получает описание поля файлового типа -// +// // Параметры: // Наименование - Строка - Наименование поля - title -// +// // Возвращаемое значение: // Структура - Описание поля Функция ПолучитьПолеВложения(Знач Наименование) Экспорт - + Возврат ОписаниеПримитивногоПоля(Наименование, "multipleAttachments"); - + КонецФункции // Получить поле (флажок) // Получает описание поля типа булево -// +// // Параметры: // Наименование - Строка - Наименование поля - title -// +// // Возвращаемое значение: // Структура - Описание поля Функция ПолучитьПолеФлажка(Знач Наименование) Экспорт - + СтруктураОпций = Новый Структура("icon,color", "check", "yellowBright"); Возврат ОписаниеПримитивногоПоля(Наименование, "checkbox", СтруктураОпций); - + КонецФункции // Получить поле (дата) // Получает описание поля типа дата -// +// // Параметры: // Наименование - Строка - Наименование поля - title -// +// // Возвращаемое значение: // Структура - Описание поля Функция ПолучитьПолеДаты(Знач Наименование) Экспорт - + СтруктураФормата = Новый Структура("format,name", "YYYY-MM-DD", "iso"); СтруктураОпций = Новый Структура("dateFormat", СтруктураФормата); - + Возврат ОписаниеПримитивногоПоля(Наименование, "date", СтруктураОпций); - + КонецФункции // Получить поле (email) // Получает описание поля с электронной почтой -// +// // Параметры: // Наименование - Строка - Наименование поля - title -// +// // Возвращаемое значение: // Структура - Описание поля Функция ПолучитьПолеПочты(Знач Наименование) Экспорт - + Возврат ОписаниеПримитивногоПоля(Наименование, "email"); - + КонецФункции // Получить поле (телефон) // Получает описание поля с номером телефона -// +// // Параметры: // Наименование - Строка - Наименование поля - title -// +// // Возвращаемое значение: // Структура - Описание поля Функция ПолучитьПолеТелефона(Знач Наименование) Экспорт - + Возврат ОписаниеПримитивногоПоля(Наименование, "phoneNumber"); - + КонецФункции // Получить поле (url) // Получает описание поля с URL -// +// // Параметры: // Наименование - Строка - Наименование поля - title -// +// // Возвращаемое значение: // Структура - Описание поля Функция ПолучитьПолеСсылки(Знач Наименование) Экспорт - + Возврат ОписаниеПримитивногоПоля(Наименование, "url"); - + КонецФункции #КонецОбласти @@ -392,67 +392,67 @@ // Получить список записей // Получает список записей выбранной таблицы -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - Идентификатор базы данных - base // Таблица - Строка - Идентификатор таблицы - table // Отступ - Строка - Иднтификатор следующей страницы данных из предыдущего запроса - offset -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция ПолучитьСписокЗаписей(Знач Токен, Знач База, Знач Таблица, Знач Отступ = "") Экспорт OPI_ПреобразованиеТипов.ПолучитьСтроку(База); OPI_ПреобразованиеТипов.ПолучитьСтроку(Таблица); - + URL = "https://api.airtable.com/v0/" + База + "/" + Таблица; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура(); OPI_Инструменты.ДобавитьПоле("offset", Отступ, "Строка", Параметры); - + Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить запись // Получает данные строки таблицы по идентификатору -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - Идентификатор базы данных - base // Таблица - Строка - Идентификатор таблицы - table // Запись - Строка - Идентификатор записи в таблице - record -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция ПолучитьЗапись(Знач Токен, Знач База, Знач Таблица, Знач Запись) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(База); OPI_ПреобразованиеТипов.ПолучитьСтроку(Таблица); OPI_ПреобразованиеТипов.ПолучитьСтроку(Запись); - + URL = "https://api.airtable.com/v0/" + База + "/" + Таблица + "/" + Запись; Заголовки = ПолучитьЗаголовокАвторизации(Токен); Ответ = OPI_Инструменты.Get(URL, , Заголовки); - + Возврат Ответ; - + КонецФункции // Создать записи // Создает одну или массив записей по описанию или массиву описаний значений полей -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - Идентификатор базы данных - base // Таблица - Строка - Идентификатор таблицы - table // Данные - Структура, Массив из Структура - Набор или массив наборов пар Ключ : Значение > Поле : Показатель - data -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция СоздатьЗаписи(Знач Токен, Знач База, Знач Таблица, Знач Данные) Экспорт @@ -460,52 +460,52 @@ OPI_ПреобразованиеТипов.ПолучитьСтроку(База); OPI_ПреобразованиеТипов.ПолучитьСтроку(Таблица); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Данные); - + Параметры = Новый Структура(); - ДобавитьОписаниеДанных(Данные, Параметры); + ДобавитьОписаниеДанных(Данные, Параметры); URL = "https://api.airtable.com/v0/" + База + "/" + Таблица; Заголовки = ПолучитьЗаголовокАвторизации(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции // Удалить записи // Удаляет одну или массив записей по идентификаторам -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - Идентификатор базы данных - base // Таблица - Строка - Идентификатор таблицы - table // Записи - Строка, Массив из Строка - Идентификатор или массив индентификаторов записей - records -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция УдалитьЗаписи(Знач Токен, Знач База, Знач Таблица, Знач Записи) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(База); OPI_ПреобразованиеТипов.ПолучитьСтроку(Таблица); OPI_ПреобразованиеТипов.ПолучитьМассив(Записи); - + СтрокаЗаписей = ""; - + Для Каждого Запись Из Записи Цикл - СтрокаЗаписей = СтрокаЗаписей + СтрокаЗаписей = СтрокаЗаписей + ?(ЗначениеЗаполнено(СтрокаЗаписей), "&", "?") + "records[]=" - + OPI_Инструменты.ЧислоВСтроку(Запись); + + OPI_Инструменты.ЧислоВСтроку(Запись); КонецЦикла; - + URL = "https://api.airtable.com/v0/" + База + "/" + Таблица + СтрокаЗаписей; Заголовки = ПолучитьЗаголовокАвторизации(Токен); Ответ = OPI_Инструменты.Delete(URL, , Заголовки); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции #КонецОбласти @@ -514,67 +514,67 @@ // Получить комментарии // Получает список комментариев к записи в таблице -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - Идентификатор базы данных - base // Таблица - Строка - Идентификатор таблицы - table // Запись - Строка - Идентификатор записи в таблице - record // Отступ - Строка - Иднтификатор следующей страницы данных из предыдущего запроса - offset -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция ПолучитьКомментарии(Знач Токен, Знач База, Знач Таблица, Знач Запись, Знач Отступ = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(База); OPI_ПреобразованиеТипов.ПолучитьСтроку(Таблица); OPI_ПреобразованиеТипов.ПолучитьСтроку(Запись); - + URL = "https://api.airtable.com/v0/" + База + "/" + Таблица + "/" + Запись + "/comments"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура(); OPI_Инструменты.ДобавитьПоле("offset", Отступ, "Строка", Параметры); - + Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Создать комментарий // Создает комментарий к записи в таблице -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - Идентификатор базы данных - base // Таблица - Строка - Идентификатор таблицы - table // Запись - Строка - Идентификатор записи в таблице - record // Текст - Строка - Текст комментария - text -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция СоздатьКомментарий(Знач Токен, Знач База, Знач Таблица, Знач Запись, Знач Текст) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(База); OPI_ПреобразованиеТипов.ПолучитьСтроку(Таблица); OPI_ПреобразованиеТипов.ПолучитьСтроку(Запись); - + URL = "https://api.airtable.com/v0/" + База + "/" + Таблица + "/" + Запись + "/comments"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура(); OPI_Инструменты.ДобавитьПоле("text", Текст, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Изменить комментарий // Изменяет текст существующего комментария -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - Идентификатор базы данных - base @@ -582,54 +582,54 @@ // Запись - Строка - Идентификатор записи в таблице - record // Комментарий - Строка - Идентификатор комментария - comment // Текст - Строка - Новый текст комментария - text -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция ИзменитьКомментарий(Знач Токен, Знач База, Знач Таблица, Знач Запись, Знач Комментарий, Знач Текст) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(База); OPI_ПреобразованиеТипов.ПолучитьСтроку(Таблица); OPI_ПреобразованиеТипов.ПолучитьСтроку(Запись); OPI_ПреобразованиеТипов.ПолучитьСтроку(Комментарий); - + URL = "https://api.airtable.com/v0/" + База + "/" + Таблица + "/" + Запись + "/comments/" + Комментарий; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура(); OPI_Инструменты.ДобавитьПоле("text", Текст, "Строка", Параметры); - + Ответ = OPI_Инструменты.Patch(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Удалить комментарий // Удаляет комментарий к записи таблицы -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - Идентификатор базы данных - base // Таблица - Строка - Идентификатор таблицы - table // Запись - Строка - Идентификатор записи в таблице - record // Комментарий - Строка - Идентификатор комментария - comment -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Airtable Функция УдалитьКомментарий(Знач Токен, Знач База, Знач Таблица, Знач Запись, Знач Комментарий) Экспорт OPI_ПреобразованиеТипов.ПолучитьСтроку(База); OPI_ПреобразованиеТипов.ПолучитьСтроку(Таблица); OPI_ПреобразованиеТипов.ПолучитьСтроку(Запись); OPI_ПреобразованиеТипов.ПолучитьСтроку(Комментарий); - + URL = "https://api.airtable.com/v0/" + База + "/" + Таблица + "/" + Запись + "/comments/" + Комментарий; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Ответ = OPI_Инструменты.Delete(URL, , Заголовки); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -639,58 +639,58 @@ #Область СлужебныеПроцедурыИФункции Функция ПолучитьЗаголовокАвторизации(Знач Токен) - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Заголовки = Новый Соответствие; Заголовки.Вставить("Authorization", "Bearer " + Токен); - + Возврат Заголовки; - + КонецФункции Функция СформироватьОписаниеТаблицы(Знач Наименование, Знач МассивПолей, Знач Описание = "") - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Наименование); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивПолей); - + ОписаниеТаблицы = Новый Структура("name,fields", Наименование, МассивПолей); - + OPI_Инструменты.ДобавитьПоле("description", Описание, "Строка", ОписаниеТаблицы); - + Возврат ОписаниеТаблицы; - + КонецФункции Функция ОписаниеПримитивногоПоля(Знач Наименование, Знач Тип, Знач Опции = "") - + СтруктураПоля = Новый Структура(); OPI_Инструменты.ДобавитьПоле("name" , Наименование, "Строка" , СтруктураПоля); OPI_Инструменты.ДобавитьПоле("type" , Тип , "Строка" , СтруктураПоля); OPI_Инструменты.ДобавитьПоле("options", Опции , "Коллекция", СтруктураПоля); - + Возврат СтруктураПоля; КонецФункции Процедура ДобавитьОписаниеДанных(Знач Данные, Параметры) - + Если ТипЗнч(Данные) = Тип("Массив") Тогда - + МассивОтправки = Новый Массив; - + Для Каждого ОписаниеЗаписи Из Данные Цикл - МассивОтправки.Добавить(Новый Структура("fields", ОписаниеЗаписи)); + МассивОтправки.Добавить(Новый Структура("fields", ОписаниеЗаписи)); КонецЦикла; - + OPI_Инструменты.ДобавитьПоле("records", МассивОтправки, "Массив", Параметры); - + Иначе - - OPI_Инструменты.ДобавитьПоле("fields", Данные, "Коллекция", Параметры); - + + OPI_Инструменты.ДобавитьПоле("fields", Данные, "Коллекция", Параметры); + КонецЕсли; - + КонецПроцедуры -#КонецОбласти \ No newline at end of file +#КонецОбласти diff --git a/src/ru/OPI/src/CommonModules/OPI_Bitrix24/Module.bsl b/src/ru/OPI/src/CommonModules/OPI_Bitrix24/Module.bsl index 3c7786d23e..8a11d5406c 100644 --- a/src/ru/OPI/src/CommonModules/OPI_Bitrix24/Module.bsl +++ b/src/ru/OPI/src/CommonModules/OPI_Bitrix24/Module.bsl @@ -1,4 +1,4 @@ -// OneScript: ./OInt/core/Modules/OPI_Bitrix24.os +// OneScript: ./OInt/core/Modules/OPI_Bitrix24.os // Lib: Bitrix24 // CLI: bitrix24 @@ -47,105 +47,105 @@ // Получить ссылку авторизации приложения // Формирует ссылку для авторизации через браузер -// +// // Параметры: // Домен - Строка - Адрес битрикс вида portal.bitrix24.com - domain // ClientID - Строка - Client ID из настроек приложения - clientid -// +// // Возвращаемое значение: // Строка - URL для перехода в браузере Функция ПолучитьСсылкуАвторизацииПриложения(Знач Домен, Знач ClientID) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Домен); OPI_ПреобразованиеТипов.ПолучитьСтроку(ClientID); - + Если Не СтрНачинаетсяС(Домен, "http") Тогда URL = "https://" + Домен; КонецЕсли; - + Если Не СтрЗаканчиваетсяНа(URL, "/") Тогда URL = URL + "/"; КонецЕсли; - + URL = URL + "oauth/authorize/?client_id=" + ClientID; - + Возврат URL; - + КонецФункции // Получить токен // Получает токен по коду авторизации -// +// // Параметры: // ClientID - Строка - Client ID из настроек приложения - clientid // ClientSecret - Строка - Client secret из настроек приложения - clientsecret // Code - Строка - Code из авторизации через браузер - code -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьТокен(Знач ClientID, Знач ClientSecret, Знач Code) Экспорт - + URL = "https://oauth.bitrix.info/oauth/token/"; Строка_ = "Строка"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("grant_type" , "authorization_code", Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("client_id" , ClientID , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("client_secret", ClientSecret , Строка_, Параметры); - OPI_Инструменты.ДобавитьПоле("code" , Code , Строка_, Параметры); - + OPI_Инструменты.ДобавитьПоле("code" , Code , Строка_, Параметры); + Ответ = OPI_Инструменты.Get(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Обновить токен // Обновляет токен по Refresh токену -// +// // Параметры: // ClientID - Строка - Client ID из настроек приложения - clientid // ClientSecret - Строка - Client secret из настроек приложения - clientsecret // Refresh - Строка - Refresh токен - refresh -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ОбновитьТокен(Знач ClientID, Знач ClientSecret, Знач Refresh) Экспорт - + URL = "https://oauth.bitrix.info/oauth/token/"; Строка_ = "Строка"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("grant_type" , "refresh_token" , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("client_id" , ClientID , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("client_secret", ClientSecret , Строка_, Параметры); - OPI_Инструменты.ДобавитьПоле("refresh_token", Refresh , Строка_, Параметры); - + OPI_Инструменты.ДобавитьПоле("refresh_token", Refresh , Строка_, Параметры); + Ответ = OPI_Инструменты.Get(URL, Параметры); - + Возврат Ответ; КонецФункции // Серверное время // Получает текущее серверное время -// +// // Примечание: // Метод в документации API: [server_time](@dev.1c-bitrix.ru/rest_help/general/server_time.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция СерверноеВремя(Знач URL, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "server.time"); Ответ = OPI_Инструменты.Get(URL, Параметры); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -154,19 +154,19 @@ // Создать новость // Создает новую новость в ленте -// +// // Примечание: // Метод в документации API: [log.blogpost.add](@dev.1c-bitrix.ru/rest_help/log/log_blogpost_add.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Текст - Строка - Текст новости - text // Видимость - Строка - Массив или 1 получатель: UA все, SGn р. группа, Un пользователь, DRn отдел, Gn группа - vision // Файлы - Соответствие Из КлючИЗначение - Ключ > имя файла, значение > путь или двоичные данные - files // Заголовок - Строка - Заголовок новости - title -// Важное - Булево - Помечает новость как важную - important +// Важное - Булево - Помечает новость как важную - important // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция СоздатьНовость(Знач URL @@ -176,41 +176,41 @@ , Знач Заголовок = "" , Знач Важное = Ложь , Знач Токен = "") Экспорт - + ПривестиБулево(Важное); - + Строка_ = "Строка"; - + Параметры = НормализоватьАвторизацию(URL, Токен, "log.blogpost.add"); - OPI_Инструменты.ДобавитьПоле("POST_MESSAGE", Текст , Строка_, Параметры); - OPI_Инструменты.ДобавитьПоле("POST_TITLE" , Заголовок , Строка_, Параметры); + OPI_Инструменты.ДобавитьПоле("POST_MESSAGE", Текст , Строка_ , Параметры); + OPI_Инструменты.ДобавитьПоле("POST_TITLE" , Заголовок , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("DEST" , Видимость , "Массив", Параметры); - OPI_Инструменты.ДобавитьПоле("IMPORTANT" , Важное , Строка_, Параметры); - + OPI_Инструменты.ДобавитьПоле("IMPORTANT" , Важное , Строка_ , Параметры); + Если ЗначениеЗаполнено(Файлы) Тогда - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Файлы); - + МассивФайлов = НормализоватьФайлы(Файлы); - + Если Не МассивФайлов.Количество() = 0 Тогда Параметры.Вставить("FILES", МассивФайлов); КонецЕсли; - + КонецЕсли; - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Изменить новость // Изменяет новость в ленте -// +// // Примечание: // Метод в документации API: [log.blogpost.update](@dev.1c-bitrix.ru/rest_help/log/log_blogpost_update.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDНовости - Строка, Число - ID новости - postid @@ -219,170 +219,170 @@ // Файлы - Соответствие Из КлючИЗначение - Ключ > имя файла, значение > путь или двоичные данные - files // Заголовок - Строка - Заголовок новости - title // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ИзменитьНовость(Знач URL - , Знач IDНовости + , Знач IDНовости , Знач Текст , Знач Видимость = "UA" , Знач Файлы = "" , Знач Заголовок = "" , Знач Токен = "") Экспорт - + Строка_ = "Строка"; - + Параметры = НормализоватьАвторизацию(URL, Токен, "log.blogpost.update"); - OPI_Инструменты.ДобавитьПоле("POST_MESSAGE", Текст , Строка_, Параметры); - OPI_Инструменты.ДобавитьПоле("POST_TITLE" , Заголовок , Строка_, Параметры); + OPI_Инструменты.ДобавитьПоле("POST_MESSAGE", Текст , Строка_ , Параметры); + OPI_Инструменты.ДобавитьПоле("POST_TITLE" , Заголовок , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("DEST" , Видимость , "Массив", Параметры); - OPI_Инструменты.ДобавитьПоле("POST_ID" , IDНовости , Строка_, Параметры); - + OPI_Инструменты.ДобавитьПоле("POST_ID" , IDНовости , Строка_ , Параметры); + Если ЗначениеЗаполнено(Файлы) Тогда - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Файлы); - + МассивФайлов = НормализоватьФайлы(Файлы); - + Если Не МассивФайлов.Количество() = 0 Тогда Параметры.Вставить("FILES", МассивФайлов); КонецЕсли; - + КонецЕсли; - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Удалить новость // Удаляет новость из ленты по выбранному ID -// +// // Примечание: // Метод в документации API: [log.blogpost.delete](@dev.1c-bitrix.ru/rest_help/log/log_blogpost_delete.php) -// +// // Параметры: -// URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url +// URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDНовости - Строка, Число - ID новости для удаления - postid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УдалитьНовость(Знач URL, Знач IDНовости, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "log.blogpost.delete"); OPI_Инструменты.ДобавитьПоле("POST_ID", IDНовости, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить список просмотревших важное // Возвращает список пользователей, просмотревших выбранное важное сообщение -// +// // Примечание: // Метод в документации API: [log.blogpost.getusers.important](@dev.1c-bitrix.ru/rest_help/log/log_blogpost_getusers_important.php) -// +// // Параметры: -// URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url +// URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDНовости - Строка, Число - ID важной новости - postid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьСписокПросмотревшихВажное(Знач URL, Знач IDНовости, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "log.blogpost.getusers.important"); OPI_Инструменты.ДобавитьПоле("POST_ID", IDНовости, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить новости // Получает нвости или одну новость с отобором по ID или доступности -// +// // Примечание: // Метод в документации API: [log.blogpost.get](@dev.1c-bitrix.ru/rest_help/log/log_blogpost_get.php) -// +// // Параметры: -// URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url +// URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDНовости - Строка, Число - ID важной новости - postid -// Отбор - Строка - Отбор новостей по доступу: UA все, SGn раб. группа, Un пользователь, DRn отдел, Gn группа - sel +// Отбор - Строка - Отбор новостей по доступу: UA все, SGn раб. группа, Un пользователь, DRn отдел, Gn группа - sel // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьНовости(Знач URL, Знач IDНовости = "", Знач Отбор = "UA", Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "log.blogpost.get"); - + OPI_Инструменты.ДобавитьПоле("POST_ID" , IDНовости, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("LOG_RIGHTS", Отбор , "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Добавить комментарий новости // Добавляет комментарий к новости -// +// // Примечание: // Метод в документации API: [log.blogcomment.add](@dev.1c-bitrix.ru/rest_help/log/log_blogcomment_add.php) -// +// // Параметры: -// URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url +// URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDНовости - Строка, Число - ID новости - postid // Текст - Строка - Текст комментария - text // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ДобавитьКомментарийНовости(Знач URL, Знач IDНовости, Знач Текст, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "log.blogcomment.add"); - + OPI_Инструменты.ДобавитьПоле("POST_ID" , IDНовости, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("TEXT" , Текст , "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Добавить получателей к новости // Добавляет новые группы или пользователей в получатели -// +// // Примечание: // Метод в документации API: [log.blogpost.share](@dev.1c-bitrix.ru/rest_help/log/log_blogpost_share.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDНовости - Строка, Число - ID новости - postid // Видимость - Строка - Массив или 1 получатель: UA все, SGn р. группа, Un пользователь, DRn отдел, Gn группа - vision // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ДобавитьПолучателейКНовости(Знач URL, Знач IDНовости, Знач Видимость, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "log.blogpost.share"); - + OPI_Инструменты.ДобавитьПоле("POST_ID" , IDНовости, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("DEST" , Видимость, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -391,132 +391,132 @@ // Получить задачу // Получает задачу по ID -// +// // Примечание: // Метод в документации API: [tasks.task.get](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_get.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьЗадачу(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.get", Токен); Возврат Ответ; - + КонецФункции // Получить список задач // Получает список задач (50 шт. за запрос максимум) с фильтром или без (см. ПолучитьСтруктуруФильтраЗадач) -// +// // Примечание: // Метод в документации API: [tasks.task.list](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_list.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Фильтр - Структура из КлючИЗначение - Структура отбора задач (см. ПолучитьСтруктуруФильтраЗадач) - filter // Отступ - Число, Строка - Отступ от начала списка для полчения задач > 50 шт. рекурсивно - offset // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьСписокЗадач(Знач URL, Знач Фильтр = "", Знач Отступ = 0, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "tasks.task.list"); OPI_Инструменты.ДобавитьПоле("filter", Фильтр, "Коллекция", Параметры); OPI_Инструменты.ДобавитьПоле("start" , Отступ, "Строка" , Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Создать задачу // Создает новую задачу по структуре полей (см. ПолучитьСтруктуруЗадачи) -// +// // Примечание: // Метод в документации API: [tasks.task.add](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_add.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // СтруктураПолей - Структура Из КлючИЗначение - Структура полей задачи (см. ПолучитьСтруктуруЗадачи) - fields // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция СоздатьЗадачу(Знач URL, Знач СтруктураПолей, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "tasks.task.add"); OPI_Инструменты.ДобавитьПоле("fields", СтруктураПолей, "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; КонецФункции // Изменить задачу // Изменяет существующую задачу -// +// // Примечание: // Метод в документации API: [tasks.task.update](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_update.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // СтруктураПолей - Структура Из КлючИЗначение - Структура полей задачи - fields // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ИзменитьЗадачу(Знач URL, Знач IDЗадачи, Знач СтруктураПолей, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "tasks.task.update"); OPI_Инструменты.ДобавитьПоле("fields", СтруктураПолей, "Коллекция", Параметры); OPI_Инструменты.ДобавитьПоле("taskId", IDЗадачи , "Строка" , Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; КонецФункции // Удалить задачу // Удаляет задачу по ID -// +// // Примечание: // Метод в документации API: [tasks.task.delete](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_delete.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УдалитьЗадачу(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.delete", Токен); Возврат Ответ; - + КонецФункции // Добавить файл в задачу // Прикрепляет файл к выбранной задаче -// +// // Примечание: // Метод в документации API: [tasks.task.files.attach](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_files_attach.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число, Строка - ID задачи - task // IDФайла - Число, Строка - ID Файла - fileid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ДобавитьФайлВЗадачу(Знач URL, Знач IDЗадачи, Знач IDФайла, Знач Токен = "") Экспорт @@ -524,467 +524,467 @@ Параметры = НормализоватьАвторизацию(URL, Токен, "tasks.task.files.attach"); OPI_Инструменты.ДобавитьПоле("fileId", IDФайла , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("taskId", IDЗадачи, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Принять задачу // Принимает задачу по ID -// +// // Примечание: // Метод в документации API: [tasks.task.approve](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_approve.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПринятьЗадачу(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.approve", Токен); Возврат Ответ; - + КонецФункции // Отклонить задачу // Отклоняет задачу по ID -// +// // Примечание: // Метод в документации API: [tasks.task.disapprove](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_disapprove.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ОтклонитьЗадачу(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.disapprove", Токен); Возврат Ответ; - + КонецФункции // Завершить задачу // Завершает задачу по ID -// +// // Примечание: // Метод в документации API: [tasks.task.complete](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_complete.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ЗавершитьЗадачу(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.complete", Токен); Возврат Ответ; - + КонецФункции // Возобновить задачу // Возвращает в работу задачу по ID -// +// // Примечание: // Метод в документации API: [tasks.task.renew](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_renew.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ВозобновитьЗадачу(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.renew", Токен); Возврат Ответ; - + КонецФункции // Отложить задачу // Откладывает задачу по ID -// +// // Примечание: // Метод в документации API: [tasks.task.defer](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_defer.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ОтложитьЗадачу(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.defer", Токен); Возврат Ответ; - + КонецФункции // Приостановить задачу // Приостанавливает задачу по ID -// +// // Примечание: // Метод в документации API: [tasks.task.pause](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_pause.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПриостановитьЗадачу(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.pause", Токен); Возврат Ответ; - + КонецФункции // Начать выполнение задачи // Начинает выполнение задачи по ID -// +// // Примечание: // Метод в документации API: [tasks.task.start](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_start.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция НачатьВыполнениеЗадачи(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.start", Токен); Возврат Ответ; - + КонецФункции // Начать наблюдать за задачей // Начинает наблюдение за задачей по ID -// +// // Примечание: // Метод в документации API: [tasks.task.startwatch](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_startwatch.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция НачатьНаблюдатьЗаЗадачей(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.startwatch", Токен); Возврат Ответ; - + КонецФункции // Прекратить наблюдать за задачей // Прекращает наблюдение за задчей по ID -// +// // Примечание: // Метод в документации API: [tasks.task.stopwatch](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_stopwatch.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПрекратитьНаблюдатьЗаЗадачей(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.stopwatch", Токен); Возврат Ответ; - + КонецФункции // Делегировать задачу // Делегирует задачу на другого пользователя -// +// // Примечание: // Метод в документации API: [tasks.task.delegate](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_delegate.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // IDПользователя - Число,Строка - ID пользователя исполнителя - user // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ДелегироватьЗадачу(Знач URL, Знач IDЗадачи, Знач IDПользователя, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "tasks.task.delegate"); OPI_Инструменты.ДобавитьПоле("taskId", IDЗадачи , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("userId", IDПользователя, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Добавить задачу в избранное // Добавляет задачу в список избранного -// +// // Примечание: // Метод в документации API: [tasks.task.favorite.add](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_favorite_add.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ДобавитьЗадачуВИзбранное(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.favorite.add", Токен); Возврат Ответ; - + КонецФункции // Убрать задачу из избранного // Удаляет задачу из списка избранного -// +// // Примечание: // Метод в документации API: [tasks.task.favorite.remove](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_favorite_remove.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УбратьЗадачуИзИзбранного(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.favorite.remove", Токен); Возврат Ответ; - + КонецФункции // Получить историю задачи // Получает историю изменений задачи -// +// // Примечание: // Метод в документации API: [tasks.task.history.list](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_history_list.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьИсториюЗадачи(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.history.list", Токен); Возврат Ответ; - + КонецФункции // Проверить доступ к задаче // Проверяет доступность задачи для пользователей -// +// // Примечание: // Метод в документации API: [tasks.task.getaccess](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_getaccess.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Пользователи - Массив из Строка - ID пользователей для проверки доступа - users // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПроверитьДоступКЗадаче(Знач URL, Знач IDЗадачи, Знач Пользователи = "", Знач Токен = "") Экспорт Параметры = НормализоватьАвторизацию(URL, Токен, "tasks.task.getaccess"); OPI_Инструменты.ДобавитьПоле("taskId", IDЗадачи , "Строка" , Параметры); - OPI_Инструменты.ДобавитьПоле("users" , Пользователи, "Массив", Параметры); - + OPI_Инструменты.ДобавитьПоле("users" , Пользователи, "Массив" , Параметры); + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Отключить звук задачи // Устанавливает режим Без звука для задачи -// +// // Примечание: // Метод в документации API: [tasks.task.mute](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/mute_unmute.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ОтключитьЗвукЗадачи(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.mute", Токен); Возврат Ответ; - + КонецФункции // Включить звук задачи // Отключает режим Без звука для задачи -// +// // Примечание: // Метод в документации API: [tasks.task.unmute](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/mute_unmute.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ВключитьЗвукЗадачи(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.unmute", Токен); Возврат Ответ; - + КонецФункции // Создать зависимость задач // Создает зависимость одной задачи от другой -// +// // Примечание: // Метод в документации API: [task.dependence.add](@dev.1c-bitrix.ru/rest_help/tasks/task/dependence/task_dependence_add.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDИсточника - Строка, Число - ID задачи источника связи - taskfrom // IDПриемника - Строка, Число - ID задачи приемника связи - taskto // ТипСвязи - Строка, Число - Тип связи: 0 старт>старт, 1 старт>финиш, 2 финиш>старт, 3 финиш>финиш - linktype // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция СоздатьЗависимостьЗадач(Знач URL, Знач IDИсточника, Знач IDПриемника, Знач ТипСвязи, Знач Токен = "") Экспорт - + Строка_ = "Строка"; - + OPI_ПреобразованиеТипов.ПолучитьСтроку(ТипСвязи); - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.dependence.add"); OPI_Инструменты.ДобавитьПоле("taskIdFrom", IDИсточника, Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("taskIdTo" , IDПриемника, Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("linkType" , ТипСвязи , Строка_, Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Удалить зависимость задач // Удаляет зависимость одной задачи от другой -// +// // Примечание: // Метод в документации API: [task.dependence.delete](@dev.1c-bitrix.ru/rest_help/tasks/task/dependence/task_dependence_delete.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDИсточника - Строка, Число - ID задачи источника связи - taskfrom // IDПриемника - Строка, Число - ID задачи приемника связи - taskto // ТипСвязи - Строка, Число - Тип связи: 0 старт>старт, 1 старт>финиш, 2 финиш>старт, 3 финиш>финиш - linktype // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УдалитьЗависимостьЗадач(Знач URL, Знач IDИсточника, Знач IDПриемника, Знач ТипСвязи, Знач Токен = "") Экспорт - + Строка_ = "Строка"; - + OPI_ПреобразованиеТипов.ПолучитьСтроку(ТипСвязи); - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.dependence.delete"); OPI_Инструменты.ДобавитьПоле("taskIdFrom", IDИсточника, Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("taskIdTo" , IDПриемника, Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("linkType" , ТипСвязи , Строка_, Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить план задач на день // Получает план задач на день текущего пользователя -// +// // Примечание: // Метод в документации API: [task.planner.getlist](@dev.1c-bitrix.ru/rest_help/tasks/task/planner/getlist.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьПланЗадачНаДень(Знач URL, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.planner.getlist"); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить структуру задачи // Получает структуру с описанем полей для создания задачи -// +// // Примечание: // Метод в документации API: [tasks.task.getFields](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_getFields.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьСтруктуруЗадачи(Знач URL, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "tasks.task.getFields"); - Ответ = OPI_Инструменты.Get(URL, Параметры); - + Ответ = OPI_Инструменты.Get(URL, Параметры); + Возврат Ответ; - -КонецФункции + +КонецФункции // Получить структуру фильтра задач // Возвращает структуру полей для фильтрации задач в методе ПолучитьСписокЗадач -// +// // Параметры: // Пустая - Булево - Истина > структура с пустыми значениями, Ложь > в значениях будут описания полей - empty -// +// // Возвращаемое значение: -// Структура Из КлючИЗначение - Структура полей +// Структура Из КлючИЗначение - Структура полей Функция ПолучитьСтруктуруФильтраЗадач(Знач Пустая = Ложь) Экспорт - + // Подробнее // https://dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_list.php - + OPI_ПреобразованиеТипов.ПолучитьБулево(Пустая); - + СтруктураФильтра = Новый Структура; СтруктураФильтра.Вставить("ID" , "<идентификатор задачи>"); СтруктураФильтра.Вставить("PARENT_ID" , "<идентификатор родительской задачи>"); @@ -1013,7 +1013,7 @@ СтруктураФильтра.Вставить("UF_CRM_TASK" , "<элементы CRM>"); СтруктураФильтра.Вставить("STATUS" , "<статус для сортировки. Аналогичен REAL_STATUS, но имеет дополнительно три мета-статуса>"); - + Если Пустая Тогда Для Каждого Фильтр Из СтруктураФильтра Цикл Фильтр.Значение = ""; @@ -1022,7 +1022,7 @@ //@skip-check constructor-function-return-section Возврат СтруктураФильтра; - + КонецФункции #КонецОбласти @@ -1031,185 +1031,185 @@ // Добавить элемент чеклиста задачи // Добавляет новый элемент чеклиста задачи -// +// // Примечание: // Метод в документации API: [task.checklistitem.add](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/add.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число, Строка - ID задачи - task // Текст - Строка - Текст (заголовок) пункта чек листа - text // Выполнен - Булево - Отметить пункт как выполненный - complete // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ДобавитьЭлементЧеклистаЗадачи(Знач URL, Знач IDЗадачи, Знач Текст, Знач Выполнен = Ложь, Токен = "") Экспорт - + Строка_ = "Строка"; - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.checklistitem.add"); Поля = Новый Структура; - + ПривестиБулево(Выполнен); - + OPI_Инструменты.ДобавитьПоле("TITLE" , Текст , Строка_, Поля); OPI_Инструменты.ДобавитьПоле("IS_COMPLETE", Выполнен, Строка_, Поля); - + OPI_Инструменты.ДобавитьПоле("TASKID", IDЗадачи, Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("FIELDS", Поля , "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Изменить элемент чеклиста задачи // Изменяет текст элемента чеклиста задачи -// +// // Примечание: // Метод в документации API: [task.checklistitem.update](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/update.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число, Строка - ID задачи - task // IDЭлемента - Число, Строка - ID элемента чеклиста - element // Текст - Строка - Текст (заголовок) пункта чек листа - text // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ИзменитьЭлементЧеклистаЗадачи(Знач URL, Знач IDЗадачи, Знач IDЭлемента, Знач Текст, Знач Токен = "") Экспорт - + Строка_ = "Строка"; - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.checklistitem.update"); Поля = Новый Структура; - + OPI_Инструменты.ДобавитьПоле("TITLE", Текст, Строка_, Поля); - + OPI_Инструменты.ДобавитьПоле("TASKID", IDЗадачи , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("ITEMID", IDЭлемента, Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("FIELDS", Поля , "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции - + // Удалить элемент чеклиста задачи // Удаляет элемент из чеклиста задачи -// +// // Примечание: // Метод в документации API: [task.checklistitem.delete](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/delete.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число, Строка - ID задачи - task // IDЭлемента - Число, Строка - ID элемента для удаления - element // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УдалитьЭлементЧеклистаЗадачи(Знач URL, Знач IDЗадачи, Знач IDЭлемента, Знач Токен = "") Экспорт Ответ = УправлениеЭлементомЧеклиста(URL, IDЗадачи, IDЭлемента, "task.checklistitem.delete", Токен); - + Возврат Ответ; - + КонецФункции // Получить чеклист задачи // Получает список элементов чеклиста задачи -// +// // Примечание: // Метод в документации API: [task.checklistitem.getlist](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/getlist.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число, Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьЧеклистЗадачи(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.checklistitem.getlist"); - + OPI_Инструменты.ДобавитьПоле("TASKID", IDЗадачи , "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить элемент чеклиста задачи // Получить элемент чеклиста задачи по ID -// +// // Примечание: // Метод в документации API: [task.checklistitem.get](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/get.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число, Строка - ID задачи - task // IDЭлемента - Число, Строка - ID элемента для получения - element // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьЭлементЧеклистаЗадачи(Знач URL, Знач IDЗадачи, Знач IDЭлемента, Знач Токен = "") Экспорт - + Ответ = УправлениеЭлементомЧеклиста(URL, IDЗадачи, IDЭлемента, "task.checklistitem.get", Токен); - + Возврат Ответ; - + КонецФункции // Выполнить элемент чеклиста задачи // Помечает элемент чеклиста задачи как выполненный -// +// // Примечание: // Метод в документации API: [task.checklistitem.complete](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/complete.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число, Строка - ID задачи - task // IDЭлемента - Число, Строка - ID элемента - element // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ВыполнитьЭлементЧеклистаЗадачи(Знач URL, Знач IDЗадачи, Знач IDЭлемента, Знач Токен = "") Экспорт - + Ответ = УправлениеЭлементомЧеклиста(URL, IDЗадачи, IDЭлемента, "task.checklistitem.complete", Токен); - + Возврат Ответ; - + КонецФункции // Возобновить элемент чеклиста задачи -// Снимает пометку элемента как выполненного -// +// Снимает пометку элемента как выполненного +// // Примечание: // Метод в документации API: [task.checklistitem.renew](@dev.1c-bitrix.ru/rest_help/tasks/task/checklistitem/renew.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число, Строка - ID задачи - task // IDЭлемента - Число, Строка - ID элемента - element // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ВозобновитьЭлементЧеклистаЗадачи(Знач URL, Знач IDЗадачи, Знач IDЭлемента, Знач Токен = "") Экспорт - + Ответ = УправлениеЭлементомЧеклиста(URL, IDЗадачи, IDЭлемента, "task.checklistitem.renew", Токен); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -1218,15 +1218,15 @@ // Получить список комментариев задачи // Полчает список комментариев пользователей к задаче по ID -// +// // Примечание: // Метод в документации API: [task.commentitem.getlist](@dev.1c-bitrix.ru/rest_help/tasks/task/commentitem/getlist.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число, Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьСписокКомментариевЗадачи(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт @@ -1238,203 +1238,203 @@ // Получить комменатрий задачи // Получает информацию о комментарии задачи по ID -// +// // Примечание: // Метод в документации API: [task.commentitem.get](@dev.1c-bitrix.ru/rest_help/tasks/task/commentitem/get.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число, Строка - ID задачи - task // IDКомментария - Число, Строка - ID комментария - comment // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьКомменатрийЗадачи(Знач URL, Знач IDЗадачи, Знач IDКомментария, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.commentitem.get"); OPI_Инструменты.ДобавитьПоле("TASKID", IDЗадачи , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("ITEMID", IDКомментария, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Добавить комментарий задачи // Создает комментарий к задаче -// +// // Примечание: // Метод в документации API: [task.commentitem.add](@dev.1c-bitrix.ru/rest_help/tasks/task/commentitem/add.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число, Строка - ID задачи - task // Текст - Строка - Текст комментария - text // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ДобавитьКомментарийЗадачи(Знач URL, Знач IDЗадачи, Знач Текст, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.commentitem.add"); - + Комментарий = Новый Структура; OPI_Инструменты.ДобавитьПоле("POST_MESSAGE", Текст, "Строка", Комментарий); - + OPI_Инструменты.ДобавитьПоле("TASKID", IDЗадачи , "Строка" , Параметры); OPI_Инструменты.ДобавитьПоле("FIELDS", Комментарий, "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Изменить комментарий задачи // Изменяет текст комментария задачи -// +// // Примечание: // Метод в документации API: [task.commentitem.update](@dev.1c-bitrix.ru/rest_help/tasks/task/commentitem/update.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число, Строка - ID задачи - task // IDКомментария - Число, Строка - ID комментария - comment // Текст - Строка - Текст комментария - text // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ИзменитьКомментарийЗадачи(Знач URL, Знач IDЗадачи, Знач IDКомментария, Знач Текст, Знач Токен = "") Экспорт - + Строка_ = "Строка"; - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.commentitem.update"); - + Комментарий = Новый Структура; OPI_Инструменты.ДобавитьПоле("POST_MESSAGE", Текст, "Строка", Комментарий); - + OPI_Инструменты.ДобавитьПоле("TASKID", IDЗадачи , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("ITEMID", IDКомментария, Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("FIELDS", Комментарий , "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Удалить комментарий // Удаляет существующий комментарий задачи -// +// // Примечание: // Метод в документации API: [task.commentitem.delete](@dev.1c-bitrix.ru/rest_help/tasks/task/commentitem/delete.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число, Строка - ID задачи - task // IDКомментария - Число, Строка - ID удаляемого комментария - comment // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УдалитьКомментарийЗадачи(Знач URL, Знач IDЗадачи, Знач IDКомментария, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.commentitem.delete"); OPI_Инструменты.ДобавитьПоле("TASKID", IDЗадачи , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("ITEMID", IDКомментария, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить список результатов // Получает список результатов задачи -// +// // Примечание: // Метод в документации API: [tasks.task.result.list](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_result.list.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Число,Строка - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьСписокРезультатов(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Ответ = УправлениеЗадачей(URL, IDЗадачи, "tasks.task.result.list", Токен); Возврат Ответ; - + КонецФункции // Создать результат из комментария // Создает результат задачи из комментария -// +// // Примечание: // Метод в документации API: [tasks.task.result.addFromComment](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_result_addFromComment.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDКомментария - Число, Строка - ID комментария - comment // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция СоздатьРезультатИзКомментария(Знач URL, Знач IDКомментария, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "tasks.task.result.addFromComment"); OPI_Инструменты.ДобавитьПоле("commentId", IDКомментария, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Удалить результат из комментария // Удаляет ранее созданный результат из комментария -// +// // Примечание: // Метод в документации API: [tasks.task.result.deleteFromComment](@dev.1c-bitrix.ru/rest_help/tasks/task/tasks/tasks_task_result_deleteFromComment.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDКомментария - Число, Строка - ID комментария - comment // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УдалитьРезультатИзКомментария(Знач URL, Знач IDКомментария, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "tasks.task.result.deleteFromComment"); OPI_Инструменты.ДобавитьПоле("commentId", IDКомментария, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить структуру комментария // Получает структуру полей комментария -// +// // Параметры: // Пустая - Булево - Истина > структура с пустыми значениями, Ложь > в значениях будут описания полей - empty -// +// // Возвращаемое значение: -// Структура Из КлючИЗначение - Структура полей +// Структура Из КлючИЗначение - Структура полей Функция ПолучитьСтруктуруКомментария(Знач Пустая = Ложь) Экспорт - + // Подробнее // https://dev.1c-bitrix.ru/rest_help/tasks/task/commentitem/add.php - + OPI_ПреобразованиеТипов.ПолучитьБулево(Пустая); - + СтруктураПолей = Новый Структура; СтруктураПолей.Вставить("AUTHOR_ID" , "<идентификатор автора комментария>"); СтруктураПолей.Вставить("AUTHOR_NAME" , "<Имя пользователя (опционально)>"); @@ -1442,16 +1442,16 @@ СтруктураПолей.Вставить("USE_SMILES" , "<(Y|N) - парсить или нет комментарии на наличие смайлов>"); СтруктураПолей.Вставить("POST_MESSAGE" , "<Текст сообщения>"); СтруктураПолей.Вставить("UF_FORUM_MESSAGE_DOC" , "<Массив файлов с диска для прикрепления>"); - + Если Пустая Тогда Для Каждого Поле Из СтруктураПолей Цикл Поле.Значение = ""; КонецЦикла; КонецЕсли; - + //@skip-check constructor-function-return-section Возврат СтруктураПолей; - + КонецФункции #КонецОбласти @@ -1460,10 +1460,10 @@ // Добавить стадию канбана // Добавляет стабию канбана или Моего плана -// +// // Примечание: // Метод в документации API: [task.stages.add](@dev.1c-bitrix.ru/rest_help/tasks/task/kanban/task_stages_add.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Наименование - Строка - Наименование новой стадии - title @@ -1472,7 +1472,7 @@ // IDСущности - Строка, Число - ID группы или пользователя владельца канбан. Свой по умолчанию - entityid // КакАдминистратор - Булево - Позволяет добавлять стадии без проверки прав (для администраторов) - admin // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ДобавитьСтадиюКанбана(Знач URL @@ -1482,34 +1482,34 @@ , Знач IDСущности = 0 , Знач КакАдминистратор = Ложь , Знач Токен = "") Экспорт - + Строка_ = "Строка"; - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.stages.add"); Поля = Новый Структура; - + ПривестиБулево(КакАдминистратор); - + OPI_Инструменты.ДобавитьПоле("TITLE" , Наименование , Строка_, Поля); OPI_Инструменты.ДобавитьПоле("COLOR" , Цвет , Строка_, Поля); OPI_Инструменты.ДобавитьПоле("AFTER_ID" , IDПредыдущей , Строка_, Поля); OPI_Инструменты.ДобавитьПоле("ENTITY_ID", IDСущности , Строка_, Поля); OPI_Инструменты.ДобавитьПоле("isAdmin" , КакАдминистратор, Строка_, Поля); - + Параметры.Вставить("fields", Поля); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Изменить стадию канбана // Изменяет свойства существующей стадии канбана или Моего плана -// +// // Примечание: // Метод в документации API: [task.stages.update](@dev.1c-bitrix.ru/rest_help/tasks/task/kanban/task_stages_update.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Наименование - Строка - Новое наименование стадии - title @@ -1518,7 +1518,7 @@ // IDПредыдущей - Строка, Число - ID стадии, после которой необходимо вставить выбранную - prevstage // КакАдминистратор - Булево - Позволяет добавлять стадии без проверки прав (для администраторов) - admin // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ИзменитьСтадиюКанбана(Знач URL @@ -1528,91 +1528,91 @@ , Знач IDПредыдущей = 0 , Знач КакАдминистратор = Ложь , Знач Токен = "") Экспорт - + Строка_ = "Строка"; - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.stages.update"); Поля = Новый Структура; - - OPI_Инструменты.ДобавитьПоле("TITLE" , Наименование , Строка_, Поля); - OPI_Инструменты.ДобавитьПоле("COLOR" , Цвет , Строка_, Поля); - OPI_Инструменты.ДобавитьПоле("AFTER_ID" , IDПредыдущей , Строка_, Поля); + + OPI_Инструменты.ДобавитьПоле("TITLE" , Наименование , Строка_ , Поля); + OPI_Инструменты.ДобавитьПоле("COLOR" , Цвет , Строка_ , Поля); + OPI_Инструменты.ДобавитьПоле("AFTER_ID" , IDПредыдущей , Строка_ , Поля); OPI_Инструменты.ДобавитьПоле("isAdmin" , КакАдминистратор, "Булево", Поля); - + OPI_Инструменты.ДобавитьПоле("id" , IDСтадии, Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("fields", Поля , "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Удалить стадию канбана // Удаляет стадию канбана или Моего плана, при условии, что в ней нет задач -// +// // Примечание: // Метод в документации API: [task.stages.delete](@dev.1c-bitrix.ru/rest_help/tasks/task/kanban/task_stages_delete.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDСтадии - Строка, Число - ID стадии для удаления - stage // КакАдминистратор - Булево - Позволяет добавлять стадии без проверки прав (для администраторов) - admin // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УдалитьСтадиюКанбана(Знач URL, Знач IDСтадии, Знач КакАдминистратор = Ложь, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.stages.delete"); - + ПривестиБулево(КакАдминистратор); - + OPI_Инструменты.ДобавитьПоле("id" , IDСтадии , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("isAdmin", КакАдминистратор, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить стадии канбана // Получает информацию о стадиях Канбана или Моего плана -// +// // Примечание: // Метод в документации API: [task.stages.get](@dev.1c-bitrix.ru/rest_help/tasks/task/kanban/task_stages_get.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDСущности - Строка, Число - ID группы или пользователя владельца канбан. Свой по умолчанию - entityid // КакАдминистратор - Булево - Позволяет получать стадии без проверки прав (для администраторов) - admin // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьСтадииКанбана(Знач URL, Знач IDСущности = 0, Знач КакАдминистратор = Ложь, Знач Токен = "") Экспорт - + IDСущности = OPI_Инструменты.ЧислоВСтроку(IDСущности); Параметры = НормализоватьАвторизацию(URL, Токен, "task.stages.get"); - + ПривестиБулево(КакАдминистратор); - + OPI_Инструменты.ДобавитьПоле("entityId", IDСущности , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("isAdmin" , КакАдминистратор, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Перенести задачу в стадию канбана // Переносит задачу в выбранную стадию канбана -// +// // Примечание: // Метод в документации API: [task.stages.movetask](@dev.1c-bitrix.ru/rest_help/tasks/task/kanban/task_stages_movetask.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Строка, Число - ID задачи для переноса - task @@ -1620,7 +1620,7 @@ // Перед - Строка, Число - ID задачи, перед которой надо поставить выбранную (если не заполнено После) - before // После - Строка, Число - ID задачи, после которой надо поставить выбранную (если не заполнено Перед) - after // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПеренестиЗадачуВСтадиюКанбана(Знач URL @@ -1629,29 +1629,29 @@ , Знач Перед = 0 , Знач После = 0 , Знач Токен = "") Экспорт - + Строка_ = "Строка"; - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.stages.movetask"); - + OPI_Инструменты.ДобавитьПоле("id" , IDЗадачи, Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("stageId", IDСтадии, Строка_, Параметры); - + Если ЗначениеЗаполнено(Перед) Тогда - + OPI_Инструменты.ДобавитьПоле("before", Перед, Строка_, Параметры); - + Иначе - + OPI_ПреобразованиеТипов.ПолучитьСтроку(После); OPI_Инструменты.ДобавитьПоле("after", После, Строка_, Параметры); - + КонецЕсли; - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -1660,10 +1660,10 @@ // Добавить трудозатраты задачи // Добавляет информацию о затраченном времени пользователя в задачу -// +// // Примечание: // Метод в документации API: [task.elapseditem.add](@dev.1c-bitrix.ru/rest_help/tasks/task/elapseditem/add.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Строка, Число - ID задачи для добавления затрат - task @@ -1672,7 +1672,7 @@ // Текст - Строка - Текст комментария трудозатраты - text // ДатаУстановки - Строка - Дата установки трудозатрат - date // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ДобавитьТрудозатратыЗадачи(Знач URL @@ -1682,111 +1682,111 @@ , Знач Текст = "" , Знач ДатаУстановки = "" , Знач Токен = "") Экспорт - + Строка_ = "Строка"; - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.elapseditem.add"); Поля = Новый Структура; - + OPI_Инструменты.ДобавитьПоле("SECONDS" , Время , Строка_ , Поля); OPI_Инструменты.ДобавитьПоле("COMMENT_TEXT", Текст , Строка_ , Поля); OPI_Инструменты.ДобавитьПоле("USER_ID" , IDПользователя, Строка_ , Поля); OPI_Инструменты.ДобавитьПоле("CREATED_DATE", ДатаУстановки , "ДатаISO", Поля); - + OPI_Инструменты.ДобавитьПоле("TASKID" , IDЗадачи, Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("ARFIELDS", Поля , "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Удалить трудозатраты задачи // Удаляет запись о трудозатратах из задачи -// +// // Примечание: // Метод в документации API: [task.elapseditem.delete](@dev.1c-bitrix.ru/rest_help/tasks/task/elapseditem/delete.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Строка, Число - ID задачи для добавления затрат - task // IDЗаписи - Строка, Число - ID записи о трудозатратах - record // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УдалитьТрудозатратыЗадачи(Знач URL, Знач IDЗадачи, Знач IDЗаписи, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.elapseditem.delete"); - + OPI_Инструменты.ДобавитьПоле("TASKID", IDЗадачи, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("ITEMID", IDЗаписи, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить список трудозатрат задачи // Получает список записей о трудозатратах задачи -// +// // Примечание: // Метод в документации API: [task.elapseditem.getlist](@dev.1c-bitrix.ru/rest_help/tasks/task/elapseditem/getlist.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Строка, Число - ID задачи - task // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьСписокТрудозатратЗадачи(Знач URL, Знач IDЗадачи, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.elapseditem.getlist"); - + OPI_Инструменты.ДобавитьПоле("TASKID", IDЗадачи, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить трудозатраты задачи // Получает информацию о записи трудозатрат задачи по ID -// +// // Примечание: // Метод в документации API: [task.elapseditem.get](@dev.1c-bitrix.ru/rest_help/tasks/task/elapseditem/get.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Строка, Число - ID задачи - task // IDЗаписи - Строка, Число - ID записи о трудозатратах - record // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьТрудозатратыЗадачи(Знач URL, Знач IDЗадачи, Знач IDЗаписи, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.elapseditem.get"); - + OPI_Инструменты.ДобавитьПоле("TASKID", IDЗадачи, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("ITEMID", IDЗаписи, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Изменить трудозатраты задачи // Изменяет данные записи о трудозатратах задачи -// +// // Примечание: // Метод в документации API: [task.elapseditem.update](@dev.1c-bitrix.ru/rest_help/tasks/task/elapseditem/update.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЗадачи - Строка, Число - ID задачи - task @@ -1795,7 +1795,7 @@ // Текст - Строка - Текст комментария трудозатраты - text // ДатаУстановки - Строка - Дата установки трудозатрат - date // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ИзменитьТрудозатратыЗадачи(Знач URL @@ -1805,24 +1805,24 @@ , Знач Текст = "" , Знач ДатаУстановки = "" , Знач Токен = "") Экспорт - + Строка_ = "Строка"; - + Параметры = НормализоватьАвторизацию(URL, Токен, "task.elapseditem.update"); Поля = Новый Структура; - + OPI_Инструменты.ДобавитьПоле("SECONDS" , Время , Строка_ , Поля); OPI_Инструменты.ДобавитьПоле("COMMENT_TEXT", Текст , Строка_ , Поля); OPI_Инструменты.ДобавитьПоле("CREATED_DATE", ДатаУстановки , "ДатаISO", Поля); - + OPI_Инструменты.ДобавитьПоле("TASKID" , IDЗадачи, Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("ITEMID" , IDЗаписи, Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("ARFIELDS", Поля , "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -1831,142 +1831,142 @@ // Получить список хранилищ // Получает список доступных хранилищ файлов -// +// // Примечание: // Метод в документации API: [disk.storage.getlist](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_getlist.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьСписокХранилищ(Знач URL, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.storage.getlist"); Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; КонецФункции // Получить хранилище приложения // Получает информацию о хранилище с которым может работать приложение для хранения своих данных -// +// // Примечание: // Метод в документации API: [disk.storage.getforapp](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_getforapp.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьХранилищеПриложения(Знач URL, Знач Токен = "") Экспорт - - Параметры = НормализоватьАвторизацию(URL, Токен, "disk.storage.getforapp"); + + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.storage.getforapp"); Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить хранилище // Получает информацию о хранилище по ID -// +// // Примечание: // Метод в документации API: [disk.storage.get](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_get.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDХранилища - Строка, Число - Идентификатор хранилища - storageid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьХранилище(Знач URL, Знач IDХранилища, Знач Токен = "") Экспорт - + Ответ = УправлениеФайлом(URL, IDХранилища, "disk.storage.get", Токен); Возврат Ответ; - + КонецФункции // Переименовать хранилище // Изменяет имя хранилища (только для хранилища приложения см. ПолучитьСписокХранилищПриложения) -// +// // Примечание: // Метод в документации API: [disk.storage.rename](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_rename.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDХранилища - Строка, Число - Идентификатор хранилища - storageid // Наименование - Строка - Новое наименование хранилища - title // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПереименоватьХранилище(Знач URL, Знач IDХранилища, Знач Наименование, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.storage.rename"); - + OPI_Инструменты.ДобавитьПоле("id" , IDХранилища , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("newName", Наименование, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить содержимое хранилища // Получает список файлов и каталогов, находящихся в корне хранилища -// +// // Примечание: // Метод в документации API: [disk.storage.getchildren](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_getchildren.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDХранилища - Строка, Число - Идентификатор хранилища - storageid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьСодержимоеХранилища(Знач URL, Знач IDХранилища, Знач Токен = "") Экспорт - + Ответ = УправлениеФайлом(URL, IDХранилища, "disk.storage.getchildren", Токен); Возврат Ответ; - + КонецФункции // Создать каталог в хранилище // Создает пустой каталог в хранилище -// +// // Примечание: // Метод в документации API: [disk.storage.addfolder](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_addfolder.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDХранилища - Строка - Идентификатор хранилища - storageid // Наименование - Строка - Имя каталога - title // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция СоздатьКаталогВХранилище(Знач URL, Знач IDХранилища, Знач Наименование, Знач Токен = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Наименование); - + СтруктураПапки = Новый Структура("NAME", Наименование); - + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.storage.addfolder"); - + OPI_Инструменты.ДобавитьПоле("id" , IDХранилища , "Строка" , Параметры); OPI_Инструменты.ДобавитьПоле("data", СтруктураПапки, "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции #КонецОбласти @@ -1975,279 +1975,279 @@ // Получить информацию о каталоге // Получает информацию о каталоге -// +// // Примечание: // Метод в документации API: [disk.folder.get](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_get.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDКаталога - Строка, Число - Идентификатор каталога - folderid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьИнформациюОКаталоге(Знач URL, Знач IDКаталога, Знач Токен = "") Экспорт - + Ответ = УправлениеФайлом(URL, IDКаталога, "disk.folder.get", Токен); Возврат Ответ; - + КонецФункции // Создать подкаталог // Создает каталог внутри другого каталога -// +// // Примечание: // Метод в документации API: [disk.folder.addsubfolder](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_addsubfolder.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDКаталога - Строка, Число - Идентификатор каталога родителя - folderid // Наименование - Строка - Наименование нового каталога - title // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция СоздатьПодкаталог(Знач URL, Знач IDКаталога, Знач Наименование, Знач Токен = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Наименование); - + СтруктураПапки = Новый Структура("NAME", Наименование); - + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.folder.addsubfolder"); - + OPI_Инструменты.ДобавитьПоле("id" , IDКаталога , "Строка" , Параметры); OPI_Инструменты.ДобавитьПоле("data", СтруктураПапки, "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции // Скопировать каталог // Копирует один каталог в другой -// +// // Примечание: // Метод в документации API: [disk.folder.copyto](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_copyto.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDКаталога - Строка, Число - Идентификатор каталога - folderid // IDПриемника - Строка, Число - ID каталога назначения - tagetid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция СкопироватьКаталог(Знач URL, Знач IDКаталога, Знач IDПриемника, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.folder.copyto"); - + OPI_Инструменты.ДобавитьПоле("id" , IDКаталога , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("targetFolderId", IDПриемника, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции // Переместить каталог // Перемещает один каталог внутрь другого -// +// // Примечание: // Метод в документации API: [disk.folder.moveto](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_moveto.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDКаталога - Строка, Число - Идентификатор каталога - folderid // IDПриемника - Строка, Число - ID каталога назначения - tagetid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПереместитьКаталог(Знач URL, Знач IDКаталога, Знач IDПриемника, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.folder.moveto"); - + OPI_Инструменты.ДобавитьПоле("id" , IDКаталога , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("targetFolderId", IDПриемника, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции // Удалить каталог // Удаляет каталог с подкаталогами -// +// // Примечание: // Метод в документации API: [disk.folder.deletetree](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_deletetree.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDКаталога - Строка, Число - Идентификатор удаляемого каталога - folderid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УдалитьКаталог(Знач URL, Знач IDКаталога, Знач Токен = "") Экспорт - + Ответ = УправлениеФайлом(URL, IDКаталога, "disk.folder.deletetree", Токен); Возврат Ответ; - + КонецФункции // Получить внешнюю ссылку каталога // Получает внешнюю ссылку для доступа к каталогу -// +// // Примечание: // Метод в документации API: [disk.folder.getExternalLink](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_getexternallink.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDКаталога - Строка, Число - Идентификатор каталога - folderid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьВнешнююСсылкуКаталога(Знач URL, Знач IDКаталога, Знач Токен = "") Экспорт - + Ответ = УправлениеФайлом(URL, IDКаталога, "disk.folder.getExternalLink", Токен); Возврат Ответ; - + КонецФункции // Получить дочерние элементы каталога // Получает дочерние элементы каталога -// +// // Примечание: // Метод в документации API: [disk.folder.getchildren](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_getchildren.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDКаталога - Строка, Число - Идентификатор каталога - folderid // Фильтр - Структура из КлючИЗначение - Отбор элементов (См. ПолучитьСтруктуруФильтраКаталога) - filter // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьДочерниеЭлементыКаталога(Знач URL, Знач IDКаталога, Знач Фильтр = "", Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.folder.getchildren"); OPI_Инструменты.ДобавитьПоле("id" , IDКаталога, "Строка" , Параметры); OPI_Инструменты.ДобавитьПоле("filter", Фильтр , "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Поместить каталог в корзину // Перемещает каталог в корзину удаляемых файлов -// +// // Примечание: // Метод в документации API: [disk.folder.markdeleted](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_markdeleted.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDКаталога - Строка, Число - Идентификатор каталога - folderid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПоместитьКаталогВКорзину(Знач URL, Знач IDКаталога, Знач Токен = "") Экспорт - + Ответ = УправлениеФайлом(URL, IDКаталога, "disk.folder.markdeleted", Токен); Возврат Ответ; - + КонецФункции // Восстановить каталог // Восстанавливает каталог из корзины -// +// // Примечание: // Метод в документации API: [disk.folder.restore](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_restore.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDКаталога - Строка, Число - Идентификатор каталога - folderid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ВосстановитьКаталог(Знач URL, Знач IDКаталога, Знач Токен = "") Экспорт - + Ответ = УправлениеФайлом(URL, IDКаталога, "disk.folder.restore", Токен); - Возврат Ответ; - + Возврат Ответ; + КонецФункции // Переименовать каталог // Изменяет имя каталога -// +// // Примечание: // Метод в документации API: [disk.folder.rename](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_rename.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDКаталога - Строка, Число - Идентификатор каталога - folderid // Наименование - Строка - Новое наименование каталога - title // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПереименоватьКаталог(Знач URL, Знач IDКаталога, Знач Наименование, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.folder.rename"); - + OPI_Инструменты.ДобавитьПоле("id" , IDКаталога , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("newName", Наименование, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции // Получить структуру фильтра каталога // Возвращает структуру полей для фильтрации дочерних элементов каталога -// +// // Примечание: // Метод в документации API: [disk.folder.getfields](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_getfields.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Пустая - Булево - Истина > структура с пустыми значениями, Ложь > в значениях будут описания типов полей - empty // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: -// Структура Из КлючИЗначение - Структура полей +// Структура Из КлючИЗначение - Структура полей Функция ПолучитьСтруктуруФильтраКаталога(Знач URL, Знач Пустая = Ложь, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.folder.getfields"); Фильтр = Новый Структура; - + Ответ = OPI_Инструменты.Post(URL, Параметры); Поля = Ответ["result"]; - + Для Каждого Поле Из Поля Цикл - + Имя = Поле.Ключ; Описание = Поле.Значение; - + Если Описание["USE_IN_FILTER"] Тогда - - ТипДанных = ?(Пустая, "", Описание["TYPE"]); + + ТипДанных = ?(Пустая, "", Описание["TYPE"]); Фильтр.Вставить(Имя, ТипДанных); - + КонецЕсли; - + КонецЦикла; - + Возврат Фильтр; - + КонецФункции #КонецОбласти @@ -2256,18 +2256,18 @@ // Загрузить файл в хранилище // Загружает файл в выбранное хранилище -// +// // Примечание: // Метод в документации API: [disk.storage.uploadfile](@dev.1c-bitrix.ru/rest_help/disk/storage/disk_storage_uploadfile.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Наименование - Строка - Наименование файла с расширением для сохранения - title -// Файл - Строка, ДвоичныеДанные - Файл для загрузки - file +// Файл - Строка, ДвоичныеДанные - Файл для загрузки - file // IDХранилища - Строка - Идентификатор хранилища для загрузки - storageid // Доступы - Строка - Массив доступов по задачам, если необходимо - rights // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ЗагрузитьФайлВХранилище(Знач URL @@ -2276,118 +2276,118 @@ , Знач IDХранилища , Знач Доступы = "" , Знач Токен = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDХранилища); OPI_ПреобразованиеТипов.ПолучитьСтроку(Наименование); - + Метод = "disk.storage.uploadfile"; ДанныеФайла = Новый Структура("NAME", Наименование); СодержимоеФайла = Новый Соответствие(); СодержимоеФайла.Вставить(Наименование, Файл); - + Параметры = НормализоватьАвторизацию(URL, Токен, Метод); OPI_Инструменты.ДобавитьПоле("data" , ДанныеФайла, "Коллекция", Параметры); OPI_Инструменты.ДобавитьПоле("rights", Доступы , "Массив" , Параметры); OPI_Инструменты.ДобавитьПоле("id" , IDХранилища, "Строка" , Параметры); МассивФайла = НормализоватьФайлы(СодержимоеФайла); - + Если Не МассивФайла.Количество() = 0 Тогда Параметры.Вставить("fileContent", МассивФайла[0]); КонецЕсли; - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Загрузить файл в каталог // Загружает переданный файл в каталог -// +// // Примечание: // Метод в документации API: [disk.folder.uploadfile](@dev.1c-bitrix.ru/rest_help/disk/folder/disk_folder_uploadfile.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Наименование - Строка - Наименование файла с расширением для сохранения - title -// Файл - Строка, ДвоичныеДанные - Файл для загрузки - file +// Файл - Строка, ДвоичныеДанные - Файл для загрузки - file // IDКаталога - Строка - Идентификатор каталога для загрузки - folderid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ЗагрузитьФайлВКаталог(Знач URL, Знач Наименование, Знач Файл, Знач IDКаталога, Знач Токен = "") Экспорт OPI_ПреобразованиеТипов.ПолучитьСтроку(Наименование); OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Файл); - + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.folder.uploadFile"); OPI_Инструменты.ДобавитьПоле("id", IDКаталога, "Строка", Параметры); - + Ответ = OPI_Инструменты.Get(URL, Параметры); Результат = Ответ["result"]; - + Если ЗначениеЗаполнено(Результат) Тогда - + ИмяПоля = Результат["field"]; URLЗагрузки = Результат["uploadUrl"]; - + Если ЗначениеЗаполнено(ИмяПоля) И ЗначениеЗаполнено(URLЗагрузки) Тогда - + ИмяПоля = СокрЛП(ИмяПоля); URLЗагрузки = СокрЛП(URLЗагрузки); ИмяФайла = ИмяПоля + "|" + Наименование; - + СоответствиеФайла = Новый Соответствие; - СоответствиеФайла.Вставить(ИмяФайла, Файл); - - Ответ = OPI_Инструменты.PostMultipart(URLЗагрузки, , СоответствиеФайла, ""); - + СоответствиеФайла.Вставить(ИмяФайла, Файл); + + Ответ = OPI_Инструменты.PostMultipart(URLЗагрузки, , СоответствиеФайла, ""); + КонецЕсли; - - КонецЕсли; - - Возврат Ответ; - + + КонецЕсли; + + Возврат Ответ; + КонецФункции // Получить информацию о файле // Получает информацию о файле по ID -// +// // Примечание: // Метод в документации API: [disk.file.get](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_get.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDФайла - Строка, Число - Идентификатор файла - fileid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьИнформациюОФайле(Знач URL, Знач IDФайла, Знач Токен = "") Экспорт - + Ответ = УправлениеФайлом(URL, IDФайла, "disk.file.get", Токен); Возврат Ответ; - + КонецФункции // Удалить файл // Удаляет файл по ID -// +// // Примечание: // Метод в документации API: [disk.file.delete](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_delete.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDФайла - Строка, Число - Идентификатор удаляемого файла - fileid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УдалитьФайл(Знач URL, Знач IDФайла, Знач Токен = "") Экспорт - + Ответ = УправлениеФайлом(URL, IDФайла, "disk.file.delete", Токен); Возврат Ответ; @@ -2395,143 +2395,143 @@ // Получить внешнюю ссылку файла // Получает внешнюю ссылку для доступа к файлу -// +// // Примечание: // Метод в документации API: [disk.file.getExternalLink](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_getexternallink.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDФайла - Строка, Число - Идентификатор файла - fileid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьВнешнююСсылкуФайла(Знач URL, Знач IDФайла, Знач Токен = "") Экспорт - + Ответ = УправлениеФайлом(URL, IDФайла, "disk.file.getExternalLink", Токен); Возврат Ответ; - + КонецФункции // Поместить файл в корзину // Перемещает файл в корзину удаляемых файлов -// +// // Примечание: // Метод в документации API: [disk.file.markdeleted](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_markdeleted.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDФайла - Строка, Число - Идентификатор файла - fileid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПоместитьФайлВКорзину(Знач URL, Знач IDФайла, Знач Токен = "") Экспорт - + Ответ = УправлениеФайлом(URL, IDФайла, "disk.file.markdeleted", Токен); Возврат Ответ; - + КонецФункции // Восстановить файл // Восстанавливает файл из корзины -// +// // Примечание: // Метод в документации API: [disk.file.restore](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_restore.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDФайла - Строка, Число - Идентификатор файла - fileid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ВосстановитьФайл(Знач URL, Знач IDФайла, Знач Токен = "") Экспорт - + Ответ = УправлениеФайлом(URL, IDФайла, "disk.file.restore", Токен); Возврат Ответ; - + КонецФункции // Скопировать файл // Копирует файл из одного расположения в другое -// +// // Примечание: // Метод в документации API: [disk.file.copyto](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_copyto.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDФайла - Строка, Число - ID файла для копирования - fileid -// IDКаталога - Строка, Число - ID каталога размещения копии - folderid +// IDКаталога - Строка, Число - ID каталога размещения копии - folderid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция СкопироватьФайл(Знач URL, Знач IDФайла, Знач IDКаталога, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.file.copyto"); - + OPI_Инструменты.ДобавитьПоле("id" , IDФайла , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("targetFolderId", IDКаталога, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции // Переместить файл // Перемещает файл из одного расположения в другое -// +// // Примечание: // Метод в документации API: [disk.file.moveto](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_moveto.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDФайла - Строка, Число - ID файла для перемещения - fileid -// IDКаталога - Строка, Число - ID каталога нового размещения - folderid +// IDКаталога - Строка, Число - ID каталога нового размещения - folderid // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПереместитьФайлВКаталог(Знач URL, Знач IDФайла, Знач IDКаталога, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.file.moveto"); - + OPI_Инструменты.ДобавитьПоле("id" , IDФайла , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("targetFolderId", IDКаталога, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции // Переименовать файл // Изменяет имя существующего файла -// +// // Примечание: // Метод в документации API: [disk.file.rename](@dev.1c-bitrix.ru/rest_help/disk/file/disk_file_rename.php) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDФайла - Строка, Число - Идентификатор файла - fileid // Наименование - Строка - Новое наименование каталога - title // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПереименоватьФайл(Знач URL, Знач IDФайла, Знач Наименование, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "disk.file.rename"); - + OPI_Инструменты.ДобавитьПоле("id" , IDФайла , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("newName", Наименование, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции #КонецОбласти @@ -2540,109 +2540,109 @@ // Создать чат // Создает новый чат на основе структуры полей -// +// // Примечание: // Метод в документации API: [im.chat.add](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12093) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url -// СтруктураЧата - Структура Из КлючИЗначение - Структура полей чата. См. ПолучитьСтруктуруЧата - fields +// СтруктураЧата - Структура Из КлючИЗначение - Структура полей чата. См. ПолучитьСтруктуруЧата - fields // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция СоздатьЧат(Знач URL, Знач СтруктураЧата, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.chat.add"); - + Для Каждого Элемент Из СтруктураЧата Цикл Параметры.Вставить(Элемент.Ключ, Элемент.Значение); КонецЦикла; - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить список пользователей чата // Получает список пользователей чата по ID -// +// // Примечание: // Метод в документации API: [im.chat.user.list](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12095) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата - chat // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьСписокПользователейЧата(Знач URL, Знач IDЧата, Знач Токен = "") Экспорт - - Ответ = УправлениеЧатом(URL, IDЧата, "im.chat.user.list", Токен); + + Ответ = УправлениеЧатом(URL, IDЧата, "im.chat.user.list", Токен); Возврат Ответ; - + КонецФункции // Покинуть чат // Исключает текущего пользователя из чата -// +// // Примечание: // Метод в документации API: [im.chat.leave](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12101) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата - chat // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПокинутьЧат(Знач URL, Знач IDЧата, Знач Токен = "") Экспорт - - Ответ = УправлениеЧатом(URL, IDЧата, "im.chat.leave", Токен); + + Ответ = УправлениеЧатом(URL, IDЧата, "im.chat.leave", Токен); Возврат Ответ; - + КонецФункции // Получить пользователей // Получает информацию о пользователях для диалога -// +// // Примечание: // Метод в документации API: [im.user.list.get ](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=11493) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDПользователей - Массив Из Строка, Число - ID пользователя или нескольких пользователей - users // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьПользователей(Знач URL, Знач IDПользователей, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.user.list.get"); - + OPI_Инструменты.ДобавитьПоле("ID", IDПользователей, "Массив", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Добавить пользователей в чат // Добавляет пользователей в чат по массиву ID -// +// // Примечание: // Метод в документации API: [im.chat.user.add](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12097) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата - chat // IDПользователей - Массив из Строка, Число - ID пользователей для добавления - users // СкрытьИсторию - Булево - Скрыть старые сообщения от новых пользователей - hide // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ДобавитьПользователейВЧат(Знач URL @@ -2650,213 +2650,213 @@ , Знач IDПользователей , Знач СкрытьИсторию = Ложь , Знач Токен = "") Экспорт - + ПривестиБулево(СкрытьИсторию); - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.chat.user.add"); - + OPI_Инструменты.ДобавитьПоле("CHAT_ID" , IDЧата , "Строка" , Параметры); OPI_Инструменты.ДобавитьПоле("USERS" , IDПользователей, "Коллекция", Параметры); OPI_Инструменты.ДобавитьПоле("HIDE_HISTORY", СкрытьИсторию , "Строка" , Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Исключить пользователя из чата // Исключает выбранного пользователя из чата -// +// // Примечание: // Метод в документации API: [im.chat.user.delete](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12099) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата - chat // IDПользователя - Строка, Число - ID пользователя - user // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ИсключитьПользователяИзЧата(Знач URL, Знач IDЧата, Знач IDПользователя, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.chat.user.delete"); - + OPI_Инструменты.ДобавитьПоле("CHAT_ID", IDЧата , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("USER_ID", IDПользователя, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Изменить заголовок чата // Изменяет текст заголовка чата -// +// // Примечание: // Метод в документации API: [im.chat.updateTitle](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12105) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата - chat // Заголовок - Строка - Новый текст заголовка - title // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ИзменитьЗаголовокЧата(Знач URL, Знач IDЧата, Знач Заголовок, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.chat.updateTitle"); - + OPI_Инструменты.ДобавитьПоле("CHAT_ID", IDЧата , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("TITLE" , Заголовок, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Изменить цвет чата // Изменяет цвет чата для мобильного приложения -// +// // Примечание: // Метод в документации API: [im.chat.updateTitle](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12105) // Доступные цвета: RED, GREEN, MINT, LIGHT_BLUE, DARK_BLUE, PURPLE, AQUA, PINK, LIME, BROWN, AZURE, KHAKI, SAND, MARENGO, GRAY, GRAPHITE -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата - chat // Цвет - Строка - Новый цвет чата - color // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ИзменитьЦветЧата(Знач URL, Знач IDЧата, Знач Цвет, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.chat.updateColor"); - + OPI_Инструменты.ДобавитьПоле("CHAT_ID", IDЧата, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("COLOR" , Цвет , "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Изменить картинку чата // Устанавливает новую картинку чата -// +// // Примечание: // Метод в документации API: [im.chat.updateAvatar](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12109) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата - chat // Картинка - Строка, ДвоичныеДанные - Данные файла картинки - picture // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ИзменитьКартинкуЧата(Знач URL, Знач IDЧата, Знач Картинка, Знач Токен = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Картинка); - + Картинка = Base64Строка(Картинка); Параметры = НормализоватьАвторизацию(URL, Токен, "im.chat.updateAvatar"); - + OPI_Инструменты.ДобавитьПоле("CHAT_ID", IDЧата , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("AVATAR" , Картинка, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Сменить владельца чата // Изменяет пользователя владельца чата -// +// // Примечание: // Метод в документации API: [im.chat.setOwner](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12111) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата - chat // IDПользователя - Строка, Число - ID пользователя - user // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция СменитьВладельцаЧата(Знач URL, Знач IDЧата, Знач IDПользователя, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.chat.setOwner"); - + OPI_Инструменты.ДобавитьПоле("CHAT_ID", IDЧата , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("USER_ID", IDПользователя, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Отключить уведомления чата // Отключает уведомлений чата -// +// // Примечание: // Метод в документации API: [im.chat.mute](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=11473) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата - chat // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ОтключитьУведомленияЧата(Знач URL, Знач IDЧата, Знач Токен = "") Экспорт - + Ответ = УправлениеЗвукомЧата(URL, IDЧата, Истина, Токен); Возврат Ответ; - + КонецФункции // Включить уведомления чата // Включает уведомления в чате -// +// // Примечание: // Метод в документации API: [im.chat.mute](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=11473) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата - chat // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ВключитьУведомленияЧата(Знач URL, Знач IDЧата, Знач Токен = "") Экспорт - + Ответ = УправлениеЗвукомЧата(URL, IDЧата, Ложь, Токен); Возврат Ответ; - + КонецФункции // Получить список сообщений чата // Получает список из 20 сообщений чата или диалога, в зависимости от указания IDПервого и IDПоследнего -// +// // Примечание: // Метод в документации API: [im.dialog.messages.get](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=11479) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата (chatXXX) или пользователя (XXX) для диалога - chat // IDПоследнего - Строка, Число - ID последнего загруженного сообщения - last // IDПервого - Строка, Число - ID первого загруженного сообщения - first // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьСписокСообщенийЧата(Знач URL @@ -2864,199 +2864,199 @@ , Знач IDПоследнего = "" , Знач IDПервого = "" , Знач Токен = "") Экспорт - + Строка_ = "Строка"; - + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDПоследнего); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDПервого); - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.dialog.messages.get"); - + OPI_Инструменты.ДобавитьПоле("DIALOG_ID", IDЧата , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("LAST_ID" , IDПоследнего, Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("FIRST_ID" , IDПервого , Строка_, Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить диалог // Получает информацию о диалоге по ID -// +// // Примечание: // Метод в документации API: [im.dialog.get](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12886) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата (chatXXX) или пользователя (XXX) для диалога - chat // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьДиалог(Знач URL, Знач IDЧата, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.dialog.get"); - + OPI_Инструменты.ДобавитьПоле("DIALOG_ID", IDЧата, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить список пользователей диалога // Получает список участников далога -// +// // Примечание: // Метод в документации API: [im.dialog.users.list](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=23800) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата (chatXXX) или пользователя (XXX) для диалога - chat // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьСписокПользователейДиалога(Знач URL, Знач IDЧата, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.dialog.users.list"); - + OPI_Инструменты.ДобавитьПоле("DIALOG_ID", IDЧата, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Отправить уведомление о вводе // Отправляет в чат статус Вам пишут... -// +// // Примечание: // Метод в документации API: [im.dialog.writing](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=23802) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата (chatXXX) или пользователя (XXX) для диалога - chat // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ОтправитьУведомлениеОВводе(Знач URL, Знач IDЧата, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.dialog.writing"); - + OPI_Инструменты.ДобавитьПоле("DIALOG_ID", IDЧата, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить статус пользователя // Получает статус (онлайн) текущего пользователя -// +// // Примечание: // Метод в документации API: [im.user.status.get](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=11497) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьСтатусПользователя(Знач URL, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.user.status.get"); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Установить статус пользователя // Устанавливает статус (онлайн) текущего пользователя -// +// // Примечание: // Метод в документации API: [im.user.status.set](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=11499) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Статус - Строка, Число - Статус пользователя: online, dnd, away - status // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УстановитьСтатусПользователя(Знач URL, Знач Статус, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.user.status.set"); - + OPI_Инструменты.ДобавитьПоле("STATUS", Статус, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Прочитать все // Отмечает все сообщения во всех доступных чатах как прочитанные -// +// // Примечание: // Метод в документации API: [im.dialog.read.all](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=23804) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПрочитатьВсе(Знач URL, Знач Токен = "") Экспорт - - Параметры = НормализоватьАвторизацию(URL, Токен, "im.dialog.read.all"); + + Параметры = НормализоватьАвторизацию(URL, Токен, "im.dialog.read.all"); Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Получить каталог файлов чата // Получает каталог для хранения фйлов чата -// +// // Примечание: // Метод в документации API: [im.disk.folder.get](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=11483) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата - chat // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ПолучитьКаталогФайловЧата(Знач URL, Знач IDЧата, Знач Токен = "") Экспорт - - Ответ = УправлениеЧатом(URL, IDЧата, "im.disk.folder.get", Токен); + + Ответ = УправлениеЧатом(URL, IDЧата, "im.disk.folder.get", Токен); Возврат Ответ; - + КонецФункции // Получить структуру чата // Получает структуру полей чата -// +// // Параметры: // Пустая - Булево - Истина > структура с пустыми значениями, Ложь > в значениях будут описания типов полей - empty -// +// // Возвращаемое значение: -// Структура Из КлючИЗначение - Структура полей +// Структура Из КлючИЗначение - Структура полей Функция ПолучитьСтруктуруЧата(Знач Пустая = Ложь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьБулево(Пустая); - + СтруктураЧата = Новый Структура; СтруктураЧата.Вставить("TYPE" , "<Тип чата OPEN (публичный) | CHAT (по приглашениям)>"); СтруктураЧата.Вставить("TITLE" , "<Заголовок чата>"); @@ -3066,7 +3066,7 @@ СтруктураЧата.Вставить("USERS" , "<Массив участников чата>"); СтруктураЧата.Вставить("AVATAR" , "<Аватар чата в base64 формате>"); СтруктураЧата.Вставить("OWNER_ID" , "<Идентификатор владельца чата. Текущий пользователь, если не указано>"); - + Если Пустая Тогда Для Каждого Элемент Из СтруктураЧата Цикл Элемент.Значение = ""; @@ -3075,7 +3075,7 @@ //@skip-check constructor-function-return-section Возврат СтруктураЧата; - + КонецФункции #КонецОбласти @@ -3084,253 +3084,253 @@ // Отправить сообщение // Отправляет сообщение в диалог -// +// // Примечание: // Метод в документации API: [im.message.add](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12115) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата (chatXXX) или пользователя (XXX) для диалога - chat // Текст - Строка - Текст сообщения - text // Вложения - Массив из Структура - Массив блоков вложений - blocks // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ОтправитьСообщение(Знач URL, Знач IDЧата, Знач Текст, Знач Вложения = "", Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.message.add"); - + OPI_Инструменты.ДобавитьПоле("DIALOG_ID", IDЧата , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("MESSAGE" , Текст , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("ATTACH" , Вложения, "Массив", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Изменить сообщение // Изменяет сообщение в диалоге -// +// // Примечание: // Метод в документации API: [im.message.update](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12117) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDСообщения - Строка, Число - ID сообщения для изменения - message // Текст - Строка - Новый текст сообщения - text // Вложения - Массив из Структура - Новый массив блоков вложений - blocks // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ИзменитьСообщение(Знач URL, Знач IDСообщения, Знач Текст = "", Знач Вложения = "", Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.message.update"); - + OPI_Инструменты.ДобавитьПоле("MESSAGE_ID", IDСообщения, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("MESSAGE" , Текст , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("ATTACH" , Вложения , "Массив", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Установить реакцию на сообщение // Устанавливает или снимает реакцию на сообщение -// +// // Примечание: // Метод в документации API: [im.message.like](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12121) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDСообщения - Строка, Число - ID сообщения - message // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УстановитьРеакциюНаСообщение(Знач URL, Знач IDСообщения, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.message.like"); - + OPI_Инструменты.ДобавитьПоле("MESSAGE_ID", IDСообщения, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Удалить сообщение // Удаляет сообщение в диалоге -// +// // Примечание: // Метод в документации API: [im.message.delete](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12119) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDСообщения - Строка, Число - ID сообщения для удаления - message // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УдалитьСообщение(Знач URL, Знач IDСообщения, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.message.delete"); - + OPI_Инструменты.ДобавитьПоле("MESSAGE_ID", IDСообщения , "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Отправить файл // Отправляет файл диска в чат по ID -// +// // Примечание: // Метод в документации API: [im.disk.file.commit](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=11485) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата - chat // IDФайла - Строка, Число - ID файла, загруженного при помощи ЗагрузитьФайлВКаталог - fileid // Описание - Строка - Описание файла - description // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ОтправитьФайл(Знач URL, Знач IDЧата, Знач IDФайла, Знач Описание = "", Знач Токен = "") Экспорт - + Строка_ = "Строка"; - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.disk.file.commit"); - + OPI_Инструменты.ДобавитьПоле("CHAT_ID" , IDЧата , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("UPLOAD_ID", IDФайла , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("MESSAGE" , Описание, Строка_, Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Отметить сообщение как прочитанное // Отмечает выбранное сообщение и все сообщения до него как прочитанные -// +// // Примечание: // Метод в документации API: [im.dialog.read](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12053) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата (chatXXX) или пользователя (XXX) для диалога - chat // IDСообщения - Строка, Число - ID последнего прочитанного сообщения - message // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ОтметитьСообщениеКакПрочитанное(Знач URL, Знач IDЧата, Знач IDСообщения, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.dialog.read"); - + OPI_Инструменты.ДобавитьПоле("DIALOG_ID" , IDЧата , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("MESSAGE_ID", IDСообщения, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Отметить сообщение как непрочитанное // Отмечает выбранное сообщение и все сообщения после него как непрочитанные -// +// // Примечание: // Метод в документации API: [im.dialog.unread](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&LESSON_ID=12055) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDЧата - Строка, Число - ID чата (chatXXX) или пользователя (XXX) для диалога - chat // IDСообщения - Строка, Число - ID послднего непрочитанного сообщения - message // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция ОтметитьСообщениеКакНепрочитанное(Знач URL, Знач IDЧата, Знач IDСообщения, Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.dialog.unread"); - + OPI_Инструменты.ДобавитьПоле("DIALOG_ID" , IDЧата , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("MESSAGE_ID", IDСообщения, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции - + // Получить блок картинки // Формирует картинку для отправки в функции ОтправитьСообщение -// +// // Примечание: // Блоки в документации API: [Ссылка](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&CHAPTER_ID=07867) -// +// // Параметры: // Наименование - Строка - Наименование картинки - title // URL - Строка - URL картинки для отправки - url -// +// // Возвращаемое значение: // Структура - Блок с картинкой Функция ПолучитьБлокКартинки(Знач Наименование, Знач URL) Экспорт - СтруктураКартинки = Новый Структура; + СтруктураКартинки = Новый Структура; OPI_Инструменты.ДобавитьПоле("NAME", Наименование, "Строка", СтруктураКартинки); OPI_Инструменты.ДобавитьПоле("LINK", URL , "Строка", СтруктураКартинки); - + //@skip-check constructor-function-return-section Возврат Новый Структура("IMAGE", СтруктураКартинки); - + КонецФункции // Получить блок файла // Формирует блок файла для отправки в функции ОтправитьСообщение -// +// // Примечание: // Блоки в документации API: [Ссылка](@dev.1c-bitrix.ru/learning/course/?COURSE_ID=93&CHAPTER_ID=07867) -// +// // Параметры: // Наименование - Строка - Наименование картинки - title // URL - Строка - URL файла для отправки - url -// +// // Возвращаемое значение: // Структура - Блок с файлом Функция ПолучитьБлокФайла(Знач Наименование, Знач URL) Экспорт - СтруктураКартинки = Новый Структура; + СтруктураКартинки = Новый Структура; OPI_Инструменты.ДобавитьПоле("NAME", Наименование, "Строка", СтруктураКартинки); OPI_Инструменты.ДобавитьПоле("LINK", URL , "Строка", СтруктураКартинки); - + //@skip-check constructor-function-return-section Возврат Новый Структура("FILE", СтруктураКартинки); - + КонецФункции - + #КонецОбласти #Область РаботаСУведомлениями // Создать персональное уведомление // Создает персональное уведомление пользователю -// +// // Примечание: // Метод в документации API: [im.notify.personal.add](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=12129) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDПользователя - Строка, Число - ID пользователя для отправки уведомления - user @@ -3338,7 +3338,7 @@ // Тег - Строка - Тег уникальности Если уже существет - другие увед. будут удалены - tag // Вложения - Массив из Структура - Массив блоков вложений - blocks // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция СоздатьПерсональноеУведомление(Знач URL @@ -3347,26 +3347,26 @@ , Знач Тег , Знач Вложения = "" , Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.notify.personal.add"); - + OPI_Инструменты.ДобавитьПоле("USER_ID", IDПользователя, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("MESSAGE", Текст , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("TAG" , Тег , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("ATTACH" , Вложения , "Массив", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Создать системное уведомление // Создает системное уведомление пользователю -// +// // Примечание: // Метод в документации API: [im.notify.system.add](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=12131) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDПользователя - Строка, Число - ID пользователя для отправки уведомления - user @@ -3374,7 +3374,7 @@ // Тег - Строка - Тег уникальности Если уже существет - другие увед. будут удалены - tag // Вложения - Массив из Структура - Массив блоков вложений - blocks // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция СоздатьСистемноеУведомление(Знач URL @@ -3383,43 +3383,43 @@ , Знач Тег , Знач Вложения = "" , Знач Токен = "") Экспорт - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.notify.system.add"); - + OPI_Инструменты.ДобавитьПоле("USER_ID", IDПользователя, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("MESSAGE", Текст , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("TAG" , Тег , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("ATTACH" , Вложения , "Массив", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции // Удалить уведомление // Удаляет уведомление по ID -// +// // Примечание: // Метод в документации API: [im.notify.delete](@dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=93&LESSON_ID=12133) -// +// // Параметры: // URL - Строка - URL внешнего вебхука или адрес Bitrix24 при использовании токена - url // IDУведомления - Строка, Число - ID уведомления для удаления - notif // Токен - Строка - Токен авторизации, если используется не вебхук - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Bitrxi24 Функция УдалитьУведомление(Знач URL, Знач IDУведомления, Знач Токен = "") Экспорт Параметры = НормализоватьАвторизацию(URL, Токен, "im.notify.delete"); - + OPI_Инструменты.ДобавитьПоле("ID", IDУведомления, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -3432,137 +3432,137 @@ OPI_ПреобразованиеТипов.ПолучитьБулево(Значение); Значение = ?(Значение, "Y", "N"); - + КонецПроцедуры Функция НормализоватьАвторизацию(URL, Знач Токен, Знач Метод = "") - + OPI_ПреобразованиеТипов.ПолучитьСтроку(URL); OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Параметры = Новый Структура; ЭтоАвторизацияТокеном = ЗначениеЗаполнено(Токен); - + МассивЛишнихЭлементов = Новый Массив; МассивЛишнихЭлементов.Добавить("https://"); МассивЛишнихЭлементов.Добавить("http://"); МассивЛишнихЭлементов.Добавить("www."); - + Для Каждого УдаляемыйЭлемент Из МассивЛишнихЭлементов Цикл URL = СтрЗаменить(URL, УдаляемыйЭлемент, ""); КонецЦикла; - + URL = СокрЛП(URL); - + Если Не СтрЗаканчиваетсяНа(URL, "/") Тогда URL = URL + "/"; КонецЕсли; - + Если ЭтоАвторизацияТокеном Тогда - + Если Не СтрЗаканчиваетсяНа(URL, "rest/") Тогда URL = URL + "rest/"; КонецЕсли; - + Параметры.Вставить("auth", Токен); - + КонецЕсли; - + Если ЗначениеЗаполнено(Метод) Тогда URL = URL + СокрЛП(Метод); КонецЕсли; - + Возврат Параметры; КонецФункции Функция НормализоватьФайлы(Знач Файлы) - + НормализованныеФайлы = Новый Массив; Если ТипЗнч(Файлы) = Тип("Соответствие") Тогда - - Для Каждого Файл Из Файлы Цикл - + + Для Каждого Файл Из Файлы Цикл + ТекущийМассив = Новый Массив; ТекущийФайл = Файл.Значение; ТекущееИмя = Файл.Ключ; - + OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(ТекущийФайл); OPI_ПреобразованиеТипов.ПолучитьСтроку(ТекущееИмя); - + ТекущийМассив.Добавить(ТекущееИмя); ТекущийМассив.Добавить(Base64Строка(ТекущийФайл)); - + НормализованныеФайлы.Добавить(ТекущийМассив); - + КонецЦикла; - + КонецЕсли; - + Возврат НормализованныеФайлы; - + КонецФункции Функция УправлениеЗадачей(Знач URL, Знач IDЗадачи, Знач Метод, Знач Токен = "") - + Параметры = НормализоватьАвторизацию(URL, Токен, Метод); OPI_Инструменты.ДобавитьПоле("taskId", IDЗадачи, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции Функция УправлениеФайлом(Знач URL, Знач IDФайла, Знач Метод, Знач Токен = "") Параметры = НормализоватьАвторизацию(URL, Токен, Метод); OPI_Инструменты.ДобавитьПоле("id", IDФайла, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции -Функция УправлениеЭлементомЧеклиста(Знач URL, Знач IDЗадачи, Знач IDЭлемента, Знач Метод, Знач Токен = "") - +Функция УправлениеЭлементомЧеклиста(Знач URL, Знач IDЗадачи, Знач IDЭлемента, Знач Метод, Знач Токен = "") + Параметры = НормализоватьАвторизацию(URL, Токен, Метод); - + OPI_Инструменты.ДобавитьПоле("TASKID", IDЗадачи , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("ITEMID", IDЭлемента, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - + Возврат Ответ; - + КонецФункции Функция УправлениеЧатом(Знач URL, Знач IDЧата, Знач Метод, Знач Токен = "") Параметры = НормализоватьАвторизацию(URL, Токен, Метод); OPI_Инструменты.ДобавитьПоле("CHAT_ID", IDЧата, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции Функция УправлениеЗвукомЧата(Знач URL, Знач IDЧата, Знач Выключить, Знач Токен = "") ПривестиБулево(Выключить); - + Параметры = НормализоватьАвторизацию(URL, Токен, "im.chat.mute"); - + OPI_Инструменты.ДобавитьПоле("CHAT_ID", IDЧата , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("MUTE" , Выключить, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции #КонецОбласти diff --git a/src/ru/OPI/src/CommonModules/OPI_Dropbox/Module.bsl b/src/ru/OPI/src/CommonModules/OPI_Dropbox/Module.bsl index 564b14d8d3..bc8ebdf2ce 100644 --- a/src/ru/OPI/src/CommonModules/OPI_Dropbox/Module.bsl +++ b/src/ru/OPI/src/CommonModules/OPI_Dropbox/Module.bsl @@ -1,4 +1,4 @@ -// OneScript: ./OInt/core/Modules/OPI_Dropbox.os +// OneScript: ./OInt/core/Modules/OPI_Dropbox.os // Lib: Dropbox // CLI: dropbox @@ -42,44 +42,44 @@ // Получить ссылку авторизации // Генерирует ссылку авторизации для перехода в браузере -// +// // Параметры: // КлючПриложения - Строка - Ключ приложения - appkey -// +// // Возвращаемое значение: // Строка - URL для перехода в браузере Функция ПолучитьСсылкуАвторизации(Знач КлючПриложения) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(КлючПриложения); - Возврат "https://www.dropbox.com/oauth2/authorize?client_id=" - + КлючПриложения + Возврат "https://www.dropbox.com/oauth2/authorize?client_id=" + + КлючПриложения + "&response_type=code&token_access_type=offline"; - + КонецФункции // Получить токен // Полеучает токен на основе кода со страницы ПолучитьСсылкуАвторизации -// +// // Параметры: // КлючПриложения - Строка - Ключ приложения - appkey // СекретПриложения - Строка - Секрет приложения - appsecret // Код - Строка - Код со страницы авторизации - code -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ПолучитьТокен(Знач КлючПриложения, Знач СекретПриложения, Знач Код) Экспорт - + URL = "https://api.dropbox.com/oauth2/token"; ТипДанных = "application/x-www-form-urlencoded; charset=utf-8"; - - Параметры = Новый Структура; + + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("code" , Код , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("grant_type", "authorization_code", "Строка", Параметры); - + СтруктураURL = OPI_Инструменты.РазбитьURL(URL); Сервер = СтруктураURL["Сервер"]; Адрес = СтруктураURL["Адрес"]; - + Запрос = OPI_Инструменты.СоздатьЗапрос(Адрес, , ТипДанных); Соединение = OPI_Инструменты.СоздатьСоединение(Сервер, КлючПриложения, СекретПриложения); @@ -87,83 +87,83 @@ Данные = Прав(СтрокаПараметров, СтрДлина(СтрокаПараметров) - 1); Запрос.УстановитьТелоИзСтроки(Данные); - + Ответ = Соединение.ВызватьHTTPМетод("POST", Запрос); OPI_Инструменты.ОбработатьОтвет(Ответ); - + Возврат Ответ; - + КонецФункции // Обновить токен // Получает новый токен на основе рефреш токена -// +// // Параметры: // КлючПриложения - Строка - Ключ приложения - appkey // СекретПриложения - Строка - Секрет приложения - appsecret // РефрешТокен - Строка - Рефреш токен - refresh -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ОбновитьТокен(Знач КлючПриложения, Знач СекретПриложения, Знач РефрешТокен) Экспорт - + Строка_ = "Строка"; URL = "https://api.dropbox.com/oauth2/token"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("refresh_token", РефрешТокен , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("grant_type" , "refresh_token" , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("client_id" , КлючПриложения , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("client_secret", СекретПриложения, Строка_, Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры, , Ложь); - + Возврат Ответ; - + КонецФункции // Получить информацию об аккаунте // Получает информацию об аккаунте -// +// // Параметры: // Токен - Строка - Токен - token // Аккаунт - Строка - ID аккаунта. Текущий аккаунт токена, если не заполнено - account -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ПолучитьИнформациюОбАккаунте(Знач Токен, Знач Аккаунт = "") Экспорт - + Если ЗначениеЗаполнено(Аккаунт) Тогда Результат = ПолучитьАккаунт(Токен, Аккаунт); Иначе Результат = ПолучитьСвойАккаунт(Токен); КонецЕсли; - + Возврат Результат; - + КонецФункции // Получить данные использования пространства // Получает информацию о количестве использованного дискового пространства -// +// // Параметры: -// Токен - Строка - Токен - token -// +// Токен - Строка - Токен - token +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ПолучитьДанныеИспользованияПространства(Знач Токен) Экспорт - + URL = "https://api.dropboxapi.com/2/users/get_space_usage"; Заголовки = ПолучитьЗаголовкиЗапроса(Токен); - + Ответ = OPI_Инструменты.PostBinary(URL , ПолучитьДвоичныеДанныеИзСтроки("null") , Заголовки - , - , "text/plain; charset=dropbox-cors-hack"); - + , + , "text/plain; charset=dropbox-cors-hack"); + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -172,344 +172,344 @@ // Получить информацию об объекте // Получает информацию о файле или каталоге -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к объекту - path -// Подробно - Булево - Добавляет дополнительные поля информации для медиафайлов - detail -// +// Подробно - Булево - Добавляет дополнительные поля информации для медиафайлов - detail +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ПолучитьИнформациюОбОбъекте(Знач Токен, Знач Путь, Знач Подробно = Ложь) Экспорт - - URL = "https://api.dropboxapi.com/2/files/get_metadata"; - + + URL = "https://api.dropboxapi.com/2/files/get_metadata"; + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("path" , Путь , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("include_media_info", Подробно, "Булево", Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить список файлов папки // Получает список первых файлов каталога или продолжает получение следующих при указании курсора -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к каталогу. Необязателен, если указан курсор - path // Подробно - Булево - Добавляет дополнительные поля информации для медиафайлов - detail // Курсор - Строка - Курсор из предыдущего запроса для получения следующего набора файлов - cursor -// +// // Возвращаемое значение: // HTTPОтвет - Получить список файлов папки Функция ПолучитьСписокФайловПапки(Знач Токен, Знач Путь = "", Знач Подробно = Ложь, Знач Курсор = "") Экспорт - + Если Не ЗначениеЗаполнено(Курсор) Тогда - + URL = "https://api.dropboxapi.com/2/files/list_folder"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("path" , Путь , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("include_media_info", Подробно , "Булево", Параметры); - + Иначе - + URL = "https://api.dropboxapi.com/2/files/list_folder/continue"; - + Параметры = Новый Структура; - OPI_Инструменты.ДобавитьПоле("cursor", Курсор, "Строка", Параметры); - + OPI_Инструменты.ДобавитьПоле("cursor", Курсор, "Строка", Параметры); + КонецЕсли; - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить превью // Получает PDF или HTML превью объекта (только для токументов) -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к объекту - path -// +// // Возвращаемое значение: -// ДвоичныеДанные - превью документа +// ДвоичныеДанные - превью документа Функция ПолучитьПревью(Знач Токен, Знач Путь) Экспорт - + URL = "https://content.dropboxapi.com/2/files/get_preview"; Ответ = ОбработатьОбъект(Токен, URL, Путь, Истина); - + Возврат Ответ; - + КонецФункции // Загрузить файл // Загружает файл на облачный диск -// +// // Параметры: // Токен - Строка - Токен - token // Файл - Строка, ДвоичныеДанные - Данные файл для загрузки - file // Путь - Строка - Путь сохранения на Dropbox - path // Перезаписывать - Булево - Перезаписывать файл при конфликте путей - overwrite -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ЗагрузитьФайл(Знач Токен, Знач Файл, Знач Путь, Знач Перезаписывать = Ложь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Файл); OPI_ПреобразованиеТипов.ПолучитьБулево(Перезаписывать); OPI_ПреобразованиеТипов.ПолучитьСтроку(Путь); - + Режим = ?(Перезаписывать, "overwrite", "add"); Размер = Файл.Размер(); Граница = 100000000; - + Если Размер > Граница Тогда Ответ = ЗагрузитьБольшойФайл(Токен, Файл, Путь, Режим); Иначе Ответ = ЗагрузитьМалыйФайл(Токен, Файл, Путь, Режим); КонецЕсли; - + Возврат Ответ; - + КонецФункции // Загрузить файл по URL -// Загружает файл на облачный диск, получая его по указанному URL -// +// Загружает файл на облачный диск, получая его по указанному URL +// // Параметры: // Токен - Строка - Токен - token // URLФайла - Строка - URL источник файла - url // Путь - Строка - Путь сохранения на Dropbox - path -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ЗагрузитьФайлПоURL(Знач Токен, Знач URLФайла, Знач Путь) Экспорт - - URL = "https://api.dropboxapi.com/2/files/save_url"; - + + URL = "https://api.dropboxapi.com/2/files/save_url"; + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("path", Путь , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("url" , URLФайла , "Строка", Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить статус загрузки по URL // Получает статус загрузки файла по URL -// +// // Параметры: // Токен - Строка - Токен - token -// IDРаботы - Строка - ID асинхронной работы из ответа ЗагрузитьФайлПоURL - job -// +// IDРаботы - Строка - ID асинхронной работы из ответа ЗагрузитьФайлПоURL - job +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ПолучитьСтатусЗагрузкиПоURL(Знач Токен, Знач IDРаботы) Экспорт - - URL = "https://api.dropboxapi.com/2/files/save_url/check_job_status"; - + + URL = "https://api.dropboxapi.com/2/files/save_url/check_job_status"; + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("async_job_id", IDРаботы, "Строка", Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Удалить объект // Удаляет объект с облачного диска -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к объекту удаления - path // БезВозвратно - Строка - Удалить объект без возможности востановления - permanently -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция УдалитьОбъект(Знач Токен, Знач Путь, Знач Безвозвратно = Ложь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьБулево(Безвозвратно); - + Если Безвозвратно Тогда URL = "https://api.dropboxapi.com/2/files/permanently_delete"; Иначе URL = "https://api.dropboxapi.com/2/files/delete_v2"; КонецЕсли; - + Ответ = ОбработатьОбъект(Токен, URL, Путь); - + Возврат Ответ; КонецФункции // Копировать объект // Копирует файл или каталог по выбранному пути -// +// // Параметры: // Токен - Строка - Токен - token // Откуда - Строка - Путь к объекту оригинала - form // Куда - Строка - Целевой путь для нового объекта - to -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция КопироватьОбъект(Знач Токен, Знач Откуда, Знач Куда) Экспорт - + URL = "https://api.dropboxapi.com/2/files/copy_v2"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("from_path", Откуда, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("to_path" , Куда , "Строка", Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Переместить объект // Перемещает объект по выбранному пути -// +// // Параметры: // Токен - Строка - Токен - token // Откуда - Строка - Путь к объекту оригинала - form // Куда - Строка - Целевой путь для нового объекта - to -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ПереместитьОбъект(Знач Токен, Знач Откуда, Знач Куда) Экспорт URL = "https://api.dropboxapi.com/2/files/move_v2"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("from_path", Откуда, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("to_path" , Куда , "Строка", Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Создать папку // Создает пустой каталог по выбранному пути -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Целевой путь создания каталога - path -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция СоздатьПапку(Знач Токен, Знач Путь) Экспорт - + URL = "https://api.dropboxapi.com/2/files/create_folder_v2"; Ответ = ОбработатьОбъект(Токен, URL, Путь); - + Возврат Ответ; - + КонецФункции // Скачать файл // Скачивает файл по указанному пути или ID -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь или ID файла - path -// +// // Возвращаемое значение: // ДвоичныеДанные - двоичные данные файла Функция СкачатьФайл(Знач Токен, Знач Путь) Экспорт - + URL = "https://content.dropboxapi.com/2/files/download"; Ответ = ОбработатьОбъект(Токен, URL, Путь, Истина); - + Возврат Ответ; - + КонецФункции // Скачать папку // Скачивает zip архив с содержимым указанного каталога -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь или ID каталога - path -// +// // Возвращаемое значение: // ДвоичныеДанные - двоичные данные zip архива с содержимым каталога Функция СкачатьПапку(Знач Токен, Знач Путь) Экспорт - + URL = "https://content.dropboxapi.com/2/files/download_zip"; Ответ = ОбработатьОбъект(Токен, URL, Путь, Истина); - + Возврат Ответ; - + КонецФункции // Получить список версий объекта // Получает список версий (ревизий) объекта -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к объекту - path // Количество - Строка, Число - Число последних версий объекта для отображения - amount -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ПолучитьСписокВерсийОбъекта(Знач Токен, Знач Путь, Знач Количество = 10) Экспорт - - URL = "https://api.dropboxapi.com/2/files/list_revisions"; - + + URL = "https://api.dropboxapi.com/2/files/list_revisions"; + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("path" , Путь , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("limit", Количество, "Число" , Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Восстановить объект к версии // Восстанавливает состояние объекта к необходимой версии (ревизии) -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к объекту - path // Версия - Строка - ID версии (ревизии) для востановления - rev -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ВосстановитьОбъектКВерсии(Знач Токен, Знач Путь, Знач Версия) Экспорт - - URL = "https://api.dropboxapi.com/2/files/restore"; - + + URL = "https://api.dropboxapi.com/2/files/restore"; + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("path", Путь , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("rev" , Версия, "Строка", Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -518,58 +518,58 @@ // Получить список тегов // Получает список тегов выбранных файлов -// +// // Параметры: // Токен - Строка - Токен - token // Пути - Строка, Массив Из Строка - Путь или набору путей к файлам - paths -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ПолучитьСписокТегов(Знач Токен, Знач Пути) Экспорт - + URL = "https://api.dropboxapi.com/2/files/tags/get"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("paths", Пути, "Массив", Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Добавить тег // Добавляет новый текстовый тег к файлу или каталогу -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к объекту, для которого необходимо создать тег - path // Тег - Строка - Текст тега - tag -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ДобавитьТег(Знач Токен, Знач Путь, Знач Тег) Экспорт - + Возврат ОбработатьТег(Токен, Путь, Тег); - + КонецФункции // Удалить тег // Удаляет текстовый тег файла или каталога -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к объекту, тег которого необходимо удалить - path // Тег - Строка - Текст тега - tag -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция УдалитьТег(Знач Токен, Знач Путь, Знач Тег) Экспорт - + Возврат ОбработатьТег(Токен, Путь, Тег, Истина); - + КонецФункции #КонецОбласти @@ -578,38 +578,38 @@ // Опубликовать папку // Переводит каталог в режим публичного доступа -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к целевому каталогу - path -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ОпубликоватьПапку(Знач Токен, Знач Путь) Экспорт - + URL = "https://api.dropboxapi.com/2/sharing/share_folder"; Ответ = ОбработатьОбъект(Токен, URL, Путь); - + Возврат Ответ; - + КонецФункции // Отменить публикацию папки // Отменяет режим общего доступа для каталога -// +// // Параметры: // Токен - Строка - Токен - token // IDПапки - Строка - ID публичного каталога (shared folder ID) - folder -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ОтменитьПубликациюПапки(Знач Токен, Знач IDПапки) Экспорт - + URL = "https://api.dropboxapi.com/2/sharing/unshare_folder"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("shared_folder_id", IDПапки, "Строка", Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); @@ -619,120 +619,120 @@ // Добавить пользователя к файлу // Определяет доступ к файлу для стороннего пользователя -// +// // Параметры: // Токен - Строка - Токен - token // IDФайла - Строка - ID файла, к которому предоставляется доступ - fileid // АдресаПочты - Строка, Массив Из Строка - Список адресов почты добавляемых пользователей - emails // ТолькоПросмотр - Булево - Запрещает редактирование файла для стороннего пользователя - readonly -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ДобавитьПользователейКФайлу(Знач Токен, Знач IDФайла, Знач АдресаПочты, Знач ТолькоПросмотр = Истина) Экспорт - + Строка_ = "Строка"; - + OPI_ПреобразованиеТипов.ПолучитьМассив(АдресаПочты); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDФайла); OPI_ПреобразованиеТипов.ПолучитьБулево(ТолькоПросмотр); - + Если Не СтрНачинаетсяС(IDФайла, "id:") Тогда IDФайла = "id:" + IDФайла; КонецЕсли; - + URL = "https://api.dropboxapi.com/2/sharing/add_file_member"; - + МассивПользователей = Новый Массив; - + Для Каждого Адрес Из АдресаПочты Цикл - + ДанныеПользователя = Новый Соответствие; OPI_Инструменты.ДобавитьПоле(".tag" , "email", Строка_, ДанныеПользователя); OPI_Инструменты.ДобавитьПоле("email", Адрес , Строка_, ДанныеПользователя); - + МассивПользователей.Добавить(ДанныеПользователя); КонецЦикла; - + Параметры = Новый Структура; - OPI_Инструменты.ДобавитьПоле("file" , IDФайла , Строка_, Параметры); + OPI_Инструменты.ДобавитьПоле("file" , IDФайла , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("members", МассивПользователей , "Массив", Параметры); - + Режим = ?(ТолькоПросмотр, "viewer", "editor"); - + OPI_Инструменты.ДобавитьПоле("access_level", Режим , Строка_, Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Добавить пользователей к папке // Предоставляет стороннии пользователям доступ к каталогу -// +// // Параметры: // Токен - Строка - Токен - token // IDПапки - Строка - ID публичного каталога (shared folder ID) - folder // АдресаПочты - Строка, Массив Из Строка - Список адресов почты добавляемых пользователей - emails // ТолькоПросмотр - Булево - Запрещает редактирование файла для стороннего пользователя - readonly -// +// // Возвращаемое значение: // Неопределено - пустой ответ Функция ДобавитьПользователейКПапке(Знач Токен, Знач IDПапки, Знач АдресаПочты, Знач ТолькоПросмотр = Истина) Экспорт - + Строка_ = "Строка"; - + OPI_ПреобразованиеТипов.ПолучитьМассив(АдресаПочты); OPI_ПреобразованиеТипов.ПолучитьБулево(ТолькоПросмотр); Режим = ?(ТолькоПросмотр, "viewer", "editor"); - + URL = "https://api.dropboxapi.com/2/sharing/add_folder_member"; - + МассивПользователей = Новый Массив; - + Для Каждого Адрес Из АдресаПочты Цикл - + ДанныеПользователя = Новый Соответствие; OPI_Инструменты.ДобавитьПоле(".tag" , "email", Строка_, ДанныеПользователя); OPI_Инструменты.ДобавитьПоле("email", Адрес , Строка_, ДанныеПользователя); - - СтруктураПользователя = Новый Структура("member,access_level", ДанныеПользователя, Режим); - + + СтруктураПользователя = Новый Структура("member,access_level", ДанныеПользователя, Режим); + МассивПользователей.Добавить(СтруктураПользователя); КонецЦикла; - + Параметры = Новый Структура; - OPI_Инструменты.ДобавитьПоле("shared_folder_id", IDПапки , Строка_, Параметры); + OPI_Инструменты.ДобавитьПоле("shared_folder_id", IDПапки , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("members" , МассивПользователей , "Массив", Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Получить статус асинхронного изменения // Получает статус асинхронной работы по изменению доступов -// +// // Параметры: // Токен - Строка - Токен - token // IDРаботы - Строка - ID асинхронной работы - job -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ПолучитьСтатусАсинхронногоИзменения(Знач Токен, Знач IDРаботы) Экспорт - + URL = "https://api.dropboxapi.com/2/sharing/check_job_status"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("async_job_id", IDРаботы, "Строка", Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); @@ -742,31 +742,31 @@ // Отменить публикацию файла // Запрещает доступ к файлу для внешних пользователей -// +// // Параметры: // Токен - Строка - Токен - token // IDФайла - Строка - ID файла, к которому предоставляется доступ - fileid -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Dropbox Функция ОтменитьПубликациюФайла(Знач Токен, Знач IDФайла) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDФайла); - + Если Не СтрНачинаетсяС(IDФайла, "id:") Тогда IDФайла = "id:" + IDФайла; КонецЕсли; - + URL = "https://api.dropboxapi.com/2/sharing/unshare_file"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("file", IDФайла, "Строка", Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); Возврат Ответ; - + КонецФункции #КонецОбласти @@ -776,10 +776,10 @@ #Область СлужебныеПроцедурыИФункции Функция ОбработатьОбъект(Знач Токен, Знач URL, Знач Путь, Знач ВЗаголовках = Ложь) - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("path", Путь, "Строка", Параметры); - + Если ВЗаголовках Тогда Заголовки = ПолучитьЗаголовкиЗапроса(Токен, Параметры); Ответ = OPI_Инструменты.PostBinary(URL, ПолучитьДвоичныеДанныеИзСтроки(""), Заголовки); @@ -787,9 +787,9 @@ Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); КонецЕсли; - + Возврат Ответ; - + КонецФункции Функция ОбработатьТег(Знач Токен, Знач Путь, Знач Тег, Знач ЭтоУдаление = Ложь) @@ -799,168 +799,168 @@ Иначе URL = "https://api.dropboxapi.com/2/files/tags/add"; КонецЕсли; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("path" , Путь, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("tag_text" , Тег , "Строка", Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции Функция ПолучитьЗаголовкиЗапроса(Знач Токен, Знач Параметры = "") - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Заголовки = Новый Соответствие; Заголовки.Вставить("Authorization" , "Bearer " + Токен); - + Если ЗначениеЗаполнено(Параметры) Тогда - + JSON = OPI_Инструменты.JSONСтрокой(Параметры, "Нет"); JSON = СтрЗаменить(JSON, Символы.ВК + Символы.ПС, ""); Заголовки.Вставить("Dropbox-API-Arg", JSON); - + КонецЕсли; - + Возврат Заголовки; - + КонецФункции Функция ЗагрузитьБольшойФайл(Знач Токен, Знач Файл, Знач Путь, Знач Режим) - - URL = "https://content.dropboxapi.com/2/files/upload_session/append_v2"; + + URL = "https://content.dropboxapi.com/2/files/upload_session/append_v2"; РазмерЧасти = 100000000; ТекущаяПозиция = 0; ПрочитаноБайт = 0; - ОбщийРазмер = Файл.Размер(); + ОбщийРазмер = Файл.Размер(); Сессия = ОткрытьСессию(Токен); - + Пока ПрочитаноБайт < ОбщийРазмер Цикл - + Отступ = ТекущаяПозиция; Курсор = Новый Структура("offset,session_id", Отступ, Сессия); - + Параметры = Новый Структура("cursor", Курсор); Заголовки = ПолучитьЗаголовкиЗапроса(Токен, Параметры); - + ЧтениеДанных = Новый ЧтениеДанных(Файл); ПрочитаноБайт = ЧтениеДанных.Пропустить(ТекущаяПозиция); Результат = ЧтениеДанных.Прочитать(РазмерЧасти); ТекущиеДанные = Результат.ПолучитьДвоичныеДанные(); РазмерТекущих = ТекущиеДанные.Размер(); - СледующаяПозиция = ТекущаяПозиция + РазмерТекущих; - + СледующаяПозиция = ТекущаяПозиция + РазмерТекущих; + Если Не ЗначениеЗаполнено(ТекущиеДанные) Тогда Прервать; КонецЕсли; Ответ = OPI_Инструменты.PostBinary(URL, ТекущиеДанные, Заголовки); - + ТекущаяПозиция = СледующаяПозиция; - + // !OInt КБайт = 1024; // !OInt МБайт = КБайт * КБайт; // !OInt Сообщить(OPI_Инструменты.ИнформацияОПрогрессе(ТекущаяПозиция, ОбщийРазмер, "МБ", МБайт)); - + // !OInt ВыполнитьСборкуМусора(); // !OInt ОсвободитьОбъект(ТекущиеДанные); - + КонецЦикла; - + Ответ = ЗакрытьСессию(Токен, Путь, Режим, ОбщийРазмер, Сессия); - + Возврат Ответ; - + КонецФункции Функция ЗагрузитьМалыйФайл(Знач Токен, Знач Файл, Знач Путь, Знач Режим) - + Булево_ = "Булево"; Строка_ = "Строка"; URL = "https://content.dropboxapi.com/2/files/upload"; - + Параметры = Новый Структура; - + OPI_Инструменты.ДобавитьПоле("autorename" , Ложь , Булево_, Параметры); OPI_Инструменты.ДобавитьПоле("mode" , Режим, Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("mute" , Ложь , Булево_, Параметры); OPI_Инструменты.ДобавитьПоле("path" , Путь , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("strict_conflict", Ложь , Булево_, Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен, Параметры); Ответ = OPI_Инструменты.PostBinary(URL, Файл, Заголовки); - + Возврат Ответ; - + КонецФункции Функция ОткрытьСессию(Знач Токен) - + SessionId = "session_id"; URL = "https://content.dropboxapi.com/2/files/upload_session/start"; Заголовки = ПолучитьЗаголовкиЗапроса(Токен); - - Ответ = OPI_Инструменты.PostBinary(URL, ПолучитьДвоичныеДанныеИзСтроки(""), Заголовки); - + + Ответ = OPI_Инструменты.PostBinary(URL, ПолучитьДвоичныеДанныеИзСтроки(""), Заголовки); + Возврат Ответ[SessionId]; - + КонецФункции Функция ЗакрытьСессию(Знач Токен, Знач Путь, Знач Режим, Знач ОбщийРазмер, Знач Сессия) URL = "https://content.dropboxapi.com/2/files/upload_session/finish"; - + Коммит = Новый Структура(); OPI_Инструменты.ДобавитьПоле("mode", Режим, "Строка", Коммит); - OPI_Инструменты.ДобавитьПоле("path", Путь, "Строка", Коммит); - + OPI_Инструменты.ДобавитьПоле("path", Путь , "Строка", Коммит); + Курсор = Новый Структура("offset,session_id", ОбщийРазмер, Сессия); - + Параметры = Новый Структура("commit,cursor", Коммит, Курсор); Заголовки = ПолучитьЗаголовкиЗапроса(Токен, Параметры); - + Ответ = OPI_Инструменты.PostBinary(URL, ПолучитьДвоичныеДанныеИзСтроки(""), Заголовки); - + Возврат Ответ; - + КонецФункции Функция ПолучитьАккаунт(Знач Токен, Знач Аккаунт) - + URL = "https://api.dropboxapi.com/2/users/get_account"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("account_id", Аккаунт, "Строка", Параметры); - + Заголовки = ПолучитьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции Функция ПолучитьСвойАккаунт(Знач Токен) - + URL = "https://api.dropboxapi.com/2/users/get_current_account"; Заголовки = ПолучитьЗаголовкиЗапроса(Токен); - + Ответ = OPI_Инструменты.PostBinary(URL , ПолучитьДвоичныеДанныеИзСтроки("null") , Заголовки - , - , "text/plain; charset=dropbox-cors-hack"); - + , + , "text/plain; charset=dropbox-cors-hack"); + Возврат Ответ; - + КонецФункции -#КонецОбласти \ No newline at end of file +#КонецОбласти diff --git a/src/ru/OPI/src/CommonModules/OPI_GoogleCalendar/Module.bsl b/src/ru/OPI/src/CommonModules/OPI_GoogleCalendar/Module.bsl index 366f71bb26..f3af5689e9 100644 --- a/src/ru/OPI/src/CommonModules/OPI_GoogleCalendar/Module.bsl +++ b/src/ru/OPI/src/CommonModules/OPI_GoogleCalendar/Module.bsl @@ -1,4 +1,4 @@ -// OneScript: ./OInt/core/Modules/OPI_GoogleCalendar.os +// OneScript: ./OInt/core/Modules/OPI_GoogleCalendar.os // Lib: Google Calendar // CLI: gcalendar @@ -43,131 +43,131 @@ // Создать календарь // Создает пустой календарь -// +// // Параметры: // Токен - Строка - Токен - token // Наименование - Строка - Наименование создаваемого календаря - title -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция СоздатьКалендарь(Знач Токен, Знач Наименование) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Наименование); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://www.googleapis.com/calendar/v3/calendars"; - + Параметры = Новый Структура; Параметры.Вставить("summary" , Наименование); Параметры.Вставить("timeZone", "Europe/Moscow"); - + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить календарь // Получает информацию о календаре по ID -// +// // Параметры: // Токен - Строка - Токен - token // Календарь - Строка - ID календаря - calendar -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ПолучитьМетаданныеКалендаря(Знач Токен, Знач Календарь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Календарь); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/calendar/v3/calendars/" + Календарь; + URL = "https://www.googleapis.com/calendar/v3/calendars/" + Календарь; Ответ = OPI_Инструменты.Get(URL, , Заголовки); - + Возврат Ответ; КонецФункции // Изменить календарь // Изменяет свойства существуещего календаря -// +// // Параметры: // Токен - Строка - Токен - token // Календарь - Строка - ID календаря - calendar // Наименование - Строка - Новое наименование - title // Описание - Строка - Новое описание календаря - description -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ИзменитьМетаданныеКалендаря(Знач Токен , Знач Календарь , Знач Наименование = "" , Знач Описание = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Календарь); OPI_ПреобразованиеТипов.ПолучитьСтроку(Наименование); OPI_ПреобразованиеТипов.ПолучитьСтроку(Описание); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://www.googleapis.com/calendar/v3/calendars/" + Календарь; - + Параметры = Новый Структура; - + Если ЗначениеЗаполнено(Наименование) Тогда Параметры.Вставить("summary", Наименование); КонецЕсли; - + Если ЗначениеЗаполнено(Описание) Тогда Параметры.Вставить("description", Описание); КонецЕсли; - + Ответ = OPI_Инструменты.Patch(URL, Параметры, Заголовки, Истина); - + Возврат Ответ; КонецФункции // Очистить основной календарь // Очищает список событий основного календаря -// +// // Параметры: // Токен - Строка - Токен - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ОчиститьОсновнойКалендарь(Знач Токен) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/calendar/v3/calendars/primary/clear"; + URL = "https://www.googleapis.com/calendar/v3/calendars/primary/clear"; Ответ = OPI_Инструменты.Post(URL, , Заголовки, Ложь); - + Возврат Ответ; КонецФункции // Удалить календарь // Удаляет календарь по ID -// +// // Параметры: // Токен - Строка - Токен - token // Календарь - Строка - ID календаря - calendar -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция УдалитьКалендарь(Знач Токен, Знач Календарь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Календарь); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/calendar/v3/calendars/" + Календарь; + URL = "https://www.googleapis.com/calendar/v3/calendars/" + Календарь; Ответ = OPI_Инструменты.Delete(URL, , Заголовки); - + Возврат Ответ; КонецФункции @@ -178,105 +178,105 @@ // Получить список календарей // Получает массив календарей аккаунта -// +// // Параметры: // Токен - Строка - Токен - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - Массив соответствий данных календарей Функция ПолучитьСписокКалендарей(Знач Токен) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); МассивКалендарей = Новый Массив; - + ПолучитьСписокКалендарейРекурсивно(Заголовки, МассивКалендарей); - + Возврат МассивКалендарей; - + КонецФункции // Добавить календарь в список // Добавляет существующий календарь в список пользователя -// +// // Параметры: // Токен - Строка - Токен - token // Календарь - Строка - ID календаря - calendar -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ДобавитьКалендарьВСписок(Знач Токен, Знач Календарь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Календарь); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://www.googleapis.com/calendar/v3/users/me/calendarList"; - + Параметры = Новый Структура; Параметры.Вставить("id", Календарь); - + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить календарь списка // Получает календарь из списка пользователя по ID -// +// // Параметры: // Токен - Строка - Токен - token // Календарь - Строка - ID календаря - calendar -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ПолучитьКалендарьСписка(Знач Токен, Знач Календарь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Календарь); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://www.googleapis.com/calendar/v3/users/me/calendarList/" + Календарь; Ответ = OPI_Инструменты.Get(URL, , Заголовки); - + Возврат Ответ; КонецФункции // Удалить календарь из списка // Удаляет календарь из списка пользователя -// +// // Параметры: // Токен - Строка - Токен - token // Календарь - Строка - ID календаря - calendar -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция УдалитьКалендарьИзСписка(Знач Токен, Знач Календарь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Календарь); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://www.googleapis.com/calendar/v3/users/me/calendarList/" + Календарь; Ответ = OPI_Инструменты.Delete(URL, , Заголовки); - + Возврат Ответ; КонецФункции // Изменить календарь списка // Изменяет свойства календаря из списка пользователей -// +// // Параметры: // Токен - Строка - Токен - token // Календарь - Строка - ID календаря - calendar // ОсновнойЦвет - Строка - HEX основного цвета (#ffffff) - primary // ДополнительныйЦвет - Строка - HEX дополнительного цвета (#ffffff) - secondary // Скрытый - Булево - Скрытый календарь - hidden -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ИзменитьКалендарьСписка(Знач Токен @@ -284,23 +284,23 @@ , Знач ОсновнойЦвет , Знач ДополнительныйЦвет , Знач Скрытый = Ложь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Календарь); OPI_ПреобразованиеТипов.ПолучитьСтроку(ОсновнойЦвет); OPI_ПреобразованиеТипов.ПолучитьСтроку(ДополнительныйЦвет); OPI_ПреобразованиеТипов.ПолучитьБулево(Скрытый); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://www.googleapis.com/calendar/v3/users/me/calendarList/" + Календарь + "?colorRgbFormat=true"; - + Параметры = Новый Соответствие; Параметры.Вставить("hidden" , Скрытый); Параметры.Вставить("foregroundColor", ОсновнойЦвет); Параметры.Вставить("backgroundColor", ДополнительныйЦвет); - + Ответ = OPI_Инструменты.Put(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции @@ -310,15 +310,15 @@ #Область РаботаССобытиями // Получить описание события !NOCLI -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - Пустой макет события Функция ПолучитьОписаниеСобытия() Экспорт - + ТекущаяДата = OPI_Инструменты.ПолучитьТекущуюДату(); Час = 3600; Событие = Новый Соответствие; - + Событие.Вставить("Описание" , ""); // Описание события Событие.Вставить("Заголовок" , "Новое событие"); // Заголовок события Событие.Вставить("МестоПроведения" , ""); // Строка описание места проведения @@ -328,149 +328,149 @@ Событие.Вставить("ОтправлятьУведомления" , Истина); // Признак отправки уведомлений участникам Возврат Событие; - + КонецФункции // Получить список событий // Получает список всех событий календаря -// +// // Параметры: // Токен - Строка - Токен - token // Календарь - Строка - ID календаря - calendar -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - Массив соответствий событий Функция ПолучитьСписокСобытий(Знач Токен, Знач Календарь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Календарь); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); МассивСобытий = Новый Массив; - + ПолучитьСписокСобытийРекурсивно(Заголовки, Календарь, МассивСобытий); - + Возврат МассивСобытий; - + КонецФункции // Получить событие // Получает событие по ID -// +// // Параметры: // Токен - Строка - Токен - token // Календарь - Строка - ID календаря - calendar // Событие - Строка - ID события - event -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ПолучитьСобытие(Знач Токен, Знач Календарь, Знач Событие) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Календарь); OPI_ПреобразованиеТипов.ПолучитьСтроку(Событие); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/calendar/v3/calendars/" - + Календарь + URL = "https://www.googleapis.com/calendar/v3/calendars/" + + Календарь + "/events/" - + Событие; - + + Событие; + Ответ = OPI_Инструменты.Get(URL, , Заголовки); - + Возврат Ответ; КонецФункции // Создать событие // Создает новое событие -// +// // Параметры: -// Токен - Строка - Токен - token +// Токен - Строка - Токен - token // Календарь - Строка - ID календаря - calendar // ОписаниеСобытия - Соответствие Из КлючИЗначение - Описание события - props -// +// // Возвращаемое значение: // Строка, Произвольный, HTTPОтвет, ДвоичныеДанные, Неопределено - ответ сервера Google -Функция СоздатьСобытие(Знач Токен, Знач Календарь, Знач ОписаниеСобытия) Экспорт - +Функция СоздатьСобытие(Знач Токен, Знач Календарь, Знач ОписаниеСобытия) Экспорт + Возврат УправлениеСобытием(Токен, Календарь, ОписаниеСобытия); - + КонецФункции // Переместить событие // Перемещает событие в другой календарь -// +// // Параметры: // Токен - Строка - Токен - token // КалендарьИсточник - Строка - ID календаря источника - from // КалендарьПриемник - Строка - ID календаря приемника - to // Событие - Строка - ID события календаря источника - event -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ПереместитьСобытие(Знач Токен, Знач КалендарьИсточник, Знач КалендарьПриемник, Знач Событие) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(КалендарьИсточник); OPI_ПреобразованиеТипов.ПолучитьСтроку(КалендарьПриемник); OPI_ПреобразованиеТипов.ПолучитьСтроку(Событие); - - Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/calendar/v3/calendars/" - + КалендарьИсточник + + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); + URL = "https://www.googleapis.com/calendar/v3/calendars/" + + КалендарьИсточник + "/events/" + Событие + "/move?destination=" - + КалендарьПриемник; - + + КалендарьПриемник; + Ответ = OPI_Инструменты.Post(URL, , Заголовки); - + Возврат Ответ; КонецФункции // Изменить событие // Изменяет существующее событие -// +// // Параметры: // Токен - Строка - Токен - token // Календарь - Строка - ID календаря - calendar // ОписаниеСобытия - Строка - Новое описание события - props // Событие - Строка - ID события - event -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ИзменитьСобытие(Знач Токен, Знач Календарь, Знач ОписаниеСобытия, Знач Событие) Экспорт - + Возврат УправлениеСобытием(Токен, Календарь, ОписаниеСобытия, Событие); - + КонецФункции // Удалить событие // Удаляет событие по ID -// +// // Параметры: // Токен - Строка - Токен - token // Календарь - Строка - ID календаря - calendar // Событие - Строка - ID события - event -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция УдалитьСобытие(Знач Токен, Знач Календарь, Знач Событие) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Календарь); OPI_ПреобразованиеТипов.ПолучитьСтроку(Событие); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/calendar/v3/calendars/" - + Календарь + URL = "https://www.googleapis.com/calendar/v3/calendars/" + + Календарь + "/events/" - + Событие; - + + Событие; + Ответ = OPI_Инструменты.Delete(URL, , Заголовки); - + Возврат Ответ; КонецФункции @@ -482,51 +482,51 @@ #Область СлужебныеПроцедурыИФункции Функция ПреобразоватьДату(Знач Дата) - + OPI_ПреобразованиеТипов.ПолучитьДату(Дата); - + СтруктураДаты = Новый Структура; - + Если Не ТипЗнч(Дата) = Тип("Дата") Тогда Возврат Неопределено; КонецЕсли; - - Если Дата = НачалоДня(Дата) Тогда + + Если Дата = НачалоДня(Дата) Тогда ФорматДаты = "ДФ=yyyy-MM-dd"; Поле = "date"; Иначе ФорматДаты = "ДФ=yyyy-MM-ddTHH:mm:ssZ"; Поле = "dateTime"; КонецЕсли; - + Дата = Формат(Дата, ФорматДаты); СтруктураДаты.Вставить(Поле , Дата); СтруктураДаты.Вставить("timeZone", "Europe/Moscow"); - + Возврат СтруктураДаты; - + КонецФункции Функция ПреобразоватьВложения(Знач Вложения) - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Вложения); - + МассивВложений = Новый Массив; - + Если ТипЗнч(Вложения) = Тип("Соответствие") Или ТипЗнч(Вложения) = Тип("Структура") Тогда - + Для Каждого Вложение Из Вложения Цикл - + ТекущеВложение = Новый Структура; ТекущеВложение.Вставить("title" , Вложение.Ключ); ТекущеВложение.Вставить("fileUrl", Вложение.Значение); - + МассивВложений.Добавить(ТекущеВложение); - + КонецЦикла; - + КонецЕсли; - + Если МассивВложений.Количество() > 0 Тогда Возврат МассивВложений; Иначе @@ -536,19 +536,19 @@ КонецФункции Функция УправлениеСобытием(Знач Токен, Знач Календарь, Знач ОписаниеСобытия, Знач Событие = "") - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Календарь); OPI_ПреобразованиеТипов.ПолучитьСтроку(Событие); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(ОписаниеСобытия); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); Существующее = ЗначениеЗаполнено(Событие); - URL = "https://www.googleapis.com/calendar/v3/calendars/" - + Календарь + URL = "https://www.googleapis.com/calendar/v3/calendars/" + + Календарь + "/events" - + ?(Существующее, "/" + Событие, ""); - + + ?(Существующее, "/" + Событие, ""); + Дата0 = ОписаниеСобытия["ДатаНачала"]; Дата1 = ОписаниеСобытия["ДатаОкончания"]; Вложения = ОписаниеСобытия["МассивURLФайловВложений"]; @@ -556,85 +556,85 @@ Уведомления = ?(ОписаниеСобытия["ОтправлятьУведомления"] = Неопределено , Ложь , ОписаниеСобытия["ОтправлятьУведомления"]); - + Параметры = Новый Структура; Параметры.Вставить("summary" , ОписаниеСобытия["Заголовок"]); Параметры.Вставить("description", ОписаниеСобытия["Описание"]); Параметры.Вставить("location" , ОписаниеСобытия["МестоПроведения"]); Параметры.Вставить("start" , ПреобразоватьДату(Дата0)); Параметры.Вставить("end" , ПреобразоватьДату(Дата1)); - Параметры.Вставить("attachments", Вложения); - - ПараметрыURL = Новый Структура; - ПараметрыURL.Вставить("sendUpdates" , ?(Уведомления, "all", "none")); + Параметры.Вставить("attachments", Вложения); + + ПараметрыURL = Новый Структура; + ПараметрыURL.Вставить("sendUpdates" , ?(Уведомления , "all" , "none")); ПараметрыURL.Вставить("supportsAttachments" , ?(ЗначениеЗаполнено(Вложения), "true", "false")); - + URL = URL + OPI_Инструменты.ПараметрыЗапросаВСтроку(ПараметрыURL); - + OPI_Инструменты.УдалитьПустыеПоляКоллекции(Параметры); - + Если Существующее Тогда Ответ = OPI_Инструменты.Patch(URL, Параметры, Заголовки, Истина); Иначе Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки, Истина); КонецЕсли; - + Возврат Ответ; КонецФункции -Процедура ПолучитьСписокКалендарейРекурсивно(Знач Заголовки, МассивКалендарей, Страница = "") - +Процедура ПолучитьСписокКалендарейРекурсивно(Знач Заголовки, МассивКалендарей, Страница = "") + Items = "items"; NPT = "nextPageToken"; Параметры = Новый Структура; - + Если ЗначениеЗаполнено(Страница) Тогда Параметры.Вставить("pageToken", Страница); КонецЕсли; - + Результат = OPI_Инструменты.Get("https://www.googleapis.com/calendar/v3/users/me/calendarList" , Параметры , Заголовки); - + Календари = Результат[Items]; Страница = Результат[NPT]; - + Для Каждого Календарь Из Календари Цикл - МассивКалендарей.Добавить(Календарь); - КонецЦикла; - + МассивКалендарей.Добавить(Календарь); + КонецЦикла; + Если Календари.Количество() > 0 И ЗначениеЗаполнено(Страница) Тогда - ПолучитьСписокКалендарейРекурсивно(Заголовки, МассивКалендарей, Страница); + ПолучитьСписокКалендарейРекурсивно(Заголовки, МассивКалендарей, Страница); КонецЕсли; - + КонецПроцедуры -Процедура ПолучитьСписокСобытийРекурсивно(Знач Заголовки, Знач Календарь, МассивСобытий, Страница = "") - +Процедура ПолучитьСписокСобытийРекурсивно(Знач Заголовки, Знач Календарь, МассивСобытий, Страница = "") + Items = "items"; NPT = "nextPageToken"; Параметры = Новый Структура; - + Если ЗначениеЗаполнено(Страница) Тогда Параметры.Вставить("pageToken", Страница); КонецЕсли; - + Результат = OPI_Инструменты.Get("https://www.googleapis.com/calendar/v3/calendars/" + Календарь + "/events" , Параметры , Заголовки); - + События = Результат[Items]; Страница = Результат[NPT]; - + Для Каждого Событие Из События Цикл - МассивСобытий.Добавить(Событие); - КонецЦикла; - + МассивСобытий.Добавить(Событие); + КонецЦикла; + Если События.Количество() > 0 И ЗначениеЗаполнено(Страница) Тогда - ПолучитьСписокСобытийРекурсивно(Заголовки, МассивСобытий, Страница); + ПолучитьСписокСобытийРекурсивно(Заголовки, МассивСобытий, Страница); КонецЕсли; - + КонецПроцедуры -#КонецОбласти \ No newline at end of file +#КонецОбласти diff --git a/src/ru/OPI/src/CommonModules/OPI_GoogleDrive/Module.bsl b/src/ru/OPI/src/CommonModules/OPI_GoogleDrive/Module.bsl index 1788c40507..710da4781c 100644 --- a/src/ru/OPI/src/CommonModules/OPI_GoogleDrive/Module.bsl +++ b/src/ru/OPI/src/CommonModules/OPI_GoogleDrive/Module.bsl @@ -1,4 +1,4 @@ -// OneScript: ./OInt/core/Modules/OPI_GoogleDrive.os +// OneScript: ./OInt/core/Modules/OPI_GoogleDrive.os // Lib: Google Drive // CLI: gdrive @@ -43,277 +43,277 @@ // Получить информацию об объекте // Получает информацию о папке или файле по ID -// +// // Параметры: // Токен - Строка - Токен - token // Идентификатор - Строка - Идентификатор файла или каталога - object -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ПолучитьИнформациюОбОбъекте(Знач Токен, Знач Идентификатор) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Идентификатор); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/drive/v3/files/" + Идентификатор; - + URL = "https://www.googleapis.com/drive/v3/files/" + Идентификатор; + Параметры = Новый Структура; Параметры.Вставить("fields", "*"); - + Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Получить список каталогов // Получает список каталогов диска -// +// // Параметры: // Токен - Строка - Токен - token // ИмяСодержит - Строка - Отбор по имени - querry // Подробно - Булево - Добавляет список файлов к полям каталога - depth -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - Массив соответствий каталогов Функция ПолучитьСписокКаталогов(Знач Токен, Знач ИмяСодержит = "", Знач Подробно = Ложь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(ИмяСодержит); OPI_ПреобразованиеТипов.ПолучитьБулево(Подробно); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); МассивОбъектов = Новый Массив; Отбор = Новый Массив; - + Отбор.Добавить("mimeType = 'application/vnd.google-apps.folder'"); - + Если ЗначениеЗаполнено(ИмяСодержит) Тогда Отбор.Добавить("name contains '" + ИмяСодержит + "'"); КонецЕсли; - + ПолучитьСписокОбъектовРекурсивно(Заголовки, МассивОбъектов, Подробно, Отбор); - + Если Подробно Тогда - РазложитьОбъектыПодробно(Токен, МассивОбъектов); + РазложитьОбъектыПодробно(Токен, МассивОбъектов); КонецЕсли; - + Возврат МассивОбъектов; - + КонецФункции // Получить список файлов // Получает список файлов -// +// // Параметры: // Токен - Строка - Токен - token // ИмяСодержит - Строка - Отбор по имени - querry // Каталог - Строка - Отбор по ID каталога родителя - catalog -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - Массив соответствий файлов Функция ПолучитьСписокФайлов(Знач Токен, Знач ИмяСодержит = "", Знач Каталог = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(ИмяСодержит); OPI_ПреобразованиеТипов.ПолучитьСтроку(Каталог); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); МассивОбъектов = Новый Массив; Отбор = Новый Массив; - + Отбор.Добавить("mimeType != 'application/vnd.google-apps.folder'"); - + Если ЗначениеЗаполнено(ИмяСодержит) Тогда Отбор.Добавить("name contains '" + ИмяСодержит + "'"); КонецЕсли; - + Если ЗначениеЗаполнено(Каталог) Тогда Отбор.Добавить("'" + Каталог + "' in parents"); КонецЕсли; - + ПолучитьСписокОбъектовРекурсивно(Заголовки, МассивОбъектов, , Отбор); - + Возврат МассивОбъектов; КонецФункции // Загрузить файл // Загружает файл на диск -// +// // Параметры: // Токен - Строка - Токен - token // Файл - ДвоичныеДанные,Строка - Загружаемый файл - file // Описание - Соответствие Из КлючИЗначение - См. ПолучитьОписаниеФайла - props - JSON описания или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ЗагрузитьФайл(Знач Токен, Знач Файл, Знач Описание) Экспорт - - Возврат УправлениеФайлом(Токен, Файл, Описание); - + + Возврат УправлениеФайлом(Токен, Файл, Описание); + КонецФункции // Создать папку // Создает пустой каталог на диске -// +// // Параметры: // Токен - Строка - Токен - token // Имя - Строка - Имя папки - title // Родитель - Строка - Родитель - catalog -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция СоздатьПапку(Знач Токен, Знач Имя, Знач Родитель = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Имя); OPI_ПреобразованиеТипов.ПолучитьСтроку(Родитель); - + Описание = Новый Соответствие; Описание.Вставить("MIME" , "application/vnd.google-apps.folder"); Описание.Вставить("Имя" , Имя); Описание.Вставить("Описание", ""); Описание.Вставить("Родитель", ?(ЗначениеЗаполнено(Родитель), Родитель, "root")); - + Возврат УправлениеФайлом(Токен, , Описание); - + КонецФункции // Скачать файл // Получает файл по ID -// +// // Параметры: // Токен - Строка - Токен - token // Идентификатор - Строка - Идентификатор файла - object -// ПутьСохранения - Строка - Путь сохранения файла - out -// +// ПутьСохранения - Строка - Путь сохранения файла - out +// // Возвращаемое значение: // ДвоичныеДанные,Строка - Двоичные данные или путь к файлу при указании параметра ПутьСохранения Функция СкачатьФайл(Знач Токен, Знач Идентификатор, Знач ПутьСохранения = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Идентификатор); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/drive/v3/files/" + Идентификатор; - + URL = "https://www.googleapis.com/drive/v3/files/" + Идентификатор; + Параметры = Новый Соответствие; Параметры.Вставить("alt", "media"); - + Ответ = OPI_Инструменты.Get(URL, Параметры , Заголовки, ПутьСохранения); - + Возврат Ответ; КонецФункции // Скоприровать объект // Копирует файл или каталог -// +// // Параметры: // Токен - Строка - Токен - token // Идентификатор - Строка - Идентификатор объекта - object // НовоеИмя - Строка - Новое имя объекта - title // НовыйРодитель - Строка - Новый каталог размещения - catalog -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция СкопироватьОбъект(Знач Токен, Знач Идентификатор, Знач НовоеИмя = "", Знач НовыйРодитель = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(НовоеИмя); OPI_ПреобразованиеТипов.ПолучитьСтроку(Идентификатор); OPI_ПреобразованиеТипов.ПолучитьСтроку(НовыйРодитель); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/drive/v3/files/" + Идентификатор + "/copy"; - + URL = "https://www.googleapis.com/drive/v3/files/" + Идентификатор + "/copy"; + Параметры = Новый Структура; - + Если ЗначениеЗаполнено(НовоеИмя) Тогда Параметры.Вставить("name", НовоеИмя); КонецЕсли; - + Если ЗначениеЗаполнено(НовыйРодитель) Тогда - + МассивРодителей = Новый Массив; МассивРодителей.Добавить(НовыйРодитель); Параметры.Вставить("parents", МассивРодителей); - + КонецЕсли; - + Ответ = OPI_Инструменты.Post(URL, Параметры , Заголовки, Истина); - + Возврат Ответ; КонецФункции // Обновить файл // Обновляет двоичные данные файла -// +// // Параметры: // Токен - Строка - Токен - token // Идентификатор - Строка - Идентификатор обновляемого объекта - object // Файл - ДвоичныеДанные,Строка - Файл источник обновления - file // НовоеИмя - Строка - Новое имя файла (если необходимо) - title -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ОбновитьФайл(Знач Токен, Знач Идентификатор, Знач Файл, Знач НовоеИмя = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Идентификатор); OPI_ПреобразованиеТипов.ПолучитьСтроку(НовоеИмя); OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Файл); - + Если ЗначениеЗаполнено(НовоеИмя) Тогда Описание = Новый Соответствие; Описание.Вставить("Имя", НовоеИмя); Иначе Описание = ""; КонецЕсли; - + Возврат УправлениеФайлом(Токен, Файл, Описание, Идентификатор); - + КонецФункции // Удалить объект // Удаляет файл или каталог по ID -// +// // Параметры: // Токен - Строка - Токен - token // Идентификатор - Строка - Идентификатор объекта для удаления - object -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция УдалитьОбъект(Знач Токен, Знач Идентификатор) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Идентификатор); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/drive/v3/files/" + Идентификатор; + URL = "https://www.googleapis.com/drive/v3/files/" + Идентификатор; Ответ = OPI_Инструменты.Delete(URL, , Заголовки); - + Возврат Ответ; КонецФункции // Получить описание файла !NOCLI -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - Описание файла Функция ПолучитьОписаниеФайла() Экспорт - + Описание = Новый Соответствие; Описание.Вставить("MIME" , "image/jpeg"); // MIME-тип загружаемого файла Описание.Вставить("Имя" , "Новый файл.jpg"); // Имя файла с расширением Описание.Вставить("Описание" , "Это новый файл"); // Описание файла Описание.Вставить("Родитель" , "root"); // ID каталога загрузки или "root" для загрузки в корень - + Возврат Описание; - + КонецФункции #КонецОбласти @@ -322,107 +322,107 @@ // Создать комментарий // Создает комментарий к файлу или каталогу -// +// // Параметры: // Токен - Строка - Токен - token -// Идентификатор - Строка - Идентификатор объекта, для которого необходим комментарий - object +// Идентификатор - Строка - Идентификатор объекта, для которого необходим комментарий - object // Комментарий - Строка - Текст комментария - text -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция СоздатьКомментарий(Знач Токен, Знач Идентификатор, Знач Комментарий) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Идентификатор); OPI_ПреобразованиеТипов.ПолучитьСтроку(Комментарий); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/drive/v3/files/" + Идентификатор + "/comments?fields=*"; - + URL = "https://www.googleapis.com/drive/v3/files/" + Идентификатор + "/comments?fields=*"; + Параметры = Новый Структура; Параметры.Вставить("content", Комментарий); - + Ответ = OPI_Инструменты.POST(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Получить комментарий // Получает комментарий по ID -// +// // Параметры: // Токен - Строка - Токен - token // ИДОбъекта - Строка - Идентификатор файла или каталога размещения комментария - object // ИДКомментария - Строка - Идентификатор комментария - comment -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ПолучитьКомментарий(Знач Токен, Знач ИДОбъекта, Знач ИДКомментария) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(ИДОбъекта); OPI_ПреобразованиеТипов.ПолучитьСтроку(ИДКомментария); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/drive/v3/files/" + ИДОбъекта + "/comments/" + ИДКомментария; - + URL = "https://www.googleapis.com/drive/v3/files/" + ИДОбъекта + "/comments/" + ИДКомментария; + Параметры = Новый Структура; Параметры.Вставить("fields", "*"); - + Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Получить список комментариев // Получает список всех комментариев объекта -// +// // Параметры: // Токен - Строка - Токен - token // ИДОбъекта - Строка - Идентификатор объекта - object -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ПолучитьСписокКомментариев(Знач Токен, Знач ИДОбъекта) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(ИДОбъекта); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/drive/v3/files/" + ИДОбъекта + "/comments"; - + URL = "https://www.googleapis.com/drive/v3/files/" + ИДОбъекта + "/comments"; + Параметры = Новый Структура; Параметры.Вставить("fields", "*"); - + Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Удалить комментарий // Удаляет комментарий по ID -// +// // Параметры: // Токен - Строка - Токен - token // ИДОбъекта - Строка - Идентификатор файла или каталога размещения комментария - object // ИДКомментария - Строка - Идентификатор комментария - comment -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция УдалитьКомментарий(Знач Токен, Знач ИДОбъекта, Знач ИДКомментария) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(ИДОбъекта); OPI_ПреобразованиеТипов.ПолучитьСтроку(ИДКомментария); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); - URL = "https://www.googleapis.com/drive/v3/files/" + ИДОбъекта + "/comments/" + ИДКомментария; - + URL = "https://www.googleapis.com/drive/v3/files/" + ИДОбъекта + "/comments/" + ИДКомментария; + Ответ = OPI_Инструменты.Delete(URL, , Заголовки); - + Возврат Ответ; КонецФункции @@ -433,59 +433,59 @@ #Область СлужебныеПроцедурыИФункции -Процедура ПолучитьСписокОбъектовРекурсивно(Знач Заголовки, МассивОбъектов, Подробно = Ложь, Отбор = "", Страница = "") - +Процедура ПолучитьСписокОбъектовРекурсивно(Знач Заголовки, МассивОбъектов, Подробно = Ложь, Отбор = "", Страница = "") + URL = "https://www.googleapis.com/drive/v3/files"; Files = "files"; NPT = "nextPageToken"; Параметры = Новый Структура; Параметры.Вставить("fields", "*"); - + Если ЗначениеЗаполнено(Страница) Тогда Параметры.Вставить("pageToken", Страница); КонецЕсли; - - Если ЗначениеЗаполнено(Отбор) И ТипЗнч(Отбор) = Тип("Массив") Тогда + + Если ЗначениеЗаполнено(Отбор) И ТипЗнч(Отбор) = Тип("Массив") Тогда ОтборСтрока = СтрСоединить(Отбор, " and "); - Параметры.Вставить("q", ОтборСтрока); + Параметры.Вставить("q", ОтборСтрока); КонецЕсли; - + Результат = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Объекты = Результат[Files]; Страница = Результат[NPT]; - + Для Каждого ТекущийОбъект Из Объекты Цикл МассивОбъектов.Добавить(ТекущийОбъект); - КонецЦикла; - + КонецЦикла; + Если Объекты.Количество() > 0 И ЗначениеЗаполнено(Страница) Тогда - ПолучитьСписокОбъектовРекурсивно(Заголовки, МассивОбъектов, Подробно, Отбор, Страница); + ПолучитьСписокОбъектовРекурсивно(Заголовки, МассивОбъектов, Подробно, Отбор, Страница); КонецЕсли; - + КонецПроцедуры -Процедура РазложитьОбъектыПодробно(Знач Токен, МассивОбъектов) - +Процедура РазложитьОбъектыПодробно(Знач Токен, МассивОбъектов) + Для Каждого ТекущийОбъект Из МассивОбъектов Цикл - + МассивФайлов = Новый Массив; ТекущийИД = ТекущийОбъект["id"]; - + Результат = ПолучитьСписокФайлов(Токен, , ТекущийИД); - + Для Каждого Файл Из Результат Цикл - МассивФайлов.Добавить(Файл); + МассивФайлов.Добавить(Файл); КонецЦикла; - + ТекущийОбъект.Вставить("files", МассивФайлов); - + КонецЦикла; - + КонецПроцедуры Процедура СформироватьПараметрыЗагрузкиФайла(Описание) - + СформированноеОписание = Новый Соответствие; OPI_Инструменты.УдалитьПустыеПоляКоллекции(Описание); @@ -495,81 +495,81 @@ СоответствиеПолей.Вставить("Описание" , "description"); СоответствиеПолей.Вставить("Родитель" , "parents"); СоответствиеПолей.Вставить("Расширение", "fileExtension"); - + Для Каждого Элемент Из Описание Цикл - + Если Элемент.Ключ = "Родитель" Тогда - + ТекущееЗначение = Новый Массив; ТекущееЗначение.Добавить(Элемент.Значение); - + Иначе - + ТекущееЗначение = Элемент.Значение; - + КонецЕсли; - + ИмяПоля = СоответствиеПолей.Получить(Элемент.Ключ); СформированноеОписание.Вставить(ИмяПоля, ТекущееЗначение); - + КонецЦикла; - + Описание = СформированноеОписание; - + КонецПроцедуры -Функция УправлениеФайлом(Знач Токен, Знач Файл = "", Знач Описание = "", Знач Идентификатор = "") - +Функция УправлениеФайлом(Знач Токен, Знач Файл = "", Знач Описание = "", Знач Идентификатор = "") + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Идентификатор); - + Если ЗначениеЗаполнено(Описание) Тогда OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Описание); КонецЕсли; - + MimeType = "mimeType"; - + Если ЗначениеЗаполнено(Идентификатор) Тогда MIME = ПолучитьИнформациюОбОбъекте(Токен, Идентификатор)[MimeType]; Иначе MIME = Описание["MIME"]; - КонецЕсли; - + КонецЕсли; + Если Не ЗначениеЗаполнено(Описание) Тогда Описание = Новый Соответствие; КонецЕсли; - - Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); + + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); СформироватьПараметрыЗагрузкиФайла(Описание); ОписаниеJSON = OPI_Инструменты.JSONСтрокой(Описание); - + СоответствиеФайла = Новый Соответствие; - + Если ЗначениеЗаполнено(Файл) Тогда - - РазмерЧасти = 268435457; + + РазмерЧасти = 268435457; Размер = OPI_Инструменты.ПреобразоватьДанныеСПолучениемРазмера(Файл, РазмерЧасти); - + СоответствиеФайла.Вставить(Файл, MIME); - + Если Размер < РазмерЧасти И ТипЗнч(Файл) = Тип("ДвоичныеДанные") Тогда Ответ = ЗагрузитьМалыйФайл(ОписаниеJSON, СоответствиеФайла, Заголовки, Идентификатор); Иначе Ответ = ЗагрузитьБольшойФайл(Описание, СоответствиеФайла, Заголовки, Идентификатор); КонецЕсли; - + Иначе - Ответ = ЗагрузитьМалыйФайл(ОписаниеJSON, СоответствиеФайла, Заголовки, Идентификатор); + Ответ = ЗагрузитьМалыйФайл(ОписаниеJSON, СоответствиеФайла, Заголовки, Идентификатор); КонецЕсли; - + Возврат Ответ; - + КонецФункции Функция ЗагрузитьМалыйФайл(Знач Описание, Знач СоответствиеФайла, Знач Заголовки, Знач Идентификатор = "") - + URL = "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart"; - + Если ЗначениеЗаполнено(Идентификатор) Тогда URL = СтрЗаменить(URL, "/files", "/files/" + Идентификатор); Ответ = OPI_Инструменты.PatchMultipartRelated(URL, Описание, СоответствиеФайла, Заголовки); @@ -578,149 +578,149 @@ КонецЕсли; Возврат Ответ; - + КонецФункции Функция ЗагрузитьБольшойФайл(Знач Описание, Знач СоответствиеФайла, Знач Заголовки, Знач Идентификатор = "") - + Для Каждого Файл Из СоответствиеФайла Цикл Двоичные = Файл.Ключ; Прервать; КонецЦикла; - + URL = "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable"; - + Если ЗначениеЗаполнено(Идентификатор) Тогда URL = СтрЗаменить(URL, "/files", "/files/" + Идентификатор); Ответ = OPI_Инструменты.Patch(URL, Описание, Заголовки, Истина, Истина); Иначе Ответ = OPI_Инструменты.Post(URL, Описание, Заголовки, Истина, Истина); КонецЕсли; - + АдресЗагрузки = Ответ.Заголовки["Location"]; - + Если Не ЗначениеЗаполнено(АдресЗагрузки) Тогда OPI_Инструменты.ОбработатьОтвет(Ответ); Возврат Ответ; КонецЕсли; - + ОтветЗагрузки = ЗагрузитьФайлЧастями(Двоичные, АдресЗагрузки); Ответ = ?(ЗначениеЗаполнено(ОтветЗагрузки), ОтветЗагрузки, Ответ); - + OPI_Инструменты.ОбработатьОтвет(Ответ); Возврат Ответ; - + КонецФункции Функция ЗагрузитьФайлЧастями(Знач Двоичные, Знач АдресЗагрузки) - - Ответ = ""; - РазмерЧасти = 268435456; - ПрочитаноБайт = 0; + + Ответ = ""; + РазмерЧасти = 268435456; + ПрочитаноБайт = 0; ТекущаяПозиция = 0; ОбщийРазмер = Двоичные.Размер(); СтрОбщийРазмер = OPI_Инструменты.ЧислоВСтроку(ОбщийРазмер); ЧтениеДанных = Новый ЧтениеДанных(Двоичные); ИсходныйПоток = ЧтениеДанных.ИсходныйПоток(); - + Пока ПрочитаноБайт < ОбщийРазмер Цикл - + ПрочитаноБайт = ИсходныйПоток.ТекущаяПозиция(); Результат = ЧтениеДанных.Прочитать(РазмерЧасти); ТекущиеДанные = Результат.ПолучитьДвоичныеДанные(); РазмерТекущих = ТекущиеДанные.Размер(); - СледующаяПозиция = ТекущаяПозиция + РазмерТекущих - 1; - + СледующаяПозиция = ТекущаяПозиция + РазмерТекущих - 1; + Если Не ЗначениеЗаполнено(ТекущиеДанные) Тогда Прервать; КонецЕсли; - + ЗаголовокПотока = "bytes " + OPI_Инструменты.ЧислоВСтроку(ТекущаяПозиция) - + "-" - + OPI_Инструменты.ЧислоВСтроку(СледующаяПозиция) - + "/" + + "-" + + OPI_Инструменты.ЧислоВСтроку(СледующаяПозиция) + + "/" + СтрОбщийРазмер; - + ДопЗаголовки = Новый Соответствие; ДопЗаголовки.Вставить("Content-Length", OPI_Инструменты.ЧислоВСтроку(РазмерТекущих)); - ДопЗаголовки.Вставить("Content-Range" , ЗаголовокПотока); + ДопЗаголовки.Вставить("Content-Range" , ЗаголовокПотока); ДопЗаголовки.Вставить("Content-Type" , "application/octet-stream"); - + Ответ = OPI_Инструменты.Put(АдресЗагрузки, ТекущиеДанные, ДопЗаголовки, Ложь, Истина); - + РезультатПроверки = ПроверитьЗагрузкуЧасти(Ответ, СтрОбщийРазмер, ДопЗаголовки, АдресЗагрузки, ТекущаяПозиция); - + Если ЗначениеЗаполнено(РезультатПроверки) Тогда Возврат РезультатПроверки; КонецЕсли; - + // !OInt КБайт = 1024; // !OInt МБайт = КБайт * КБайт; // !OInt Сообщить(OPI_Инструменты.ИнформацияОПрогрессе(ТекущаяПозиция, ОбщийРазмер, "МБ", МБайт)); - + // !OInt ВыполнитьСборкуМусора(); // !OInt ОсвободитьОбъект(ТекущиеДанные); - + КонецЦикла; - + Возврат Ответ; - + КонецФункции Функция ПроверитьЗагрузкуЧасти(Ответ, СтрОбщийРазмер, ДопЗаголовки, АдресЗагрузки, ТекущаяПозиция) - + НачалоКодовОшибок = 400; КонецКодовПадений = 600; НачалоКодовУспеха = 200; КонецКодовУспеха = 300; Перенаправление = 308; - + Если Ответ.КодСостояния >= НачалоКодовОшибок И Ответ.КодСостояния < КонецКодовПадений Тогда - + ЗаголовокПотока = "bytes */" + СтрОбщийРазмер; ДопЗаголовки.Вставить("Content-Range" , ЗаголовокПотока); - + ОтветПроверки = OPI_Инструменты.Put(АдресЗагрузки, "", ДопЗаголовки, Ложь, Истина); - + Если ОтветПроверки.КодСостояния >= НачалоКодовУспеха И ОтветПроверки.КодСостояния < КонецКодовУспеха Тогда - + OPI_Инструменты.ОбработатьОтвет(ОтветПроверки); Возврат ОтветПроверки; - + ИначеЕсли ОтветПроверки.КодСостояния = Перенаправление Тогда - + ЗагруженныеДанные = Ответ.Заголовки["Range"]; - + Иначе - + OPI_Инструменты.ОбработатьОтвет(Ответ); Возврат Ответ; - + КонецЕсли; - + Иначе ЗагруженныеДанные = Ответ.Заголовки["Range"]; КонецЕсли; - + Если Не ЗначениеЗаполнено(ЗагруженныеДанные) Тогда OPI_Инструменты.ОбработатьОтвет(Ответ); Возврат Ответ; КонецЕсли; - + ЗагруженныеДанные = СтрЗаменить(ЗагруженныеДанные, "bytes=", ""); МассивИнформации = СтрРазделить(ЗагруженныеДанные, "-", Ложь); НеобходимоЧастей = 2; - + Если Не МассивИнформации.Количество() = НеобходимоЧастей Тогда OPI_Инструменты.ОбработатьОтвет(Ответ); Возврат Ответ; КонецЕсли; - + ТекущаяПозиция = Число(МассивИнформации[1]) + 1; - + Возврат ""; - + КонецФункции #КонецОбласти diff --git a/src/ru/OPI/src/CommonModules/OPI_GoogleSheets/Module.bsl b/src/ru/OPI/src/CommonModules/OPI_GoogleSheets/Module.bsl index 8b7ee50c1a..041fbeb545 100644 --- a/src/ru/OPI/src/CommonModules/OPI_GoogleSheets/Module.bsl +++ b/src/ru/OPI/src/CommonModules/OPI_GoogleSheets/Module.bsl @@ -1,4 +1,4 @@ -// OneScript: ./OInt/core/Modules/OPI_GoogleSheets.os +// OneScript: ./OInt/core/Modules/OPI_GoogleSheets.os // Lib: Google Sheets // CLI: gsheets @@ -43,90 +43,90 @@ // Создать книгу // Создает новую книгу -// +// // Параметры: // Токен - Строка - Токен - token // Наименование - Строка - Наименование - title // МассивИменЛистов - Массив из Строка - Массив имен для добавления новых листов в книгу - sheets -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция СоздатьКнигу(Знач Токен, Знач Наименование, Знач МассивИменЛистов) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Наименование); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивИменЛистов); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://sheets.googleapis.com/v4/spreadsheets"; - + Свойства = Новый Структура("title" , Наименование); Листы = Новый Массив; - + ЗаполнитьМассивЛистов(МассивИменЛистов, Листы); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("properties", Свойства, "Коллекция", Параметры); OPI_Инструменты.ДобавитьПоле("sheets" , Листы , "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Получить книгу // Получает информацию о книге по ID -// +// // Параметры: // Токен - Строка - Токен - token // Идентификатор - Строка - Идентификатор книги - spreadsheet -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ПолучитьКнигу(Знач Токен, Знач Идентификатор) Экспорт - OPI_ПреобразованиеТипов.ПолучитьСтроку(Идентификатор); - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Идентификатор); + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Идентификатор; - + Ответ = OPI_Инструменты.Get(URL, , Заголовки); - + Возврат Ответ; КонецФункции // Изменить наименование книги // Изменяет наименование существующей книги -// +// // Параметры: // Токен - Строка - Токен - token // Книга - Строка - ID книги - spreadsheet // Наименование - Строка - Новое наименование - title -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ИзменитьНаименованиеКниги(Знач Токен, Знач Книга, Знач Наименование) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Книга); OPI_ПреобразованиеТипов.ПолучитьСтроку(Наименование); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Книга + ":batchUpdate"; - + Изменение = Новый Структура("title", Наименование); ЗапросИзменения = Новый Структура("properties,fields", Изменение, "title"); Запрос = Новый Структура("updateSpreadsheetProperties", ЗапросИзменения); - + МассивЗапросов = Новый Массив; МассивЗапросов.Добавить(Запрос); - + Параметры = Новый Структура("requests", МассивЗапросов); - + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -135,95 +135,95 @@ // Добавить лист // Добавляет новый лист в книгу -// -// +// +// // Параметры: // Токен - Строка - Токен - token // Книга - Строка - Идентификатор книги - spreadsheet // Наименование - Строка - Наименование нового листа - title -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ДобавитьЛист(Знач Токен, Знач Книга, Знач Наименование) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Книга); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Книга + ":batchUpdate"; Лист = СоздатьЛист(Наименование); - + Запросы = Новый Массив; Изменение = Новый Структура("addSheet", Лист); Запросы.Добавить(Изменение); - + Параметры = Новый Структура("requests", Запросы); - + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Удалить лист // Удаляет лист из книги -// +// // Параметры: // Токен - Строка - Токен - token // Книга - Строка - Идентификатор книги - spreadsheet // Лист - Строка - Идентификатор удаляемого листа - sheet -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция УдалитьЛист(Знач Токен, Знач Книга, Знач Лист) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Книга); OPI_ПреобразованиеТипов.ПолучитьСтроку(Лист); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Книга + ":batchUpdate"; - + Запросы = Новый Массив; Лист = Новый Структура("sheetId" , Лист); Изменение = Новый Структура("deleteSheet", Лист); Запросы.Добавить(Изменение); - + Параметры = Новый Структура("requests", Запросы); - + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Копировать лист // Копирует лист из одной книги в другую -// +// // Параметры: // Токен - Строка - Токен - token // Откуда - Строка - ID книги источника - from // Куда - Строка - ID книги приемника - to // Лист - Строка - ID копируемого листа - sheet -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция КопироватьЛист(Знач Токен, Знач Откуда, Знач Куда, Знач Лист) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Откуда); OPI_ПреобразованиеТипов.ПолучитьСтроку(Куда); OPI_ПреобразованиеТипов.ПолучитьСтроку(Лист); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Откуда + "/sheets/" + Лист + ":copyTo"; - - Параметры = Новый Структура("destinationSpreadsheetId", Куда); + + Параметры = Новый Структура("destinationSpreadsheetId", Куда); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -232,14 +232,14 @@ // Установить значения ячеек // Устанавливает значения ячеек листа -// +// // Параметры: // Токен - Строка - Токен - token -// Книга - Строка - ID книги - spreadsheet +// Книга - Строка - ID книги - spreadsheet // СоответствиеЗначений - Соответствие Из КлючИЗначение - Данные заполнения, где ключ это имя ячейки вида A1 - data // Лист - Строка - Имя листа (первый лист по умолчанию) - sheetname // ОсновноеИзмерение - Строка - Основное измерение при заполнении диапазона массивом - dim -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция УстановитьЗначенияЯчеек(Знач Токен @@ -247,90 +247,90 @@ , Знач СоответствиеЗначений , Знач Лист = "" , Знач ОсновноеИзмерение = "COLUMNS") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Книга); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(СоответствиеЗначений); - - Если Не ТипЗнч(СоответствиеЗначений) = Тип("Структура") + + Если Не ТипЗнч(СоответствиеЗначений) = Тип("Структура") И Не ТипЗнч(СоответствиеЗначений) = Тип("Соответствие") Тогда Возврат "Не удалось привести структуру значений к коллекции"; КонецЕсли; - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Книга + "/values:batchUpdate"; МассивДанных = СформироватьМассивДанныхЯчеек(СоответствиеЗначений, ОсновноеИзмерение, Лист); Параметры = Новый Структура("data,valueInputOption", МассивДанных, "USER_ENTERED"); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Очистить ячейки // Очищает значение в ячейках -// +// // Параметры: // Токен - Строка - Токен - token // Книга - Строка - ID книги - spreadsheet // МассивЯчеек - Массив из Строка - Массив ячеек вида А1 для очистки - cells // Лист - Строка - Имя листа (первый лист по умолчанию) - sheetname -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ОчиститьЯчейки(Знач Токен, Знач Книга, Знач МассивЯчеек, Знач Лист = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Книга); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивЯчеек); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Книга + "/values:batchClear"; - + СформироватьМассивИменЯчеек(МассивЯчеек, Лист); - + Параметры = Новый Структура("ranges", МассивЯчеек); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить значения ячеек // Получает значения ячеек таблицы -// +// // Параметры: // Токен - Строка - Токен - token // Книга - Строка - ID книги - spreadsheet // МассивЯчеек - Массив из Строка - Массив ячеек вида А1 для получения (весь лист, если не заполнено) - cells // Лист - Строка - Имя листа (первый лист по умолчанию) - sheetname -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ПолучитьЗначенияЯчеек(Знач Токен, Знач Книга, Знач МассивЯчеек = "", Знач Лист = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Книга); - + Заголовки = OPI_GoogleWorkspace.ПолучитьЗаголовокАвторизации(Токен); URL = "https://sheets.googleapis.com/v4/spreadsheets/" + Книга + "/values:batchGet"; - + Если ЗначениеЗаполнено(МассивЯчеек) Тогда - OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивЯчеек); + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивЯчеек); СформироватьМассивИменЯчеек(МассивЯчеек, Лист); - - Первый = Истина; + + Первый = Истина; Для Каждого Ячейка Из МассивЯчеек Цикл Разделитель = ?(Первый, "?", "&"); URL = URL + Разделитель + "ranges=" + Ячейка; Первый = Ложь; КонецЦикла; Иначе - URL = URL + "?ranges='" + Лист + "'"; + URL = URL + "?ranges ='" + Лист + "'"; КонецЕсли; - + Ответ = OPI_Инструменты.Get(URL, , Заголовки); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -340,75 +340,75 @@ #Область СлужебныеПроцедурыИФункции Процедура ЗаполнитьМассивЛистов(Знач МассивИмен, МассивЛистов) - + Для Каждого ИмяЛиста Из МассивИмен Цикл - + Лист = СоздатьЛист(ИмяЛиста); МассивЛистов.Добавить(Лист); - + КонецЦикла; КонецПроцедуры Процедура ДобавитьИмяЛиста(Ячейка, Знач Лист) - + Если ЗначениеЗаполнено(Лист) Тогда Ячейка = "'" + Лист + "'!" + Ячейка; КонецЕсли; - + КонецПроцедуры Функция СоздатьЛист(Знач Наименование) - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Наименование); - + СвойстваЛиста = Новый Структура("title" , Наименование); Лист = Новый Структура("properties", СвойстваЛиста); Возврат Лист; - + КонецФункции Функция СформироватьМассивДанныхЯчеек(Знач СтруктураЗначений, Знач ОсновноеИзмерение, Знач Лист) - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Лист); - + МассивДанных = Новый Массив; - + Для Каждого ДанныеЯчейки Из СтруктураЗначений Цикл - + ТекущееЗначение = ДанныеЯчейки.Значение; ТекущийКлюч = ДанныеЯчейки.Ключ; - + ДобавитьИмяЛиста(ТекущийКлюч, Лист); - + OPI_ПреобразованиеТипов.ПолучитьМассив(ТекущееЗначение); - + ТекущиеДанные = Новый Соответствие; ТекущийМассив = Новый Массив; - + ТекущийМассив.Добавить(ТекущееЗначение); - + OPI_Инструменты.ДобавитьПоле("range" , ТекущийКлюч , "Строка", ТекущиеДанные); OPI_Инструменты.ДобавитьПоле("values" , ТекущийМассив , "Массив", ТекущиеДанные); OPI_Инструменты.ДобавитьПоле("majorDimension", ОсновноеИзмерение, "Строка", ТекущиеДанные); - + МассивДанных.Добавить(ТекущиеДанные); - + КонецЦикла; - + Возврат МассивДанных; - + КонецФункции Процедура СформироватьМассивИменЯчеек(Знач МассивИмен, Знач Лист) - OPI_ПреобразованиеТипов.ПолучитьСтроку(Лист); - - Для Н = 0 По МассивИмен.ВГраница() Цикл + OPI_ПреобразованиеТипов.ПолучитьСтроку(Лист); + + Для Н = 0 По МассивИмен.ВГраница() Цикл ДобавитьИмяЛиста(МассивИмен[Н], Лист); КонецЦикла; - + КонецПроцедуры -#КонецОбласти \ No newline at end of file +#КонецОбласти diff --git a/src/ru/OPI/src/CommonModules/OPI_GoogleWorkspace/Module.bsl b/src/ru/OPI/src/CommonModules/OPI_GoogleWorkspace/Module.bsl index 1fcde3b986..1abab34c29 100644 --- a/src/ru/OPI/src/CommonModules/OPI_GoogleWorkspace/Module.bsl +++ b/src/ru/OPI/src/CommonModules/OPI_GoogleWorkspace/Module.bsl @@ -1,4 +1,4 @@ -// OneScript: ./OInt/core/Modules/OPI_GoogleWorkspace.os +// OneScript: ./OInt/core/Modules/OPI_GoogleWorkspace.os // Lib: Google Workspace // CLI: google @@ -41,97 +41,97 @@ // Сформировать ссылку получения кода // Возвращает URL для авторизации в браузере -// +// // Параметры: // ClientID - Строка - Client ID - id // Calendar - Булево - разрешение на методы Calendar - calendar // Drive - Булево - разрешение на методы Drive - drive // Sheets - Булево - разрешение на методы Sheets - sheets -// +// // Возвращаемое значение: // Строка - Ссылка получения кода Функция СформироватьСсылкуПолученияКода(Знач ClientID , Знач Calendar = Истина , Знач Drive = Истина , Знач Sheets = Истина) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(ClientID); OPI_ПреобразованиеТипов.ПолучитьБулево(Calendar); OPI_ПреобразованиеТипов.ПолучитьБулево(Sheets); OPI_ПреобразованиеТипов.ПолучитьБулево(Drive); - + URL = "https://accounts.google.com/o/oauth2/auth"; - + ПараметрыURL = Новый Структура; ПараметрыURL.Вставить("response_type", "code"); ПараметрыURL.Вставить("client_id" , ClientID); ПараметрыURL.Вставить("redirect_uri" , "http://localhost"); ПараметрыURL.Вставить("access_type" , "offline"); ПараметрыURL.Вставить("scope" , ПолучитьСписокРазрешений(Calendar, Drive, Sheets)); - + URL = URL + OPI_Инструменты.ПараметрыЗапросаВСтроку(ПараметрыURL); - + Возврат URL; - + КонецФункции // Получить токен по коду // Получает токен по коду из авторизации в бразуере -// +// // Параметры: // ClientID - Строка - Client ID - id // ClientSecret - Строка - Client secret - secret // Code - Строка - Code из браузера - code -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ПолучитьТокенПоКоду(Знач ClientID, Знач ClientSecret, Знач Code) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(ClientID); OPI_ПреобразованиеТипов.ПолучитьСтроку(ClientSecret); OPI_ПреобразованиеТипов.ПолучитьСтроку(Code); - + URL = "https://accounts.google.com/o/oauth2/token"; - + ПараметрыURL = Новый Структура; ПараметрыURL.Вставить("grant_type" , "authorization_code"); ПараметрыURL.Вставить("client_id" , ClientID); ПараметрыURL.Вставить("client_secret", ClientSecret); - ПараметрыURL.Вставить("redirect_uri" , "http://localhost"); + ПараметрыURL.Вставить("redirect_uri" , "http://localhost"); ПараметрыURL.Вставить("code" , Code); - + Ответ = OPI_Инструменты.Post(URL, ПараметрыURL, , Ложь); - + Возврат Ответ; КонецФункции // Обновить токен // Обновляет токен по Refresh token -// +// // Параметры: // ClientID - Строка - Client ID - id // ClientSecret - Строка - Client secret - secret // RefreshToken - Строка - Refresh token - refresh -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Google Функция ОбновитьТокен(Знач ClientID, Знач ClientSecret, Знач RefreshToken) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(ClientID); OPI_ПреобразованиеТипов.ПолучитьСтроку(ClientSecret); OPI_ПреобразованиеТипов.ПолучитьСтроку(RefreshToken); - + URL = "https://accounts.google.com/o/oauth2/token"; - + ПараметрыURL = Новый Структура; ПараметрыURL.Вставить("grant_type" , "refresh_token"); ПараметрыURL.Вставить("client_id" , ClientID); - ПараметрыURL.Вставить("client_secret", ClientSecret); + ПараметрыURL.Вставить("client_secret", ClientSecret); ПараметрыURL.Вставить("refresh_token", RefreshToken); - + Ответ = OPI_Инструменты.Post(URL, ПараметрыURL, , Ложь); - + Возврат Ответ; КонецФункции @@ -141,14 +141,14 @@ #Область СлужебныйПрограммныйИнтерфейс Функция ПолучитьЗаголовокАвторизации(Знач Токен) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Заголовки = Новый Соответствие; Заголовки.Вставить("Authorization", "Bearer " + Токен); - + Возврат Заголовки; - + КонецФункции #КонецОбласти @@ -156,23 +156,23 @@ #Область СлужебныеПроцедурыИфункции Функция ПолучитьСписокРазрешений(Calendar, Drive, Sheets) - + МассивРазрешений = Новый Массив; - + Если Calendar Тогда МассивРазрешений.Добавить("https://www.googleapis.com/auth/calendar"); КонецЕсли; - + Если Drive Тогда МассивРазрешений.Добавить("https://www.googleapis.com/auth/drive"); КонецЕсли; - + Если Sheets Тогда МассивРазрешений.Добавить("https://www.googleapis.com/auth/spreadsheets"); КонецЕсли; - + Возврат СтрСоединить(МассивРазрешений, " "); - + КонецФункции -#КонецОбласти \ No newline at end of file +#КонецОбласти diff --git a/src/ru/OPI/src/CommonModules/OPI_Notion/Module.bsl b/src/ru/OPI/src/CommonModules/OPI_Notion/Module.bsl index 65c41241bc..3a6e8e9b4f 100644 --- a/src/ru/OPI/src/CommonModules/OPI_Notion/Module.bsl +++ b/src/ru/OPI/src/CommonModules/OPI_Notion/Module.bsl @@ -1,4 +1,4 @@ -// OneScript: ./OInt/core/Modules/OPI_Notion.os +// OneScript: ./OInt/core/Modules/OPI_Notion.os // Lib: Notion // CLI: notion @@ -45,91 +45,91 @@ // Создать страницу // Создает дочернюю страницу над другой страницей-родителем -// +// // Параметры: // Токен - Строка - Токен - token // Родитель - Строка - ID Родителя - page // Заголовок - Строка - Заголовок страницы - title -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Notion Функция СоздатьСтраницу(Знач Токен, Знач Родитель, Знач Заголовок) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Родитель); OPI_ПреобразованиеТипов.ПолучитьСтроку(Заголовок); - - Заголовки = СоздатьЗаголовкиЗапроса(Токен); + + Заголовки = СоздатьЗаголовкиЗапроса(Токен); Свойства = Новый Структура; Параметры = Новый Структура; - + ДобавитьЗаголовокСтраницы(Заголовок, Свойства); ДобавитьРодителяСтраницы(Родитель, Ложь, Параметры); - + Параметры.Вставить("properties", Свойства); - + Ответ = OPI_Инструменты.Post("https://api.notion.com/v1/pages", Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Создать страницу в базу // Создает страницу в базе-родителе -// +// // Параметры: -// Токен - Строка - Токен - token +// Токен - Строка - Токен - token // Родитель - Строка - ID родительской базы - base // Данные - Соответствие Из КлючИЗначение - Соответствие свойств - data -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Notion Функция СоздатьСтраницуВБазу(Знач Токен, Знач Родитель, Знач Данные) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Родитель); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Данные); - + Заголовки = СоздатьЗаголовкиЗапроса(Токен); Параметры = Новый Структура; - + ДобавитьРодителяСтраницы(Родитель, Истина, Параметры); - Свойства = ЗаполнитьДанныеПоСхеме(Родитель, Данные, Токен); + Свойства = ЗаполнитьДанныеПоСхеме(Родитель, Данные, Токен); Параметры.Вставить("properties", Свойства); - + Ответ = OPI_Инструменты.Post("https://api.notion.com/v1/pages", Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить страницу // Получает информацию о странице по ID -// +// // Параметры: // Токен - Строка - Токен - token -// Страница - Строка - ID страницы - page -// +// Страница - Строка - ID страницы - page +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Notion Функция ПолучитьСтраницу(Знач Токен, Знач Страница) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Страница); - + Заголовки = СоздатьЗаголовкиЗапроса(Токен); - ПреобразоватьИД(Страница); - + ПреобразоватьИД(Страница); + Ответ = OPI_Инструменты.Get("https://api.notion.com/v1/pages/" + Страница, , Заголовки); - + Возврат Ответ; - + КонецФункции // Изменить свойства страницы // Изменяет свойства существующей страницы -// +// // Параметры: // Токен - Строка - Токен - token // Страница - Строка - ID изменяемой страницы - page @@ -137,7 +137,7 @@ // Иконка - Строка - URL картинки иконки страницы - icon // Обложка - Строка - URL картинки обложки страницы - cover // Архивирована - Булево - Архивировать страницу или нет (булево) - archive -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Notion Функция ИзменитьСвойстваСтраницы(Знач Токен @@ -146,36 +146,36 @@ , Знач Иконка = "" , Знач Обложка = "" , Знач Архивирована = Ложь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Страница); OPI_ПреобразованиеТипов.ПолучитьСтроку(Иконка); OPI_ПреобразованиеТипов.ПолучитьСтроку(Обложка); OPI_ПреобразованиеТипов.ПолучитьБулево(Архивирована); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Данные); - + Заголовки = СоздатьЗаголовкиЗапроса(Токен); Параметры = Новый Структура; Files = "files"; - - Если ЗначениеЗаполнено(Данные) + + Если ЗначениеЗаполнено(Данные) И (ТипЗнч(Данные) = Тип("Соответствие") Или ТипЗнч(Данные) = Тип("Структура")) Тогда - Свойства = ЗаполнитьДанныеПоСхеме(Страница, Данные, Токен, Ложь); - Иначе - Свойства = Новый Соответствие; + Свойства = ЗаполнитьДанныеПоСхеме(Страница, Данные, Токен, Ложь); + Иначе + Свойства = Новый Соответствие; КонецЕсли; - + Если ЗначениеЗаполнено(Иконка) Тогда СоответствиеИконки = Новый Соответствие; СоответствиеИконки.Вставить("Icon", Иконка); - + ОбъектИконка = ПреобразоватьЗначениеПоТипу(Files, СоответствиеИконки); ОбъектИконка = ОбъектИконка[Files][0]; ОбъектИконка.Удалить("name"); - + Параметры.Вставить("icon", ОбъектИконка); КонецЕсли; - + Если ЗначениеЗаполнено(Обложка) Тогда СоответствиеОбложки = Новый Соответствие; СоответствиеОбложки.Вставить("Cover", Обложка); @@ -189,13 +189,13 @@ Параметры.Вставить("properties", Свойства); Параметры.Вставить("archived" , Архивирована); - + ПреобразоватьИД(Страница); Ответ = OPI_Инструменты.Patch("https://api.notion.com/v1/pages/" + Страница, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -204,13 +204,13 @@ // Создать базу данных // Создает базу данных -// +// // Параметры: -// Токен - Строка - Токен - token +// Токен - Строка - Токен - token // Родитель - Строка - ID страницы родителя - page // Заголовок - Строка - Заголовок базы данных - title // Свойства - Структура Из Строка - Свойства базы данных - props -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Notion Функция СоздатьБазуДанных(Знач Токен, Знач Родитель, Знач Заголовок, Знач Свойства = "") Экспорт @@ -219,273 +219,273 @@ OPI_ПреобразованиеТипов.ПолучитьСтроку(Родитель); OPI_ПреобразованиеТипов.ПолучитьСтроку(Заголовок); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Свойства); - + // Пример структуры/соответствия свойств - + // Имя : title // Описание : rich_text - // В работе : checkbox + // В работе : checkbox // Количество : number // Дата : date // Статус : Соответствие // Активный : green // Неактивный : red // Архив : yellow - + // Все страницы, которые будут созданы как дочерние, должны иметь свойства базы-родителя Если Не ТипЗнч(Свойства) = Тип("Структура") И Не ТипЗнч(Свойства) = Тип("Соответствие") Тогда - Свойства = Новый Структура("Наименование", "title"); + Свойства = Новый Структура("Наименование", "title"); КонецЕсли; - Заголовки = СоздатьЗаголовкиЗапроса(Токен); + Заголовки = СоздатьЗаголовкиЗапроса(Токен); Параметры = Новый Структура; - + ДобавитьРодителяБазы(Родитель, Ложь, Параметры); ДобавитьЗаголовокБазы(Заголовок, Параметры); ДобавитьСвойстваБазы(Свойства, Параметры); Ответ = OPI_Инструменты.Post("https://api.notion.com/v1/databases", Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить базу данных // Получить данные о базе данных -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - ID базы данных - base -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Notion Функция ПолучитьБазуДанных(Знач Токен, Знач База) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(База); - + Заголовки = СоздатьЗаголовкиЗапроса(Токен); - ПреобразоватьИД(База); - + ПреобразоватьИД(База); + Ответ = OPI_Инструменты.Get("https://api.notion.com/v1/databases/" + База, , Заголовки); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции // Изменить свойства базы // Изменяет свойства существующей базы -// +// // Параметры: // Токен - Строка - Токен - token // База - Строка - ID целевой базы - base // Свойства - Соответствие из КлючИЗначение - Новые или изменяемые свойства базы данных - props // Заголовок - Строка - Новый заголовок базы - title // Описание - Строка - Новое описание базы - description -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Notion Функция ИзменитьСвойстваБазы(Знач Токен, Знач База, Знач Свойства = "", Знач Заголовок = "", Знач Описание = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(База); OPI_ПреобразованиеТипов.ПолучитьСтроку(Заголовок); OPI_ПреобразованиеТипов.ПолучитьСтроку(Описание); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Свойства); - + Параметры = Новый Структура; - Заголовки = СоздатьЗаголовкиЗапроса(Токен); - ПреобразоватьИД(База); - + Заголовки = СоздатьЗаголовкиЗапроса(Токен); + ПреобразоватьИД(База); + Если ЗначениеЗаполнено(Заголовок) Тогда ДобавитьЗаголовокБазы(Заголовок, Параметры); КонецЕсли; - + Если ЗначениеЗаполнено(Описание) Тогда ДобавитьОписаниеБазы(Описание, Параметры); КонецЕсли; - + Если ТипЗнч(Свойства) = Тип("Структура") Или ТипЗнч(Свойства) = Тип("Соответствие") Тогда ДобавитьСвойстваБазы(Свойства, Параметры); КонецЕсли; - + Ответ = OPI_Инструменты.Patch("https://api.notion.com/v1/databases/" + База, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции -#КонецОбласти +#КонецОбласти #Область РаботаСБлоками // Создать блок // Создает новый блок на основе существующего блока -// +// // Параметры: // Токен - Строка - Токен - token // Родитель - Строка - ID родительского блока или страницы - page // Блок - Строка,Соответствие Из КлючИЗначение - ID блока или сам блок образец - block // ВставитьПосле - Строка - ID блока, после которого необходимо встаивть новый - prev -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Notion Функция СоздатьБлок(Знач Токен, Знач Родитель, Знач Блок, Знач ВставитьПосле = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Родитель); OPI_ПреобразованиеТипов.ПолучитьСтроку(ВставитьПосле); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Блок); - + Если ТипЗнч(Блок) = Тип("Массив") Тогда - Блок = Блок[0]; + Блок = Блок[0]; КонецЕсли; - - Заголовки = СоздатьЗаголовкиЗапроса(Токен); + + Заголовки = СоздатьЗаголовкиЗапроса(Токен); ПреобразоватьИД(Родитель); - + Если ТипЗнч(Блок) = Тип("Строка") Тогда ПреобразоватьИД(Блок); - Блок = ВернутьБлок(Токен, Блок); + Блок = ВернутьБлок(Токен, Блок); КонецЕсли; - + МассивБлоков = Новый Массив; МассивБлоков.Добавить(Блок); - + Параметры = Новый Соответствие; Параметры.Вставить("children", МассивБлоков); - + Если ЗначениеЗаполнено(ВставитьПосле) Тогда Параметры.Вставить("after", ВставитьПосле); КонецЕсли; - + URL = "https://api.notion.com/v1/blocks/" + Родитель + "/children"; Ответ = OPI_Инструменты.Patch(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Вернуть блок // Возвращает структуру блока по ID -// +// // Параметры: // Токен - Строка - Токен - token // ИДБлока - Строка - ID блока - block // ТолькоОснова - Булево - Истина > служебные поля удаляются, остается только сам блок - core -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Notion Функция ВернутьБлок(Знач Токен, Знач ИДБлока, Знач ТолькоОснова = Истина) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(ИДБлока); OPI_ПреобразованиеТипов.ПолучитьБулево(ТолькоОснова); - + ПреобразоватьИД(ИДБлока); - + Заголовки = СоздатьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Get("https://api.notion.com/v1/blocks/" + ИДБлока, , Заголовки); - + Если ТолькоОснова Тогда - УдалитьЛишниеПоляБлока(Ответ); + УдалитьЛишниеПоляБлока(Ответ); КонецЕсли; - + Возврат Ответ; - + КонецФункции // Вернуть дочерние блоки // Созвращает список дочерних блоков блока-родителя -// +// // Параметры: // Токен - Строка - Токен - token // ИДБлока - Строка - ID блока родителя - block -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Notion Функция ВернутьДочерниеБлоки(Знач Токен, Знач ИДБлока) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(ИДБлока); - + ПреобразоватьИД(ИДБлока); - + Заголовки = СоздатьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Get("https://api.notion.com/v1/blocks/" + ИДБлока + "/children", , Заголовки); - + Возврат Ответ; - + КонецФункции // Удалить блок // Удаляет блок по ID -// +// // Параметры: // Токен - Строка - Токен - token // ИДБлока - Строка - ID блока - block -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Notion Функция УдалитьБлок(Знач Токен, Знач ИДБлока) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(ИДБлока); - + ПреобразоватьИД(ИДБлока); - + Заголовки = СоздатьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Delete("https://api.notion.com/v1/blocks/" + ИДБлока, , Заголовки); - + Возврат Ответ; - + КонецФункции - + #КонецОбласти #Область Пользователи // Список пользователей // Возвращает список пользователей рабочего пространства -// +// // Параметры: // Токен - Строка - Токен - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Notion Функция СписокПользователей(Знач Токен) Экспорт OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Заголовки = СоздатьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Get("https://api.notion.com/v1/users", , Заголовки); - + Возврат Ответ; - + КонецФункции // Получить данные пользователя // Получает данные пользователя по ID -// +// // Параметры: // Токен - Строка - Токен - token // ИДПользователя - Строка - ID целевого пользователя - user -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Notion Функция ПолучитьДанныеПользователя(Знач Токен, Знач ИДПользователя) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(ИДПользователя); - + ПреобразоватьИД(ИДПользователя); - + Заголовки = СоздатьЗаголовкиЗапроса(Токен); Ответ = OPI_Инструменты.Get("https://api.notion.com/v1/users/" + ИДПользователя, , Заголовки); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -495,183 +495,183 @@ #Область СлужебныеПроцедурыИФункции Функция СоздатьЗаголовкиЗапроса(Знач Токен) - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Заголовки = Новый Соответствие; Заголовки.Вставить("Authorization" , "Bearer " + Токен); Заголовки.Вставить("Notion-Version", "2022-06-28"); - + Возврат Заголовки; - + КонецФункции Процедура ПреобразоватьИД(Идентификатор) - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Идентификатор); - + Идентификатор = СтрЗаменить(Идентификатор, "-", ""); - + КонецПроцедуры Процедура ДобавитьРодителяСтраницы(Знач Родитель, Знач РодительБаза, ОсновнаяСтруктура) - + OPI_ПреобразованиеТипов.ПолучитьСтроку(РодительБаза); - + ПреобразоватьИД(Родитель); - + ПолеИдентификатора = ?(РодительБаза, "database_id", "page_id"); СтруктураРодителя = Новый Структура(ПолеИдентификатора, Родитель); ОсновнаяСтруктура.Вставить("parent", СтруктураРодителя); - + КонецПроцедуры Процедура ДобавитьРодителяБазы(Знач Родитель, Знач РодительБаза, ОсновнаяСтруктура) - + OPI_ПреобразованиеТипов.ПолучитьСтроку(РодительБаза); - + ПреобразоватьИД(Родитель); - + ПолеИдентификатора = ?(РодительБаза, "database_id", "page_id"); - + СтруктураРодителя = Новый Структура(); СтруктураРодителя.Вставить("type" , ПолеИдентификатора); СтруктураРодителя.Вставить(ПолеИдентификатора, Родитель); ОсновнаяСтруктура.Вставить("parent", СтруктураРодителя); - + КонецПроцедуры -Процедура ДобавитьЗаголовокСтраницы(Знач Заголовок, ОсновнаяСтруктура) - +Процедура ДобавитьЗаголовокСтраницы(Знач Заголовок, ОсновнаяСтруктура) + OPI_ПреобразованиеТипов.ПолучитьСтроку(Заголовок); - + ПодчиненнаяСтруктура = Новый Структура; СтруктураДанных = Новый Структура; СтруктураТекста = Новый Структура; МассивДанных = Новый Массив; Title = "title"; - + СтруктураТекста.Вставить("content", Заголовок); СтруктураТекста.Вставить("link" , Неопределено); - + СтруктураДанных.Вставить("text", СтруктураТекста); СтруктураДанных.Вставить("type", "text"); - + МассивДанных.Добавить(СтруктураДанных); - + ПодчиненнаяСтруктура.Вставить("id" , Title); ПодчиненнаяСтруктура.Вставить("type" , Title); ПодчиненнаяСтруктура.Вставить(Title , МассивДанных); - + ОсновнаяСтруктура.Вставить(Title, ПодчиненнаяСтруктура); - + КонецПроцедуры Процедура ДобавитьЗаголовокБазы(Знач Заголовок, ОсновнаяСтруктура) - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Заголовок); - - Заголовок = ПреобразоватьЗаголовок(Заголовок); + + Заголовок = ПреобразоватьЗаголовок(Заголовок); ОсновнаяСтруктура.Вставить("title", Заголовок["title"]); - + КонецПроцедуры Процедура ДобавитьОписаниеБазы(Знач Описание, ОсновнаяСтруктура) - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Описание); - - Заголовок = ПреобразоватьЗаголовок(Описание); + + Заголовок = ПреобразоватьЗаголовок(Описание); ОсновнаяСтруктура.Вставить("description", Заголовок["title"]); - + КонецПроцедуры Процедура ДобавитьСвойстваБазы(Знач Свойства, ОсновнаяСтруктура) - + Если Свойства.Количество() = 0 Тогда ОсновнаяСтруктура.Вставить("properties", Новый Структура); - Возврат; + Возврат; КонецЕсли; - + СоответствиеПараметров = Новый Соответствие; - + Для Каждого Свойство Из Свойства Цикл - + Если ТипЗнч(Свойство.Значение) = Тип("Строка") Тогда - + СоответствиеПараметров.Вставить(Свойство.Ключ, Новый Структура(Свойство.Значение, Новый Структура)); - - ИначеЕсли ТипЗнч(Свойство.Значение) = Тип("Структура") - Или ТипЗнч(Свойство.Значение) = Тип("Соответствие") Тогда - + + ИначеЕсли ТипЗнч(Свойство.Значение) = Тип("Структура") + Или ТипЗнч(Свойство.Значение) = Тип("Соответствие") Тогда + ВыборЗначения = СформироватьЗначенияВыбора(Свойство.Значение); СоответствиеПараметров.Вставить(Свойство.Ключ, Новый Структура("select", ВыборЗначения)); - + Иначе - + СоответствиеПараметров.Вставить(Свойство.Ключ, Свойство.Значение); - + КонецЕсли; - + КонецЦикла; - + ОсновнаяСтруктура.Вставить("properties", СоответствиеПараметров); - + КонецПроцедуры Функция СформироватьЗначенияВыбора(Знач СтруктураВариантов) - + МассивВариантов = Новый Массив; - + Для Каждого Вариант Из СтруктураВариантов Цикл - + СоответствиеВарианта = Новый Соответствие; СоответствиеВарианта.Вставить("name" , Вариант.Ключ); СоответствиеВарианта.Вставить("color", Вариант.Значение); - + МассивВариантов.Добавить(СоответствиеВарианта); - + КонецЦикла; - + Возврат Новый Структура("options", МассивВариантов); - + КонецФункции Функция ЗаполнитьДанныеПоСхеме(Знач Схема, Знач Данные, Знач Токен, Знач ЭтоБаза = Истина) - + Если ЭтоБаза Тогда ДанныеСхемы = ПолучитьБазуДанных(Токен, Схема); Иначе - ДанныеСхемы = ПолучитьСтраницу(Токен, Схема); + ДанныеСхемы = ПолучитьСтраницу(Токен, Схема); КонецЕсли; - + ПоляБазы = ДанныеСхемы["properties"]; Свойства = Новый Соответствие; - + Если ЗначениеЗаполнено(ПоляБазы) Тогда - + Для Каждого Поле Из ПоляБазы Цикл - + ДанныеПоля = Поле.Значение; ТипПоля = ДанныеПоля["type"]; - + ЗаполняемыеДанные = Данные.Получить(Поле.Ключ); - + Если ЗаполняемыеДанные = Неопределено Тогда Продолжить; КонецЕсли; - + ПреобразованныеДанные = ПреобразоватьЗначениеПоТипу(ТипПоля, ЗаполняемыеДанные); - + Если ПреобразованныеДанные = Неопределено Тогда Продолжить; КонецЕсли; - - Свойства.Вставить(ДанныеПоля["id"], ПреобразованныеДанные); - + + Свойства.Вставить(ДанныеПоля["id"], ПреобразованныеДанные); + КонецЦикла; - + КонецЕсли; Возврат Свойства; @@ -679,7 +679,7 @@ КонецФункции Процедура УдалитьЛишниеПоляБлока(Знач Блок) - + МассивЛишних = Новый Массив; МассивЛишних.Добавить("request_id"); МассивЛишних.Добавить("archived"); @@ -690,22 +690,22 @@ МассивЛишних.Добавить("parrent"); МассивЛишних.Добавить("last_edited_by"); МассивЛишних.Добавить("id"); - + Для Каждого Поле Из МассивЛишних Цикл - + Если Не Блок.Получить(Поле) = Неопределено Тогда Блок.Удалить(Поле); КонецЕсли; - + КонецЦикла; - + КонецПроцедуры #Область ПреобразованиеТипов Функция ПреобразоватьЗначениеПоТипу(Знач Тип, Знач Значение) - - Если Тип = "title" Тогда + + Если Тип = "title" Тогда Возврат ПреобразоватьЗаголовок(Значение); ИначеЕсли Тип = "rich_text" Тогда Возврат ПреобразоватьТекст(Значение); @@ -733,42 +733,42 @@ Возврат ПреобразоватьПочту(Значение); ИначеЕсли Тип = "phone_number" Тогда Возврат ПреобразоватьТелефон(Значение); - Иначе + Иначе Возврат Неопределено; КонецЕсли; - + КонецФункции -Функция ПреобразоватьЗаголовок(Знач Заголовок) - +Функция ПреобразоватьЗаголовок(Знач Заголовок) + СтруктураДанных = Новый Структура; СтруктураТекста = Новый Структура; МассивДанных = Новый Массив; - + СтруктураТекста.Вставить("content", Заголовок); СтруктураТекста.Вставить("link" , Неопределено); - + СтруктураДанных.Вставить("type", "text"); СтруктураДанных.Вставить("text", СтруктураТекста); - + МассивДанных.Добавить(СтруктураДанных); Возврат Новый Структура("title", МассивДанных); - + КонецФункции Функция ПреобразоватьТекст(Знач Текст) - + МассивТекста = Новый Массив; СтруктураТекста = Новый Структура; - + СтруктураТекста.Вставить("type", "text"); СтруктураТекста.Вставить("text", Новый Структура("content", Текст)); - + МассивТекста.Добавить(СтруктураТекста); - + Возврат Новый Структура("rich_text", МассивТекста); - + КонецФункции Функция ПреобразоватьЧисло(Знач Число) @@ -776,101 +776,101 @@ КонецФункции Функция ПреобразоватьВариантВыбора(Знач Вариант) - + СтруктураВыбора = Новый Структура; СтруктураВыбора.Вставить("select", Новый Структура("name", Вариант)); - + Возврат СтруктураВыбора; - + КонецФункции Функция ПреобразоватьСтатус(Знач Статус) - + СтруктураСтатуса = Новый Структура; СтруктураСтатуса.Вставить("status", Новый Структура("name", Статус)); - + Возврат СтруктураСтатуса; - + КонецФункции Функция ПреобразоватьМножественныйВыбор(Знач МассивВариантов) - + МассивВариантовВыбора = Новый Массив; - + Для Каждого Вариант Из МассивВариантов Цикл МассивВариантовВыбора.Добавить(Новый Структура("name", Вариант)); КонецЦикла; - + Возврат Новый Структура("multi_select", МассивВариантовВыбора); - + КонецФункции Функция ПреобразоватьДату(Знач Дата) - + СтруктураДаты = Новый Структура; - - Если Дата = НачалоДня(Дата) Тогда + + Если Дата = НачалоДня(Дата) Тогда ФорматДаты = "ДФ=yyyy-MM-dd"; Иначе ФорматДаты = "ДФ=yyyy-MM-ddThh:mm:ssZ"; КонецЕсли; - + Дата = Формат(Дата, ФорматДаты); СтруктураДаты.Вставить("start", Дата); - + Возврат Новый Структура("date", СтруктураДаты); - + КонецФункции -Функция ПреобразоватьСвязь(Знач Идентификатор) - +Функция ПреобразоватьСвязь(Знач Идентификатор) + МассивСвязи = Новый Массив; МассивСвязи.Добавить(Новый Структура("id", Идентификатор)); - + Возврат Новый Структура("relation", МассивСвязи); - + КонецФункции Функция ПреобразоватьПользователей(Знач МассивИД) - + Если Не ТипЗнч(МассивИД) = Тип("Массив") Тогда - МассивИД_ = Новый Массив; + МассивИД_ = Новый Массив; МассивИД_.Добавить(МассивИД); - МассивИД = МассивИД_; + МассивИД = МассивИД_; КонецЕсли; - + МассивПользователей = Новый Массив; - + Для Каждого Идентификатор Из МассивИД Цикл - + СтруктураПользователя = Новый Структура; СтруктураПользователя.Вставить("object", "user"); СтруктураПользователя.Вставить("id" , Идентификатор); МассивПользователей.Добавить(СтруктураПользователя); - + КонецЦикла; - + Возврат Новый Структура("people", МассивПользователей); - + КонецФункции Функция ПреобразоватьФайлы(Знач СоответствиеФайлов) - + МассивФайлов = Новый Массив; - + Для Каждого Файл Из СоответствиеФайлов Цикл - + СтруктураФайла = Новый Структура; СтруктураФайла.Вставить("type" , "external"); СтруктураФайла.Вставить("name" , Файл.Ключ); СтруктураФайла.Вставить("external", Новый Структура("url", Файл.Значение)); - + МассивФайлов.Добавить(СтруктураФайла); - + КонецЦикла; Возврат Новый Структура("files", МассивФайлов); - + КонецФункции Функция ПреобразоватьБулево(Знач Булево) @@ -891,4 +891,4 @@ #КонецОбласти -#КонецОбласти \ No newline at end of file +#КонецОбласти diff --git a/src/ru/OPI/src/CommonModules/OPI_Slack/Module.bsl b/src/ru/OPI/src/CommonModules/OPI_Slack/Module.bsl index 47703c6622..c63173be3b 100644 --- a/src/ru/OPI/src/CommonModules/OPI_Slack/Module.bsl +++ b/src/ru/OPI/src/CommonModules/OPI_Slack/Module.bsl @@ -1,4 +1,4 @@ -// OneScript: ./OInt/core/Modules/OPI_Slack.os +// OneScript: ./OInt/core/Modules/OPI_Slack.os // Lib: Slack // CLI: slack @@ -43,57 +43,57 @@ // Получить информацию о боте // Получает основную информацию о боте -// +// // Параметры: // Токен - Строка - Токен бота - token -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьИнформациюОБоте(Знач Токен) Экспорт - + URL = "https://slack.com/api/auth.test"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Ответ = OPI_Инструменты.Get(URL, , Заголовки); - + Возврат Ответ; КонецФункции // Получить список рабочих областей // Получает список рабочих областей, в которых подключен бот -// +// // Параметры: // Токен - Строка - Токен бота - token // Курсор - Строка - Указатель из предыдущего запроса, если строк результата > 100 - cursor -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьСписокРабочихОбластей(Знач Токен, Знач Курсор = "") Экспорт - + URL = "https://slack.com/api/auth.teams.list"; Ответ = ПолучениеОбщихДанных(Токен, URL, Курсор); - + Возврат Ответ; КонецФункции // Получить список пользователей // Получает список пользователей рабочей области -// +// // Параметры: // Токен - Строка - Токен бота - token // Курсор - Строка - Указатель из предыдущего запроса, если строк результата > 100 - cursor -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьСписокПользователей(Знач Токен, Знач Курсор = "") Экспорт - + URL = "https://slack.com/api/users.list"; Ответ = ПолучениеОбщихДанных(Токен, URL, Курсор); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -102,68 +102,68 @@ // Отправить сообщение // Отправляет сообщение в выбранный час -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - Идентификатор канала - channel // Текст - Строка - Текст сообщения - text -// ДатаОтправки - Дата - Дата отправки для отложенного сообщения - date +// ДатаОтправки - Дата - Дата отправки для отложенного сообщения - date // Блоки - Массив Из Структура - Массив описаний блоков - blocks - JSON массива описаний блоков -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ОтправитьСообщение(Знач Токен, Знач Канал, Знач Текст = "", Знач ДатаОтправки = "", Знач Блоки = "") Экспорт - + Строка_ = "Строка"; - ЕстьДата = ЗначениеЗаполнено(ДатаОтправки); + ЕстьДата = ЗначениеЗаполнено(ДатаОтправки); Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Если ЗначениеЗаполнено(Блоки) И ТипЗнч(Блоки) = Тип(Строка_) Тогда OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Блоки); - + Если ТипЗнч(Блоки) = Тип("Массив") Тогда - + Для Н = 0 По Блоки.ВГраница() Цикл - OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Блоки[Н]); + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Блоки[Н]); КонецЦикла; - + КонецЕсли; КонецЕсли; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал, Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("text" , Текст, Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("blocks" , Блоки, "Массив" , Параметры); Если ЕстьДата Тогда - + URL = "https://slack.com/api/chat.scheduleMessage"; - OPI_Инструменты.ДобавитьПоле("post_at", ДатаОтправки, "Дата", Параметры); - + OPI_Инструменты.ДобавитьПоле("post_at", ДатаОтправки, "Дата", Параметры); + Иначе - + URL = "https://slack.com/api/chat.postMessage"; - + КонецЕсли; - + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Отправить эфемерное сообщение -// Отправляет сообщение, которое приходит в канал, но видно +// Отправляет сообщение, которое приходит в канал, но видно // только конкретному пользователю -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - Идентификатор канала - channel // Текст - Строка - Текст сообщения - text -// Пользователь - Строка - ID пользователя - user +// Пользователь - Строка - ID пользователя - user // Блоки - Массив Из Структура - Массив описаний блоков - blocks - JSON массива описаний блоков -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ОтправитьЭфемерноеСообщение(Знач Токен @@ -171,168 +171,168 @@ , Знач Текст = "" , Знач Пользователь = "" , Знач Блоки = "") Экспорт - + Строка_ = "Строка"; - + Если ЗначениеЗаполнено(Блоки) И Не ТипЗнч(Блоки) = Тип(Строка_) Тогда OPI_ПреобразованиеТипов.ПолучитьМассив(Блоки); КонецЕсли; - + Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("text" , Текст , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("user" , Пользователь, Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("blocks" , Блоки , "Коллекция", Параметры); - + URL = "https://slack.com/api/chat.postEphemeral"; - + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Изменить сообщение // Изменяет состав существующего сообщения -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - Идентификатор канала - channel // Отметка - Строка - Временная отметка сообщения - stamp // Текст - Строка - Новый текст сообщения - text // МассивБлоков - Массив Из Структура - Массив описаний блоков - blocks - JSON массива описаний блоков -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ИзменитьСообщение(Знач Токен, Знач Канал, Знач Отметка, Знач Текст = "", Знач МассивБлоков = "") Экспорт - + Строка_ = "Строка"; URL = "https://slack.com/api/chat.update"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("text" , Текст , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("ts" , Отметка , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("blocks" , МассивБлоков, "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Удалить сообщение // Удаляет сообщение канала по timestamp -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - Идентификатор канала - channel // Отметка - Строка - Временная отметка или ID сообщения - stamp // ЭтоОтложенное - Булево - Признак удаления отложенного сообщения - issheduled -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция УдалитьСообщение(Знач Токен, Знач Канал, Знач Отметка, Знач ЭтоОтложенное = Ложь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьБулево(ЭтоОтложенное); - + Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Если ЭтоОтложенное Тогда URL = "https://slack.com/api/chat.deleteScheduledMessage"; - ПолеОтметки = "scheduled_message_id"; + ПолеОтметки = "scheduled_message_id"; Иначе URL = "https://slack.com/api/chat.delete"; ПолеОтметки = "ts"; КонецЕсли; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel" , Канал , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле(ПолеОтметки, Отметка, "Строка", Параметры); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Получить список отложенных сообщений // Получает список отложенных сообщений канала -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - Идентификатор канала - channel // Курсор - Строка - Указатель из предыдущего запроса, если строк результата > 100 - cursor -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьСписокОтложенныхСообщений(Знач Токен, Знач Канал, Знач Курсор = "") Экспорт - + URL = "https://slack.com/api/chat.scheduledMessages.list"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("cursor" , Курсор, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Получить ссылку на сообщение // Получает постоянный UTL к сообщению канала -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - Идентификатор канала - channel // Отметка - Строка - Временная отметка или ID сообщения - stamp -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьСсылкуНаСообщение(Знач Токен, Знач Канал, Знач Отметка) Экспорт - + URL = "https://slack.com/api/chat.getPermalink"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel" , Канал , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("message_ts", Отметка, "Строка", Параметры); Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Получить список ответов на сообщение // Получает массив сообщений, которые являются ответом на указанное -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - Идентификатор канала - channel // Отметка - Строка - Временная отметка или ID сообщения - stamp // Курсор - Строка - Указатель из предыдущего запроса, если строк результата > 100 - cursor -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьСписокОтветовНаСообщение(Знач Токен, Знач Канал, Знач Отметка, Знач Курсор = "") Экспорт - + Строка_ = "Строка"; URL = "https://slack.com/api/conversations.replies"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("cursor" , Курсор , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("ts" , Отметка, Строка_, Параметры); - + Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции @@ -343,107 +343,107 @@ // Получить список каналов // Получает список доступных каналов -// +// // Параметры: // Токен - Строка - Токен бота - token -// ИсключатьАрхивированные - Булево - Признак исключения архивированных каналов - notarchived +// ИсключатьАрхивированные - Булево - Признак исключения архивированных каналов - notarchived // Курсор - Строка - Указатель из предыдущего запроса, если строк результата > 100 - cursor -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьСписокКаналов(Знач Токен, Знач ИсключатьАрхивированные = Ложь, Знач Курсор = "") Экспорт - + URL = "https://slack.com/api/conversations.list"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("exclude_archived", ИсключатьАрхивированные, "Булево", Параметры); OPI_Инструменты.ДобавитьПоле("cursor" , Курсор , "Строка", Параметры); Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить список пользователей канала // Получает список пользователей указанного канала -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - Идентификатор канала - channel // Курсор - Строка - Указатель из предыдущего запроса, если строк результата > 100 - cursor -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьСписокПользователейКанала(Знач Токен, Знач Канал, Знач Курсор = "") Экспорт - + URL = "https://slack.com/api/conversations.members"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("cursor" , Курсор, "Строка", Параметры); Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Создать канал // Создает новый канал -// +// // Параметры: // Токен - Строка - Токен бота - token // Название - Строка - Наименование канала - title // Приватный - Булево - Создать канал приватным - private -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция СоздатьКанал(Знач Токен, Знач Название, Знач Приватный = Ложь) Экспорт - + URL = "https://slack.com/api/conversations.create"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("name" , Название , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("is_private", Приватный, "Булево", Параметры); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Архивировать канал // Архивирует активный канал -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - ID канала - channel -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция АрхивироватьКанал(Знач Токен, Знач Канал) Экспорт - + URL = "https://slack.com/api/conversations.archive"; Ответ = УправлениеДиалогом(Токен, Канал, URL); Возврат Ответ; - + КонецФункции // Получить канал // Получает информацию о канале -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - ID канала - channel -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьКанал(Знач Токен, Знач Канал) Экспорт - + URL = "https://slack.com/api/conversations.info"; Ответ = УправлениеДиалогом(Токен, Канал, URL, "GET"); Возврат Ответ; @@ -452,15 +452,15 @@ // Получить историю канала // Получает информацию событиях канала -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - ID канала - channel -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьИсториюКанала(Знач Токен, Знач Канал) Экспорт - + URL = "https://slack.com/api/conversations.history"; Ответ = УправлениеДиалогом(Токен, Канал, URL, "GET"); Возврат Ответ; @@ -469,68 +469,68 @@ // Пригласить пользователей в канал // Добавляет указанных пользователей в канал -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - ID канала - channel // МассивПользователей - Массив Из Строка - Массив ID пользователей - users -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПригласитьПользователейВКанал(Знач Токен, Знач Канал, Знач МассивПользователей) Экспорт - + URL = "https://slack.com/api/conversations.invite"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивПользователей); МассивПользователей = СтрСоединить(МассивПользователей, ","); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("users" , МассивПользователей, "Строка", Параметры); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Выгнать пользователя из канала // Удаляет указанного пользователя из канала -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - ID канала - channel // Пользователь - Строка - ID пользователя - user -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ВыгнатьПользователяИзКанала(Знач Токен, Знач Канал, Знач Пользователь) Экспорт - + URL = "https://slack.com/api/conversations.kick"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("user" , Пользователь, "Строка", Параметры); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Вступить в канал // Добавляет текущего бота в канал -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - ID канала - channel -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ВступитьВКанал(Знач Токен, Знач Канал) Экспорт - + URL = "https://slack.com/api/conversations.join"; Ответ = УправлениеДиалогом(Токен, Канал, URL); Возврат Ответ; @@ -539,15 +539,15 @@ // Покинуть канал // Удаляет текущего бота из канала -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - ID канала - channel -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПокинутьКанал(Знач Токен, Знач Канал) Экспорт - + URL = "https://slack.com/api/conversations.leave"; Ответ = УправлениеДиалогом(Токен, Канал, URL); Возврат Ответ; @@ -556,75 +556,75 @@ // Установить тему канала // Устанавливает тему канала -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - ID канала - channel // Тема - Строка - Тема канала - theme -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция УстановитьТемуКанала(Знач Токен, Знач Канал, Знач Тема) Экспорт - + URL = "https://slack.com/api/conversations.setTopic"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("topic" , Тема , "Строка", Параметры); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Установить цель канала // Устанавливает цель (описание) канала -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - ID канала - channel // Цель - Строка - Цель канала - purpose -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция УстановитьЦельКанала(Знач Токен, Знач Канал, Знач Цель) Экспорт - + URL = "https://slack.com/api/conversations.setPurpose"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("purpose", Цель , "Строка", Параметры); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Переименовать канал // Изменяет название канала -// +// // Параметры: // Токен - Строка - Токен бота - token // Канал - Строка - ID канала - channel // Название - Строка - Новое название канала - title -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПереименоватьКанал(Знач Токен, Знач Канал, Знач Название) Экспорт - + URL = "https://slack.com/api/conversations.rename"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("name" , Название, "Строка", Параметры); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции @@ -635,45 +635,45 @@ // Открыть диалог // Открывает новый диалог с одним или несколькими пользователями -// +// // Параметры: // Токен - Строка - Токен бота - token // МассивПользователей - Массив из Строка - Массив ID пользователей - users -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ОткрытьДиалог(Знач Токен, Знач МассивПользователей) Экспорт - + URL = "https://slack.com/api/conversations.open"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивПользователей); МассивПользователей = СтрСоединить(МассивПользователей, ","); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("users", МассивПользователей, "Строка", Параметры); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Закрыть диалог // Закрывает существующий диалог -// +// // Параметры: // Токен - Строка - Токен бота - token // Диалог - Строка - ID диалога - conv -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ЗакрытьДиалог(Знач Токен, Знач Диалог) Экспорт - + URL = "https://slack.com/api/conversations.close"; Ответ = УправлениеДиалогом(Токен, Диалог, URL); Возврат Ответ; - + КонецФункции #КонецОбласти @@ -682,54 +682,54 @@ // Получить список файлов // Получает список файлов бота или канала -// +// // Параметры: // Токен - Строка - Токен бота - token -// Канал - Строка - Канал для отбора - channel +// Канал - Строка - Канал для отбора - channel // НомерСтраницы - Число, Строка - Номер страницы - page -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьСписокФайлов(Знач Токен, Знач Канал = "", Знач НомерСтраницы = 1) Экспорт - + URL = "https://slack.com/api/files.list"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("page" , НомерСтраницы, "Строка", Параметры); Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Загрузить файл // Загружает файл на сервера Slack -// +// // Параметры: // Токен - Строка - Токен бота - token // Файл - Строка,ДвоичныеДанные - Файл для загрузки - file // ИмяФайла - Строка - Имя файла с расширением - filename // Заголовок - Строка - Имя файла в Slack - title // Канал - Строка - ID канала - channel -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ЗагрузитьФайл(Знач Токен, Знач Файл, Знач ИмяФайла, Знач Заголовок, Знач Канал = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Файл); OPI_ПреобразованиеТипов.ПолучитьСтроку(ИмяФайла); OPI_ПреобразованиеТипов.ПолучитьСтроку(Заголовок); - + Строка_ = "Строка"; Upload_url = "upload_url"; File_id = "file_id"; URL = "https://slack.com/api/files.getUploadURLExternal"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); Размер = Файл.Размер(); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("filename", ИмяФайла, Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("length" , Размер , Строка_, Параметры); @@ -737,99 +737,99 @@ Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); URL = Ответ[Upload_url]; Идентификатор = Ответ[File_id]; - + Если Не ЗначениеЗаполнено(URL) Или Не ЗначениеЗаполнено(Идентификатор) Тогда Возврат Ответ; КонецЕсли; - + Файлы = Новый Соответствие; Файлы.Вставить(ИмяФайла, Файл); - + Ответ = OPI_Инструменты.PostMultipart(URL, , Файлы, , Заголовки); - URL = "https://slack.com/api/files.completeUploadExternal"; - ФайлСлак = Новый Структура("id, title", Идентификатор, Заголовок); - + URL = "https://slack.com/api/files.completeUploadExternal"; + ФайлСлак = Новый Структура("id, title", Идентификатор, Заголовок); + Параметры = Новый Структура; - OPI_Инструменты.ДобавитьПоле("filename" , ИмяФайла, Строка_, Параметры); - OPI_Инструменты.ДобавитьПоле("channel_id", Канал , Строка_, Параметры); + OPI_Инструменты.ДобавитьПоле("filename" , ИмяФайла, Строка_ , Параметры); + OPI_Инструменты.ДобавитьПоле("channel_id", Канал , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("files" , ФайлСлак, "Массив", Параметры); Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить данные файла // Получает информацию о файле -// +// // Параметры: // Токен - Строка - Токен бота - token // ИдентификаторФайла - Строка - Идентификатор файла - fileid -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьДанныеФайла(Знач Токен, Знач ИдентификаторФайла) Экспорт - + URL = "https://slack.com/api/files.info"; Ответ = УправлениеФайлом(Токен, ИдентификаторФайла, URL, "GET"); - + Возврат Ответ; - + КонецФункции // Удалить файл // Удаляет файл на Slack -// +// // Параметры: // Токен - Строка - Токен бота - token // ИдентификаторФайла - Строка - Идентификатор файла - fileid -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция УдалитьФайл(Знач Токен, Знач ИдентификаторФайла) Экспорт - + URL = "https://slack.com/api/files.delete"; Ответ = УправлениеФайлом(Токен, ИдентификаторФайла, URL); - + Возврат Ответ; - + КонецФункции // Сделать файл публичным // Создает публичный URL для файла. Требует токен пользователя -// +// // Параметры: // Токен - Строка - Токен пользователя - token // ИдентификаторФайла - Строка - Идентификатор файла - fileid -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция СделатьФайлПубличным(Знач Токен, Знач ИдентификаторФайла) Экспорт - + URL = "https://slack.com/api/files.sharedPublicURL"; Ответ = УправлениеФайлом(Токен, ИдентификаторФайла, URL); - + Возврат Ответ; - + КонецФункции // Сделать файл приватным // Удаляет публичный URL у файла. Требует токен пользователя -// +// // Параметры: // Токен - Строка - Токен пользователя - token // ИдентификаторФайла - Строка - Идентификатор файла - fileid -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция СделатьФайлПриватным(Знач Токен, Знач ИдентификаторФайла) Экспорт - + URL = "https://slack.com/api/files.revokePublicURL"; Ответ = УправлениеФайлом(Токен, ИдентификаторФайла, URL); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -838,119 +838,119 @@ // Получить список внешних файлов // Получает список внешних файлов пользователя или канала -// +// // Параметры: // Токен - Строка - Токен бота - token -// Канал - Строка - Канал для отбора - channel +// Канал - Строка - Канал для отбора - channel // Курсор - Строка - Указатель из предыдущего запроса, если строк результата > 100 - cursor -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьСписокВнешнихФайлов(Знач Токен, Знач Канал = "", Знач Курсор = "") Экспорт - + URL = "https://slack.com/api/files.remote.list"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("cursor" , Курсор, "Строка", Параметры); Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить внешний файл // Получает информацию о внешнем файле -// +// // Параметры: // Токен - Строка - Токен бота - token // ИдентификаторФайла - Строка - Идентификатор файла - fileid -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ПолучитьВнешнийФайл(Знач Токен, Знач ИдентификаторФайла) Экспорт - + URL = "https://slack.com/api/files.remote.info"; Ответ = УправлениеВнешнимФайлом(Токен, ИдентификаторФайла, URL); - + Возврат Ответ; - + КонецФункции // Добавить внешний файл // Добавляет новый внешний файл -// +// // Параметры: // Токен - Строка - Токен бота - token // URL - Строка - URL к внешнему файлу - url // Заголовок - Строка - Заголовок файла для Slack - title -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ДобавитьВнешнийФайл(Знач Токен, Знач URL, Знач Заголовок) Экспорт - + Строка_ = "Строка"; URL = "https://slack.com/api/files.remote.add"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); UID = Строка(Новый УникальныйИдентификатор()); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("external_url", URL , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("external_id" , UID , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("title" , Заголовок , Строка_, Параметры); Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Отправить внешний файл // Отправляет внейшний файл по списку каналов -// +// // Параметры: // Токен - Строка - Токен бота - token // ИдентификаторФайла - Строка - Идентификатор файла - fileid // МассивКаналов - Массив Из Строка - Массив каналов для отправки - channels -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция ОтправитьВнешнийФайл(Знач Токен, Знач ИдентификаторФайла, Знач МассивКаналов) Экспорт - + URL = "https://slack.com/api/files.remote.share"; Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивКаналов); МассивКаналов = СтрСоединить(МассивКаналов, ","); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("file" , ИдентификаторФайла , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("channels", МассивКаналов , "Строка", Параметры); Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Удалить внешний файл // Удаляет внешний файл из Slack -// +// // Параметры: // Токен - Строка - Токен бота - token // ИдентификаторФайла - Строка - Идентификатор файла - fileid -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Slack Функция УдалитьВнешнийФайл(Знач Токен, Знач ИдентификаторФайла) Экспорт - + URL = "https://slack.com/api/files.remote.remove"; Ответ = УправлениеВнешнимФайлом(Токен, ИдентификаторФайла, URL); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -959,24 +959,24 @@ // Сформировать блок картинку // Формирует блок с картинкой для добавления в массив блоков сообщения -// +// // Параметры: // URL - Строка - URL картинки - picture // АльтернативныйТекст - Строка - Альтернативный текст картинки - alt -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - Блок картинки Функция СформироватьБлокКартинку(Знач URL, Знач АльтернативныйТекст = "") Экспорт - + Строка_ = "Строка"; - + Блок = Новый Соответствие; OPI_Инструменты.ДобавитьПоле("type" , "image" , Строка_, Блок); OPI_Инструменты.ДобавитьПоле("image_url", URL , Строка_, Блок); OPI_Инструменты.ДобавитьПоле("alt_text" , АльтернативныйТекст , Строка_, Блок); - + Возврат Блок; - + КонецФункции #КонецОбласти @@ -988,43 +988,43 @@ Функция ПолучитьЗаголовокАвторизации(Знач Токен) OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Заголовки = Новый Соответствие; Заголовки.Вставить("Authorization", "Bearer " + Токен); Возврат Заголовки; - + КонецФункции Функция УправлениеДиалогом(Знач Токен, Знач Канал, Знач URL, Знач ВидЗапроса = "POST") - + Заголовки = ПолучитьЗаголовокАвторизации(Токен); ВидЗапроса = вРег(ВидЗапроса); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("channel", Канал, "Строка", Параметры); Если ВидЗапроса = "POST" Тогда - Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); Иначе - Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); + Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); КонецЕсли; - + Возврат Ответ; - + КонецФункции Функция УправлениеФайлом(Знач Токен, Знач ИдентификаторФайла, Знач URL, Знач ВидЗапроса = "POST") - - Заголовки = ПолучитьЗаголовокАвторизации(Токен); + + Заголовки = ПолучитьЗаголовокАвторизации(Токен); ВидЗапроса = вРег(ВидЗапроса); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("file", ИдентификаторФайла , "Строка", Параметры); Если ВидЗапроса = "POST" Тогда - Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); + Ответ = OPI_Инструменты.Post(URL, Параметры, Заголовки); Иначе - Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); + Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); КонецЕсли; Возврат Ответ; @@ -1032,29 +1032,29 @@ КонецФункции Функция ПолучениеОбщихДанных(Знач Токен, Знач URL, Знач Курсор) - + Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("cursor", Курсор, "Строка", Параметры); - + Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции Функция УправлениеВнешнимФайлом(Знач Токен, Знач ИдентификаторФайла, Знач URL) - + Заголовки = ПолучитьЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("file", ИдентификаторФайла , "Строка", Параметры); Ответ = OPI_Инструменты.Get(URL, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции -#КонецОбласти \ No newline at end of file +#КонецОбласти diff --git a/src/ru/OPI/src/CommonModules/OPI_Telegram/Module.bsl b/src/ru/OPI/src/CommonModules/OPI_Telegram/Module.bsl index 3b9dc1b3ed..1abdfe0565 100644 --- a/src/ru/OPI/src/CommonModules/OPI_Telegram/Module.bsl +++ b/src/ru/OPI/src/CommonModules/OPI_Telegram/Module.bsl @@ -1,4 +1,4 @@ -// OneScript: ./OInt/core/Modules/OPI_Telegram.os +// OneScript: ./OInt/core/Modules/OPI_Telegram.os // Lib: Telegram // CLI: telegram @@ -47,19 +47,19 @@ // Получить информацию о боте // Выполняет запрос /getMe, возвращающий базовую информацию о боте: имя, id, возможность добавлять бота в группы и т.д. -// +// // Параметры: // Токен - Строка - Токен бота - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ПолучитьИнформациюБота(Знач Токен) Экспорт OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + URL = "api.telegram.org/bot" + Токен + "/getMe"; Ответ = OPI_Инструменты.Get(URL); - + Возврат Ответ; КонецФункции @@ -71,114 +71,114 @@ // Токен - Строка - Токен бота - token // Таймаут - Строка,Число - Время ожидания новых событий - timeout // Смещение - Строка,Число - Смещение в списке получаемых сообщений - offset -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ПолучитьОбновления(Знач Токен, Знач Таймаут = 0, Знач Смещение = "") Экспорт OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + URL = "api.telegram.org/bot" + Токен + "/getUpdates"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("timeout", Таймаут , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("offset" , Смещение, "Строка", Параметры); - + Ответ = OPI_Инструменты.Get(URL, Параметры); Возврат Ответ; КонецФункции // Установить Webhook -// Устанавливает URL обработчика событий бота для работы в режиме Webhook -// +// Устанавливает URL обработчика событий бота для работы в режиме Webhook +// // Параметры: // Токен - Строка - Токен бота - token // URL - Строка - Адрес обработки запросов от Telegram (с https:) - url -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция УстановитьWebhook(Знач Токен, Знач URL) Экспорт OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("url", URL, "Строка", Параметры); URL = "api.telegram.org/bot" + Токен + "/setWebHook"; Ответ = OPI_Инструменты.Get(URL, Параметры); - + Возврат Ответ; КонецФункции // Удалить Webhook // Удаляет URL обработчика событий бота для работы в режиме Webhook -// +// // Параметры: // Токен - Строка - Токен бота - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция УдалитьWebhook(Знач Токен) Экспорт OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + URL = "api.telegram.org/bot" + Токен + "/deleteWebHook"; Ответ = OPI_Инструменты.Get(URL); - + Возврат Ответ; КонецФункции // Скачать файл // Скачивает файл с серверов Telegram -// +// // Параметры: // Токен - Строка - Токен - token // IDФайла - Строка - ID файла для скачивания - fileid -// +// // Возвращаемое значение: // ДвоичныеДанные - данные файла Функция СкачатьФайл(Знач Токен, Знач IDФайла) Экспорт Result = "result"; - - OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - OPI_ПреобразованиеТипов.ПолучитьСтроку(IDФайла); - + + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDФайла); + Параметры = Новый Структура("file_id", IDФайла); URL = "api.telegram.org/bot" + Токен + "/getFile"; Ответ = OPI_Инструменты.Get(URL, Параметры); - + Путь = Ответ[Result]["file_path"]; - + Если Не ЗначениеЗаполнено(Путь) Тогда Возврат Ответ; КонецЕсли; - + URL = "api.telegram.org/file/bot" + Токен + "/" + Путь; Ответ = OPI_Инструменты.Get(URL, Параметры); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции // ОбработатьДанные Telegram Mini App // Обрабатывает данные TMA и опредеяет их достоверность -// +// // Параметры: // СтрокаДанных - Строка - querry из Telegram.WebApp.initData // Токен - Строка - Токен бота -// +// // Возвращаемое значение: // Соответствие из Строка - Соответствие данных с результатом проверки в поле passed Функция ОбработатьДанныеTMA(Знач СтрокаДанных, Знач Токен) Экспорт OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(СтрокаДанных); - + СтрокаДанных = РаскодироватьСтроку(СтрокаДанных, СпособКодированияСтроки.КодировкаURL); СтруктураДанных = OPI_Инструменты.ПараметрыЗапросаВСоответствие(СтрокаДанных); КлючСтрокой = "WebAppData"; @@ -221,9 +221,9 @@ Финал = ПолучитьHexСтрокуИзДвоичныхДанных(Подпись); Если Финал = вРег(Хэш) Тогда - Ответ = Истина; + Ответ = Истина; Иначе - Ответ = Ложь; + Ответ = Ложь; КонецЕсли; СоответствиеВозврата.Вставить("passed", Ответ); @@ -238,7 +238,7 @@ // Отправить текстовое сообщение // Отправляет текстовое сообщение в чат или канал -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата или IDЧата*IDТемы - chat @@ -246,7 +246,7 @@ // Клавиатура - Строка - См. СформироватьКлавиатуруПоМассивуКнопок - keyboard - JSON клавиатуры или путь к .json // Разметка - Строка - Вид обработки текста (HTML, Markdown, MarkdownV2) - parsemode // IDВходящего - Строка,Число - ID сообщения на которое надо ответить - reply -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ОтправитьТекстовоеСообщение(Знач Токен @@ -256,19 +256,19 @@ , Знач Разметка = "Markdown" , Знач IDВходящего = 0) Экспорт - OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_Инструменты.ЗаменитьСпецСимволы(Текст, Разметка); - + Строка_ = "Строка"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("parse_mode" , Разметка , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("text" , Текст , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("reply_markup" , Клавиатура , "СтрокаФайла", Параметры); OPI_Инструменты.ДобавитьПоле("reply_to_message_id", IDВходящего, Строка_ , Параметры); - + ДобавитьИдентификаторЧата(IDЧата, Параметры); - + URL = "api.telegram.org/bot" + Токен + "/sendMessage"; Ответ = OPI_Инструменты.Get(URL, Параметры); @@ -278,7 +278,7 @@ // Отправить картинку // Отправляет картинку в чат или канал -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата или IDЧата*IDТемы - chat @@ -286,7 +286,7 @@ // Картинка - ДвоичныеДанные,Строка - Файл картинки - picture // Клавиатура - Строка - См. СформироватьКлавиатуруПоМассивуКнопок - keyboard - JSON клавиатуры или путь к .json // Разметка - Строка - Вид обработки текста (HTML, Markdown, MarkdownV2) - parsemode -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ОтправитьКартинку(Знач Токен @@ -302,7 +302,7 @@ // Отправить видео // Отправляет видео в чат или канал -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата или IDЧата*IDТемы - chat @@ -310,7 +310,7 @@ // Видео - ДвоичныеДанные,Строка - Файл видео - video // Клавиатура - Строка - См. СформироватьКлавиатуруПоМассивуКнопок - keyboard - JSON клавиатуры или путь к .json // Разметка - Строка - Вид обработки текста (HTML, Markdown, MarkdownV2) - parsemode -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ОтправитьВидео(Знач Токен @@ -326,7 +326,7 @@ // Отправить аудио // Отправляет аудиофайл в чат или канал -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата или IDЧата*IDТемы - chat @@ -334,7 +334,7 @@ // Аудио - ДвоичныеДанные,Строка - Файл аудио - audio // Клавиатура - Строка - См. СформироватьКлавиатуруПоМассивуКнопок - keyboard - JSON клавиатуры или путь к .json // Разметка - Строка - Вид обработки текста (HTML, Markdown, MarkdownV2) - parsemode -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ОтправитьАудио(Знач Токен @@ -350,7 +350,7 @@ // Отправить документ // Отправляет документ в чат или канал -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата или IDЧата*IDТемы - chat @@ -359,7 +359,7 @@ // Клавиатура - Строка - См. СформироватьКлавиатуруПоМассивуКнопок - keyboard - JSON клавиатуры или путь к .json // Разметка - Строка - Вид обработки текста (HTML, Markdown, MarkdownV2) - parsemode // ИмяФайла - Строка - Отображаемое имя файла c расширением, если необходимо - filename -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ОтправитьДокумент(Знач Токен @@ -376,7 +376,7 @@ // Отправить гифку // Отправляет гифку в чат или канал -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата или IDЧата*IDТемы - chat @@ -384,7 +384,7 @@ // Гифка - ДвоичныеДанные,Строка - Файл гифки - gif // Клавиатура - Строка - См. СформироватьКлавиатуруПоМассивуКнопок - keyboard - JSON клавиатуры или путь к .json // Разметка - Строка - Вид обработки текста (HTML, Markdown, MarkdownV2) - parsemode -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ОтправитьГифку(Знач Токен @@ -400,10 +400,10 @@ // Отправить группу медиафайлов // Отправляет набор файлов в чат или канал. Варианты типов медиа: audio, document, photo, video -// +// // Примечание: // Соответствие файлов: Ключ - Файл, Значение - один из типов медиа -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата или IDЧата*IDТемы - chat @@ -411,7 +411,7 @@ // СоответствиеФайлов - Соответствие из Строка - Коллекция файлов - media - JSON файлов или путь к .json // Клавиатура - Строка - См. СформироватьКлавиатуруПоМассивуКнопок - keyboard - JSON клавиатуры или путь к .json // Разметка - Строка - Вид обработки текста (HTML, Markdown, MarkdownV2) - parsemode -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ОтправитьМедиагруппу(Знач Токен @@ -420,27 +420,27 @@ , Знач СоответствиеФайлов , Знач Клавиатура = "" , Знач Разметка = "Markdown") Экспорт - + // СоответствиеФайлов // Ключ - Файл, Значение - Тип // Типы: audio, document, photo, video // Нельзя замешивать разные типы! Строка_ = "Строка"; - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDЧата); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(СоответствиеФайлов); - + OPI_Инструменты.ЗаменитьСпецсимволы(Текст, Разметка); URL = "api.telegram.org/bot" + Токен + "/sendMediaGroup"; Медиа = Новый Массив; Параметры = Новый Структура; - + ДобавитьИдентификаторЧата(IDЧата, Параметры); ПреобразоватьФайлыВМедиа(СоответствиеФайлов, Текст, Медиа); - + OPI_Инструменты.ДобавитьПоле("parse_mode" , Разметка , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("caption" , Текст , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("media" , Медиа , Строка_ , Параметры); @@ -454,14 +454,14 @@ // Отправить местоположение // Отправляет местоположение по географической широте и долготе в чат или канал -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата или IDЧата*IDТемы - chat // Широта - Строка,Число - Географическая широта - lat // Долгота - Строка,Число - Географическая долгота - long // Клавиатура - Строка - См. СформироватьКлавиатуруПоМассивуКнопок - keyboard - JSON клавиатуры или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ОтправитьМестоположение(Знач Токен, Знач IDЧата, Знач Широта, Знач Долгота, Знач Клавиатура = "") Экспорт @@ -469,15 +469,15 @@ Строка_ = "Строка"; OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDЧата); - + URL = "api.telegram.org/bot" + Токен + "/sendLocation"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("parse_mode" , "Markdown" , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("latitude" , Широта , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("longitude" , Долгота , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("reply_markup", Клавиатура , "СтрокаФайла", Параметры); - + ДобавитьИдентификаторЧата(IDЧата, Параметры); Ответ = OPI_Инструменты.Get(URL, Параметры); @@ -488,7 +488,7 @@ // Отправить контакт // Отправляет контакт с именем и номером телефона -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата или IDЧата*IDТемы - chat @@ -496,7 +496,7 @@ // Фамилия - Строка - Фамилия контакта - surname // Телефон - Строка - Телефон контакта - phone // Клавиатура - Строка - См. СформироватьКлавиатуруПоМассивуКнопок - keyboard - JSON клавиатуры или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ОтправитьКонтакт(Знач Токен, Знач IDЧата, Знач Имя, Знач Фамилия, Знач Телефон, Знач Клавиатура = "") Экспорт @@ -504,7 +504,7 @@ Строка_ = "Строка"; OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDЧата); - + URL = "api.telegram.org/bot" + Токен + "/sendContact"; Параметры = Новый Структура; @@ -513,7 +513,7 @@ OPI_Инструменты.ДобавитьПоле("last_name" , Фамилия , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("phone_number", Телефон , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("reply_markup", Клавиатура, "СтрокаФайла", Параметры); - + ДобавитьИдентификаторЧата(IDЧата, Параметры); Ответ = OPI_Инструменты.Get(URL, Параметры); @@ -524,14 +524,14 @@ // Отправить опрос // Отправляет опрос с вариантами ответа -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата или IDЧата*IDТемы - chat // Вопрос - Строка - Вопрос опроса - question // МассивОтветов - Массив из Строка - Массив вариантов ответа - options // Анонимный - Булево - Анонимность опроса - anonymous -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ОтправитьОпрос(Знач Токен, Знач IDЧата, Знач Вопрос, Знач МассивОтветов, Знач Анонимный = Истина) Экспорт @@ -541,15 +541,15 @@ OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивОтветов); OPI_ПреобразованиеТипов.ПолучитьБулево(Анонимный); - + URL = "api.telegram.org/bot" + Токен + "/sendPoll"; Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("parse_mode", "Markdown" , "Строка" , Параметры); OPI_Инструменты.ДобавитьПоле("question" , Вопрос , "Строка" , Параметры); OPI_Инструменты.ДобавитьПоле("options" , МассивОтветов, "СтрокаФайла", Параметры); - - Параметры.Вставить("is_anonymous", ?(Анонимный, 1, 0)); + + Параметры.Вставить("is_anonymous", ?(Анонимный, 1, 0)); ДобавитьИдентификаторЧата(IDЧата, Параметры); Ответ = OPI_Инструменты.Get(URL, Параметры); @@ -560,13 +560,13 @@ // Переслать сообщение // Пересылает сообщение между чатами или в рамках одного чата -// +// // Параметры: // Токен - Строка - Токен бота - token // IDОригинала - Строка,Число - ID оригинального сообщения - message // ОткудаID - Строка,Число - ID чата оригинального сообщения - from // КудаID - Строка,Число - ID целевого чата или IDЧата*IDТемы - to -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ПереслатьСообщение(Знач Токен, Знач IDОригинала, Знач ОткудаID, Знач КудаID) Экспорт @@ -575,15 +575,15 @@ OPI_ПреобразованиеТипов.ПолучитьСтроку(IDОригинала); OPI_ПреобразованиеТипов.ПолучитьСтроку(ОткудаID); OPI_ПреобразованиеТипов.ПолучитьСтроку(КудаID); - + URL = "api.telegram.org/bot" + Токен + "/forwardMessage"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("from_chat_id", ОткудаID , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("message_id" , IDОригинала, "Строка", Параметры); ДобавитьИдентификаторЧата(КудаID, Параметры); - + Ответ = OPI_Инструменты.Get(URL, Параметры); Возврат Ответ; @@ -592,12 +592,12 @@ // Сформировать клавиатуру по массиву кнопок // Формирует простую JSON клавиатуру из массив кнопок для сообщения или нижней панели -// +// // Параметры: -// МассивКнопок - Массив из Строка - Массив кнопок - buttons +// МассивКнопок - Массив из Строка - Массив кнопок - buttons // ПодСообщением - Булево - Клавиатура под сообщением или на нижней панели - under // ОднаПодОдной - Булево - Истина > кнопки выводятся в столбик, Ложь > в строку - column -// +// // Возвращаемое значение: // Строка - JSON клавиатуры Функция СформироватьКлавиатуруПоМассивуКнопок(Знач МассивКнопок @@ -607,7 +607,7 @@ OPI_ПреобразованиеТипов.ПолучитьБулево(ПодСообщением); OPI_ПреобразованиеТипов.ПолучитьБулево(ОднаПодОдной); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивКнопок); - + Если ОднаПодОдной Тогда Строки = СоздатьВысокуюКлавиатуру(МассивКнопок); Иначе @@ -615,7 +615,7 @@ КонецЕсли; Если ПодСообщением Тогда - СтруктураПараметра = Новый Структура("inline_keyboard,rows", Строки, 1); + СтруктураПараметра = Новый Структура("inline_keyboard,rows" , Строки, 1); Иначе СтруктураПараметра = Новый Структура("keyboard,resize_keyboard", Строки, Истина); КонецЕсли; @@ -632,19 +632,19 @@ // Бан // Банит пользователя в выбранном чате -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата или IDЧата*IDТемы - chat // IDПользователя - Строка,Число - ID целевого пользователя - user -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция Бан(Знач Токен, Знач IDЧата, Знач IDПользователя) Экспорт Строка_ = "Строка"; OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + URL = "api.telegram.org/bot" + Токен + "/banChatMember"; Параметры = Новый Структура; @@ -660,22 +660,22 @@ // Разбан // Разбанивает забаненного ранее пользователя -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата или IDЧата*IDТемы - chat // IDПользователя - Строка,Число - ID целевого пользователя - user -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция Разбан(Знач Токен, Знач IDЧата, Знач IDПользователя) Экспорт Строка_ = "Строка"; OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + URL = "api.telegram.org/bot" + Токен + "/unbanChatMember"; - Параметры = Новый Структура; + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("parse_mode" , "Markdown" , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("chat_id" , IDЧата , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("user_id" , IDПользователя, Строка_ , Параметры); @@ -689,14 +689,14 @@ // Создать ссылку-приглашение // Создает ссылку для вступления в закрытый чат -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата или IDЧата*IDТемы - chat // Заголовок - Строка - Заголовок приглашения - title // ДатаИстечения - Дата - Дата окончания жизни ссылки (безсрочно, если не указано) - expire // ЛимитПользователей - Число - Лимит пользователей (бесконечно, если не указано) - limit -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция СоздатьСсылкуПриглашение(Знач Токен @@ -707,16 +707,16 @@ Строка_ = "Строка"; OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + URL = "api.telegram.org/bot" + Токен + "/createChatInviteLink"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("parse_mode" , "Markdown" , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("chat_id" , IDЧата , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("name" , Заголовок , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("member_limit" , ЛимитПользователей, Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("expire_date" , ДатаИстечения , "Дата" , Параметры); - + Ответ = OPI_Инструменты.Get(URL, Параметры); Возврат Ответ; @@ -725,21 +725,21 @@ // Закрепить сообщение // Закрепляет сообщение в шапке чата -// +// // Параметры: // Токен - Строка - Токен - token // IDЧата - Строка,Число - ID целевого чата - chat // IDСообщения - Строка,Число - ID целевого сообщения - message -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ЗакрепитьСообщение(Знач Токен, Знач IDЧата, Знач IDСообщения) Экспорт - + Строка_ = "Строка"; OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + URL = "api.telegram.org/bot" + Токен + "/pinChatMessage"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("parse_mode" , "Markdown" , Строка_ , Параметры); OPI_Инструменты.ДобавитьПоле("chat_id" , IDЧата , Строка_ , Параметры); @@ -754,21 +754,21 @@ // Открепить сообщение // Открепляет сообщение в шапке чата -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата - chat // IDСообщения - Строка,Число - ID целевого сообщения - message -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ОткрепитьСообщение(Знач Токен, Знач IDЧата, Знач IDСообщения) Экспорт - + Строка_ = "Строка"; OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + URL = "api.telegram.org/bot" + Токен + "/unpinChatMessage"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("parse_mode", "Markdown" , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("chat_id" , IDЧата , Строка_, Параметры); @@ -782,19 +782,19 @@ // Получить число участников // Получает общее число участников чата -// +// // Параметры: // Токен - Строка - Токен бота - token // IDЧата - Строка,Число - ID целевого чата - chat -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ПолучитьЧислоУчастников(Знач Токен, Знач IDЧата) Экспорт OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + URL = "api.telegram.org/bot" + Токен + "/getChatMemberCount"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("parse_mode", "Markdown" , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("chat_id" , IDЧата , "Строка", Параметры); @@ -807,24 +807,24 @@ // Удалить сообщение // Удаляет указанное сообщение из чата или канала -// +// // Параметры: // Токен - Строка - Токен - token // IDЧата - Строка,Число - ID целевого чата - chat // IDСообщения - Строка,Число - ID удаляемого сообщения - message -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция УдалитьСообщение(Знач Токен, Знач IDЧата, Знач IDСообщения) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + URL = "api.telegram.org/bot" + Токен + "/deleteMessage"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("message_id", IDСообщения, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("chat_id" , IDЧата , "Строка", Параметры); - + Ответ = OPI_Инструменты.Get(URL, Параметры); Возврат Ответ; @@ -836,206 +836,206 @@ // Получить список иконок-аватаров // Получает соответствие ID Emoji для установки в качестве иконок тем форума -// +// // Параметры: // Токен - Строка - Токен - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - Ключ > ID, Значение > Emoji Функция ПолучитьСписокИконокАватаров(Знач Токен) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Result = "result"; - URL = "api.telegram.org/bot" + Токен + "/getForumTopicIconStickers"; - Ответ = OPI_Инструменты.Get(URL); + URL = "api.telegram.org/bot" + Токен + "/getForumTopicIconStickers"; + Ответ = OPI_Инструменты.Get(URL); Иконки = Ответ[Result]; - + Если Не ЗначениеЗаполнено(Иконки) Тогда Возврат Ответ; - КонецЕсли; - + КонецЕсли; + Коллекция = Новый Соответствие; - + Для Каждого Иконка Из Иконки Цикл Коллекция.Вставить(Иконка["custom_emoji_id"], Иконка["emoji"]); КонецЦикла; - + Возврат Коллекция; КонецФункции // Создать тему форума // Создает новую тему в группе с включенным функционалом тем -// +// // Параметры: // Токен - Строка - Токен - token // IDЧата - Строка,Число - ID чата создания темы - forum // Заголовок - Строка - Заголовок темы - title // IDИконки - Строка - См. ПолучитьСписокИконокАватаров - icon -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция СоздатьТемуФорума(Знач Токен, Знач IDЧата, Знач Заголовок, Знач IDИконки = "") Экспорт - + Возврат УправлениеТемойФорума(Токен, IDЧата, Заголовок, IDИконки); - + КонецФункции // Изменить тему форума // Создает новую тему в группе с включенным функционалом тем -// +// // Параметры: // Токен - Строка - Токен - token // IDЧата - Строка,Число - ID чата создания темы - forum // IDТемы - Строка,Число - ID темы - topic // Заголовок - Строка - Новый заголовок - title // IDИконки - Строка - См. ПолучитьСписокИконокАватаров - icon -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ИзменитьТемуФорума(Знач Токен , Знач IDЧата , Знач IDТемы , Знач Заголовок = Неопределено - , Знач IDИконки = Неопределено) Экспорт - + , Знач IDИконки = Неопределено) Экспорт + Возврат УправлениеТемойФорума(Токен, IDЧата, Заголовок, IDИконки, IDТемы); КонецФункции // Закрыть тему форума // Закрывает тему для новых сообщений -// +// // Параметры: // Токен - Строка - Токен - token // IDЧата - Строка,Число - ID чата темы - forum // IDТемы - Строка,Число - ID темы - topic -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ЗакрытьТемуФорума(Знач Токен, Знач IDЧата, Знач IDТемы = "") Экспорт - - Возврат УправлениеСостояниемТемыФорума(Токен, IDЧата, 2, IDТемы); - + + Возврат УправлениеСостояниемТемыФорума(Токен, IDЧата, 2, IDТемы); + КонецФункции // Открыть тему форума // Повторно открывает ранее закрытую тему форума -// +// // Параметры: // Токен - Строка - Токен - token // IDЧата - Строка,Число - ID чата темы - forum // IDТемы - Строка,Число - ID темы - topic -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ОткрытьТемуФорума(Знач Токен, Знач IDЧата, Знач IDТемы = "") Экспорт - - Возврат УправлениеСостояниемТемыФорума(Токен, IDЧата, 1, IDТемы); - + + Возврат УправлениеСостояниемТемыФорума(Токен, IDЧата, 1, IDТемы); + КонецФункции // Удалить тему форума // Удаляет тему форума -// +// // Параметры: // Токен - Строка - Токен - token // IDЧата - Строка,Число - ID чата темы - forum // IDТемы - Строка,Число - ID темы - topic -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция УдалитьТемуФорума(Знач Токен, Знач IDЧата, Знач IDТемы) Экспорт - - Возврат УправлениеСостояниемТемыФорума(Токен, IDЧата, 3, IDТемы); - + + Возврат УправлениеСостояниемТемыФорума(Токен, IDЧата, 3, IDТемы); + КонецФункции // Скрыть главную тему форума // Скрывает главную тему форума -// +// // Параметры: // Токен - Строка - Токен - token // IDЧата - Строка,Число - ID чата темы - forum -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция СкрытьГлавнуюТемуФорума(Знач Токен, Знач IDЧата) Экспорт - + Возврат УправлениеВидимостьюГлавнойТемыФорума(Токен, IDЧата, Истина); - + КонецФункции // Показать главную тему форума // Показывает ранее скрытую главную тему форума -// +// // Параметры: // Токен - Строка - Токен - token // IDЧата - Строка,Число - ID чата темы - forum -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ПоказатьГлавнуюТемуФорума(Знач Токен, Знач IDЧата) Экспорт - + Возврат УправлениеВидимостьюГлавнойТемыФорума(Токен, IDЧата, Ложь); - + КонецФункции // Изменить имя главной темы форума // Изменяет имя главной темы форума -// +// // Параметры: // Токен - Строка - Токен - token // IDЧата - Строка,Число - ID чата темы - forum // Заголовок - Строка - Новое имя главной темы - title -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ИзменитьИмяГлавнойТемыФорума(Знач Токен, Знач IDЧата, Знач Заголовок) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + URL = "api.telegram.org/bot" + Токен + "/editGeneralForumTopic"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("chat_id", IDЧата , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("name" , Заголовок, "Строка", Параметры); - + Ответ = OPI_Инструменты.Get(URL, Параметры); - + Возврат Ответ; КонецФункции // Очистить список закрепленных сообщений темы // Очищает список закрепленных сообщений в теме форума -// +// // Параметры: // Токен - Строка - Токен - token // IDЧата - Строка,Число - ID чата темы - forum // IDТемы - Строка,Число - ID темы. Главная, если не заполнено - topic -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Telegram Функция ОчиститьСписокЗакрепленныхСообщенийТемы(Знач Токен, Знач IDЧата, Знач IDТемы = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDЧата); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDТемы); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("chat_id" , IDЧата, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("message_thread_id", IDТемы, "Строка", Параметры); - + Если ЗначениеЗаполнено(IDТемы) Тогда Метод = "/unpinAllForumTopicMessages"; Иначе Метод = "/unpinAllGeneralForumTopicMessages"; КонецЕсли; - + URL = "api.telegram.org/bot" + Токен + Метод; Ответ = OPI_Инструменты.Get(URL, Параметры); - + Возврат Ответ; КонецФункции @@ -1061,20 +1061,20 @@ OPI_ПреобразованиеТипов.ПолучитьСтроку(Текст); OPI_Инструменты.ЗаменитьСпецсимволы(Текст, Разметка); - + Если Не ЗначениеЗаполнено(ИмяФайла) Тогда ИмяФайла = ПреобразоватьДанныеФайла(Файл, Вид, ""); Иначе OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Файл); КонецЕсли; - + ИмяФайла = Вид + "|" + ИмяФайла; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("parse_mode" , Разметка , "Строка" , Параметры); OPI_Инструменты.ДобавитьПоле("caption" , Текст , "Строка" , Параметры); OPI_Инструменты.ДобавитьПоле("reply_markup", Клавиатура, "СтрокаФайла", Параметры); - + ДобавитьИдентификаторЧата(IDЧата, Параметры); СоответствиеФайлов = Новый Соответствие; @@ -1091,55 +1091,55 @@ Функция УправлениеТемойФорума(Знач Токен , Знач IDЧата , Знач Заголовок = Неопределено - , Знач IDИконки = Неопределено - , Знач IDТемы = "") - + , Знач IDИконки = Неопределено + , Знач IDТемы = "") + Строка_ = "Строка"; OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("name" , Заголовок, Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("chat_id" , IDЧата , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("icon_custom_emoji_id", IDИконки , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("message_thread_id" , IDТемы , Строка_, Параметры); - + Если ЗначениеЗаполнено(IDТемы) Тогда - Метод = "/editForumTopic"; - Иначе - Метод = "/createForumTopic"; + Метод = "/editForumTopic"; + Иначе + Метод = "/createForumTopic"; КонецЕсли; - + Ответ = OPI_Инструменты.Get("api.telegram.org/bot" + Токен + Метод, Параметры); - + Возврат Ответ; КонецФункции -Функция УправлениеСостояниемТемыФорума(Знач Токен, Знач IDЧата, Знач Статус, Знач IDТемы = "") - +Функция УправлениеСостояниемТемыФорума(Знач Токен, Знач IDЧата, Знач Статус, Знач IDТемы = "") + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Если ЗначениеЗаполнено(IDТемы) Тогда Форум = "Forum"; Иначе Форум = "GeneralForum"; КонецЕсли; - + Метод = ОпределитьМетодУправленияФорумом(Статус, Форум); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("chat_id" , IDЧата, "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("message_thread_id", IDТемы, "Строка", Параметры); - + URL = "api.telegram.org/bot" + Токен + Метод; Ответ = OPI_Инструменты.Get(URL, Параметры); Возврат Ответ; - + КонецФункции Функция УправлениеВидимостьюГлавнойТемыФорума(Знач Токен, Знач IDЧата, Знач Скрыть) - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьБулево(Скрыть); @@ -1148,41 +1148,41 @@ Иначе Метод = "/unhideGeneralForumTopic"; КонецЕсли; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("chat_id", IDЧата, "Строка", Параметры); - + URL = "api.telegram.org/bot" + Токен + Метод; Ответ = OPI_Инструменты.Get(URL, Параметры); - + Возврат Ответ; -КонецФункции +КонецФункции + +Функция ОпределитьМетодУправленияФорумом(Знач Статус, Знач Форум) -Функция ОпределитьМетодУправленияФорумом(Знач Статус, Знач Форум) - Открыть = 1; Закрыть = 2; Удалить = 3; - - Если Статус = Открыть Тогда - Метод = "/reopen" + Форум + "Topic"; + + Если Статус = Открыть Тогда + Метод = "/reopen" + Форум + "Topic"; ИначеЕсли Статус = Закрыть Тогда - Метод = "/close" + Форум + "Topic"; + Метод = "/close" + Форум + "Topic"; ИначеЕсли Статус = Удалить Тогда - Метод = "/deleteForumTopic"; - Иначе + Метод = "/deleteForumTopic"; + Иначе ВызватьИсключение "Некорректный статус управления форумом"; КонецЕсли; - + Возврат Метод; КонецФункции Функция СоздатьВысокуюКлавиатуру(Знач МассивКнопок) - + Строки = Новый Массив; - + Для Каждого Кнопка Из МассивКнопок Цикл Кнопки = Новый Массив; Кнопка = OPI_Инструменты.ЧислоВСтроку(Кнопка); @@ -1191,82 +1191,82 @@ КонецЦикла; Возврат Строки; - + КонецФункции Функция СоздатьДлиннуюКлавиатуру(Знач МассивКнопок) - + Строки = Новый Массив; Кнопки = Новый Массив; - + Для Каждого Кнопка Из МассивКнопок Цикл Кнопка = OPI_Инструменты.ЧислоВСтроку(Кнопка); Кнопки.Добавить(Новый Структура("text,callback_data", Кнопка, Кнопка)); КонецЦикла; - + Строки.Добавить(Кнопки); - + Возврат Строки; КонецФункции Функция ОпределитьМетодОтправки(Знач Вид) - - Если Вид = "photo" Тогда - Метод = "/sendPhoto"; + + Если Вид = "photo" Тогда + Метод = "/sendPhoto"; ИначеЕсли Вид = "video" Тогда - Метод = "/sendVideo"; + Метод = "/sendVideo"; ИначеЕсли Вид = "audio" Тогда - Метод = "/sendAudio"; + Метод = "/sendAudio"; ИначеЕсли Вид = "animation" Тогда - Метод = "/sendAnimation"; + Метод = "/sendAnimation"; Иначе - Метод = "/sendDocument"; + Метод = "/sendDocument"; КонецЕсли; Возврат Метод; - + КонецФункции Функция ПреобразоватьДанныеФайла(Файл, Вид, Счетчик) - + ИмяФайла = ""; - + Если ТипЗнч(Файл) = Тип("Строка") И Вид = "document" Тогда - + ТекущийФайл = Новый Файл(Файл); ИмяФайла = ТекущийФайл.Имя; - + КонецЕсли; - + Если Не ЗначениеЗаполнено(ИмяФайла) Тогда ИмяФайла = Вид + Строка(Счетчик); - - Если Вид = "animation" Тогда - ИмяФайла = ИмяФайла + ".gif"; + + Если Вид = "animation" Тогда + ИмяФайла = ИмяФайла + ".gif"; КонецЕсли; - + КонецЕсли; - + OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Файл); - + Возврат ИмяФайла; - + КонецФункции Процедура ПреобразоватьФайлыВМедиа(СоответствиеФайлов, Текст, Медиа) - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(СоответствиеФайлов); OPI_ПреобразованиеТипов.ПолучитьСтроку(Текст); - + Если ТипЗнч(СоответствиеФайлов) <> Тип("Соответствие") Тогда // !OInt ВызватьИсключение("Не удалось получить информацию из json медиа!"); Возврат; КонецЕсли; - + ВременноеСоответствие = Новый Соответствие; Счетчик = 0; - + Для Каждого ТекущийФайл Из СоответствиеФайлов Цикл ТекущиеДанные = ТекущийФайл.Ключ; @@ -1291,24 +1291,24 @@ КонецЦикла; Медиа = OPI_Инструменты.JSONСтрокой(Медиа); - СоответствиеФайлов = ВременноеСоответствие; - + СоответствиеФайлов = ВременноеСоответствие; + КонецПроцедуры Процедура ДобавитьИдентификаторЧата(Знач IDЧата, Параметры) - + IDЧата = OPI_Инструменты.ЧислоВСтроку(IDЧата); МассивЧата = СтрРазделить(IDЧата, "*", Ложь); - + Если МассивЧата.Количество() > 1 Тогда - + IDЧата = МассивЧата[0]; IDТемы = МассивЧата[1]; - + Параметры.Вставить("message_thread_id", IDТемы); - + КонецЕсли; - + Параметры.Вставить("chat_id", IDЧата); КонецПроцедуры diff --git a/src/ru/OPI/src/CommonModules/OPI_Twitter/Module.bsl b/src/ru/OPI/src/CommonModules/OPI_Twitter/Module.bsl index 6419924038..a966e76ae9 100644 --- a/src/ru/OPI/src/CommonModules/OPI_Twitter/Module.bsl +++ b/src/ru/OPI/src/CommonModules/OPI_Twitter/Module.bsl @@ -1,4 +1,4 @@ -// OneScript: ./OInt/core/Modules/OPI_Twitter.os +// OneScript: ./OInt/core/Modules/OPI_Twitter.os // Lib: Twitter // CLI: twitter @@ -48,18 +48,18 @@ // Получить ссылку для авторизации // Формирует ссылку для авторизации через браузер -// +// // Параметры: // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Строка - URL для перехода в браузере Функция ПолучитьСсылкуАвторизации(Параметры = "") Экспорт - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); - + ПараметрыURL = Новый Структура; - + ПараметрыURL.Вставить("response_type" , "code"); ПараметрыURL.Вставить("client_id" , Параметры_["client_id"]); ПараметрыURL.Вставить("redirect_uri" , Параметры_["redirect_uri"]); @@ -67,27 +67,27 @@ ПараметрыURL.Вставить("state" , "state"); ПараметрыURL.Вставить("code_challenge" , "challenge"); ПараметрыURL.Вставить("code_challenge_method", "plain"); - + ПараметрыURL = OPI_Инструменты.ПараметрыЗапросаВСтроку(ПараметрыURL); - Линк = "https://twitter.com/i/oauth2/authorize" + ПараметрыURL; - + Линк = "https://twitter.com/i/oauth2/authorize" + ПараметрыURL; + Возврат Линк; - + КонецФункции // Получить токен // Получает токен по коду, полученному при авторизации по ссылке из ПолучитьСсылкуАвторизации -// +// // Параметры: // Код - Строка - Код, полученный из авторизации См.ПолучитьСсылкуАвторизации - code // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Twitter Функция ПолучитьТокен(Знач Код, Знач Параметры = "") Экспорт OPI_ПреобразованиеТипов.ПолучитьСтроку(Код); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); ПараметрыЗапроса = Новый Структура; @@ -96,35 +96,35 @@ ПараметрыЗапроса.Вставить("client_id" , Параметры_["client_id"]); ПараметрыЗапроса.Вставить("redirect_uri" , Параметры_["redirect_uri"]); ПараметрыЗапроса.Вставить("code_verifier", "challenge"); - + Ответ = OPI_Инструменты.Post("https://api.twitter.com/2/oauth2/token" , ПараметрыЗапроса, , Ложь); - + Возврат Ответ; - + КонецФункции -// Обновить токен +// Обновить токен // Обновляет v2 токен при помощи refresh_token -// +// // Параметры: // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Twitter Функция ОбновитьТокен(Знач Параметры = "") Экспорт - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Refresh = "refresh_token"; - + ПараметрыЗапроса = Новый Структура; ПараметрыЗапроса.Вставить(Refresh , Параметры_[Refresh]); ПараметрыЗапроса.Вставить("grant_type" , Refresh); ПараметрыЗапроса.Вставить("client_id" , Параметры_["client_id"]); - + Ответ = OPI_Инструменты.Post("https://api.twitter.com/2/oauth2/token" , ПараметрыЗапроса, , Ложь); - + Возврат Ответ; КонецФункции @@ -133,23 +133,23 @@ // Метод для вставки в http-сервис, адрес которого указывается в redirect_uri // Вызывает метод получения токена, так как для получения токена из кода, приходящего // на redirect_uri после авторизации через браузер есть всего 30 секунд -// +// // Параметры: // Запрос - HTTPСервисЗапрос - Запрос, приходящий на http-сервис -// +// // Возвращаемое значение: // HTTPОтвет, Произвольный, ДвоичныеДанные - Результат чтения JSON ответа сервера Функция ОбработкаВходящегоЗапросаПослеАвторизации(Запрос) Экспорт - - Код = Запрос.ПараметрыЗапроса["code"]; + + Код = Запрос.ПараметрыЗапроса["code"]; ОтветТокен = ПолучитьТокен(Код); - + // BSLLS:CommentedCode-off // Предпочтительное хранение токенов // Константы.TwitterRefresh.Установить(ОтветТокен["refresh_token"]); // Константы.TwitterToken.Установить(ОтветТокен["access_token"]); // BSLLS:CommentedCode-on - + Возврат ОтветТокен; КонецФункции @@ -160,189 +160,189 @@ // !NOCLI // Создать произвольный твит -// +// // Параметры: // Текст - Строка - Текст твита // МассивМедиа - Массив из Строка,ДвоичныеДанные - Массив двоичных данных или путей к файлам // МассивВариантовОпроса - Массив из Строка - Массив вариантов опроса, если необходимо // ДлительностьОпроса - Строка,Число - Длительность опроса, если необходимо (опрос без длительности не создается) // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Twitter Функция СоздатьПроизвольныйТвит(Знач Текст = "" , Знач МассивМедиа = "" , Знач МассивВариантовОпроса = "" , Знач ДлительностьОпроса = "" - , Знач Параметры = "") Экспорт - + , Знач Параметры = "") Экспорт + OPI_ПреобразованиеТипов.ПолучитьСтроку(Текст); OPI_ПреобразованиеТипов.ПолучитьСтроку(ДлительностьОпроса); - + Если ЗначениеЗаполнено(МассивМедиа) Тогда OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивМедиа); КонецЕсли; - + Если ЗначениеЗаполнено(МассивВариантовОпроса) Тогда OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивВариантовОпроса); КонецЕсли; - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); URL = "https://api.twitter.com/2/tweets"; - Массив = "Массив"; + Массив = "Массив"; Поля = Новый Соответствие; - + Если ЗначениеЗаполнено(Текст) Тогда Поля.Вставить("text", Текст); КонецЕсли; - + Если ТипЗнч(МассивВариантовОпроса) = Тип(Массив) И ЗначениеЗаполнено(ДлительностьОпроса) Тогда - + ДлительностьОпроса = Число(ДлительностьОпроса); - + Если МассивВариантовОпроса.Количество() > 0 Тогда - + СтруктураВарианта = Новый Структура("options,duration_minutes", МассивВариантовОпроса, ДлительностьОпроса); Поля.Вставить("poll", СтруктураВарианта); - + КонецЕсли; - + КонецЕсли; - + Если ТипЗнч(МассивМедиа) = Тип(Массив) Тогда Если МассивМедиа.Количество() > 0 Тогда Поля.Вставить("media", Новый Структура("media_ids", МассивМедиа)); КонецЕсли; КонецЕсли; - + Авторизация = СоздатьЗаголовокАвторизацииV2(Параметры_); Ответ = OPI_Инструменты.Post(URL, Поля, Авторизация); Возврат Ответ; - + КонецФункции // Создать текстовый твит // Создает твит без вложений -// +// // Параметры: // Текст - Строка - Текст твита - text // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Twitter Функция СоздатьТекстовыйТвит(Знач Текст, Знач Параметры = "") Экспорт - Возврат СоздатьПроизвольныйТвит(Текст, , , , Параметры); + Возврат СоздатьПроизвольныйТвит(Текст, , , , Параметры); КонецФункции // Создать твит картинки // Создает твит с картинкой вложением -// +// // Параметры: // Текст - Строка - Текст твита - text // МассивКартинок - Массив из Строка,ДвоичныеДанные - Массив файлов картинок - pictures // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Twitter Функция СоздатьТвитКартинки(Знач Текст, Знач МассивКартинок, Знач Параметры = "") Экспорт - + МассивМедиа = ЗагрузитьМассивВложений(МассивКартинок, "photo", Параметры); - Возврат СоздатьПроизвольныйТвит(Текст, МассивМедиа, , , Параметры); - + Возврат СоздатьПроизвольныйТвит(Текст, МассивМедиа, , , Параметры); + КонецФункции // Создать твит гифки // Создает твит с вложением-гифкой -// +// // Параметры: // Текст - Строка - Текст твита - text // МассивГифок - Массив из Строка,ДвоичныеДанные - Массив файлов гифок - gifs // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Twitter Функция СоздатьТвитГифки(Знач Текст, Знач МассивГифок, Знач Параметры = "") Экспорт - + МассивМедиа = ЗагрузитьМассивВложений(МассивГифок, "animated_gif", Параметры); - Возврат СоздатьПроизвольныйТвит(Текст, МассивМедиа, , , Параметры); - + Возврат СоздатьПроизвольныйТвит(Текст, МассивМедиа, , , Параметры); + КонецФункции // Создать твит видео // Создает твит с видеовложением -// +// // Параметры: // Текст - Строка - Текст твита - text // МассивВидео - Массив из Строка,ДвоичныеДанные - Массив файлов видео - videos // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Twitter Функция СоздатьТвитВидео(Знач Текст, Знач МассивВидео, Знач Параметры = "") Экспорт - + МассивМедиа = ЗагрузитьМассивВложений(МассивВидео, "video", Параметры); Возврат СоздатьПроизвольныйТвит(Текст, МассивМедиа, , , Параметры); - + КонецФункции // Создать твит опрос // Создает твит с опросом -// +// // Параметры: // Текст - Строка - Текст твита - text // МассивВариантов - Массив из Строка - Массив вариантов опроса - options // Длительность - Строка,Число - Длительность опроса - duration // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Twitter Функция СоздатьТвитОпрос(Знач Текст, Знач МассивВариантов, Знач Длительность, Знач Параметры = "") Экспорт - - Возврат СоздатьПроизвольныйТвит(Текст, , МассивВариантов, Длительность, Параметры); - + + Возврат СоздатьПроизвольныйТвит(Текст, , МассивВариантов, Длительность, Параметры); + КонецФункции // Загрузить массив вложений !NOCLI // Загружает файлы на сервер и возвращает их ID -// +// // Параметры: // МассивФайлов - Массив из Строка, ДвоичныеДанные - Массив файлов // ТипВложений - Строка - Тип вложений // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Массив Из Строка - Массив ID медиа Функция ЗагрузитьМассивВложений(Знач МассивФайлов, Знач ТипВложений, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(ТипВложений); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивФайлов); - + МассивМедиа = Новый Массив; Параметры_ = ПолучитьСтандартныеПараметры(Параметры); MIS = "media_id_string"; - + Если ЗначениеЗаполнено(МассивФайлов) Тогда - + Для Каждого ФайлОтправки Из МассивФайлов Цикл - + OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(ФайлОтправки); - + Ответ = ЗагрузитьМедиафайл(ФайлОтправки, ТипВложений, Параметры_); IDМедиа = Ответ[MIS]; - + Если Не ЗначениеЗаполнено(IDМедиа) Тогда Возврат Ответ; КонецЕсли; - + МассивМедиа.Добавить(IDМедиа); - + КонецЦикла; - + КонецЕсли; - + Возврат МассивМедиа; - + КонецФункции #КонецОбласти @@ -351,70 +351,70 @@ #Область СлужебныеПроцедурыИФункции -Функция ЗагрузитьМедиафайл(Знач Файл, Знач Тип, Знач Параметры) - +Функция ЗагрузитьМедиафайл(Знач Файл, Знач Тип, Знач Параметры) + OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Файл); - - ВидЗапроса = "POST"; + + ВидЗапроса = "POST"; Параметры_ = ПолучитьСтандартныеПараметры(Параметры); URL = "https://upload.twitter.com/1.1/media/upload.json"; - - Если Тип = "photo" Тогда - + + Если Тип = "photo" Тогда + Поля = Новый Структура; Поля.Вставить("media_data" , Base64Строка(Файл)); Поля.Вставить("media_category", Тип); - - Авторизация = СоздатьЗаголовокАвторизацииV1(Параметры_, Поля, ВидЗапроса, URL); + + Авторизация = СоздатьЗаголовокАвторизацииV1(Параметры_, Поля, ВидЗапроса, URL); Ответ = OPI_Инструменты.Post(URL, Поля, Авторизация, Ложь); - + Иначе - + Ответ = ЗагрузитьМедиаЧастями(Файл, Тип, ВидЗапроса, URL, Параметры_); - + КонецЕсли; - + Возврат Ответ; - + КонецФункции Функция ЗагрузитьМедиаЧастями(Знач Файл, Знач Тип, Знач ВидЗапроса, Знач URL, Параметры) - + Единица = 1024; Количество = 4; MediaKey = "media_key"; MIS = "media_id_string"; Command = "command"; Размер = Файл.Размер(); - + СоответствиеMIME = Новый Соответствие; СоответствиеMIME.Вставить("photo" , "image/jpeg"); СоответствиеMIME.Вставить("video" , "video/mp4"); СоответствиеMIME.Вставить("animated_gif", "image/gif"); - + РазмерЧасти = Количество * Единица * Единица; МассивЧтения = РазделитьДвоичныеДанные(Файл, РазмерЧасти); - + Поля = Новый Структура; Поля.Вставить(Command , "INIT"); Поля.Вставить("total_bytes" , OPI_Инструменты.ЧислоВСтроку(Размер)); Поля.Вставить("media_type" , СоответствиеMIME.Получить(Тип)); Поля.Вставить("media_category" , Тип); - + Авторизация = СоздатьЗаголовокАвторизацииV1(Параметры, Поля, ВидЗапроса, URL); ОтветИнициализации = OPI_Инструменты.Post(URL, Поля, Авторизация, Ложь); KeyИнициализации = ОтветИнициализации[MediaKey]; IDИнициализации = ОтветИнициализации[MIS]; - + Если Не ЗначениеЗаполнено(KeyИнициализации) Или Не ЗначениеЗаполнено(IDИнициализации) Тогда - Возврат ОтветИнициализации; + Возврат ОтветИнициализации; КонецЕсли; - + Счетчик = 0; - + Для Каждого Часть Из МассивЧтения Цикл - + Поля = Новый Структура; Поля.Вставить(Command , "APPEND"); Поля.Вставить("media_key" , KeyИнициализации); @@ -422,111 +422,111 @@ Поля.Вставить("media" , Часть); Авторизация = СоздатьЗаголовокАвторизацииV1(Параметры, Новый Структура, ВидЗапроса, URL); - + OPI_Инструменты.PostMultipart(URL, Поля, , , Авторизация); - + Счетчик = Счетчик + 1; - + КонецЦикла; - + Поля = Новый Структура; Поля.Вставить(Command , "FINALIZE"); Поля.Вставить("media_id", IDИнициализации); - + СтатусОбработки = ПолучитьСтатусОбработки(Параметры, Поля, URL); - + Если Не ТипЗнч(СтатусОбработки) = Тип("Строка") Тогда Возврат СтатусОбработки; КонецЕсли; - + Ответ = ОжидатьЗавершенияОбработки(СтатусОбработки, IDИнициализации, URL, Параметры); - + Возврат Ответ; - + КонецФункции Функция ОжидатьЗавершенияОбработки(Знач СтатусОбработки, Знач IDИнициализации, Знач URL, Знач Параметры) - + ProcessingInfo = "processing_info"; Command = "command"; Поля = Новый Структура; - + Поля.Вставить(Command , "STATUS"); Поля.Вставить("media_id", IDИнициализации); Пока Строка(СтатусОбработки) = "pending" Или Строка(СтатусОбработки) = "in_progress" Цикл - - Авторизация = СоздатьЗаголовокАвторизацииV1(Параметры, Поля, "GET", URL); - Ответ = OPI_Инструменты.Get(URL, Поля, Авторизация); + + Авторизация = СоздатьЗаголовокАвторизацииV1(Параметры, Поля, "GET", URL); + Ответ = OPI_Инструменты.Get(URL, Поля, Авторизация); Информация = Ответ[ProcessingInfo]; Если Не ЗначениеЗаполнено(Информация) Тогда Возврат Ответ; КонецЕсли; - + СтатусОбработки = Информация["state"]; - + Если Не ЗначениеЗаполнено(СтатусОбработки) Тогда Возврат Ответ; КонецЕсли; - + КонецЦикла; - + Если СтатусОбработки = "failed" Тогда ВызватьИсключение "Твиттер не смог обработать загруженное вами видео"; КонецЕсли; - + Возврат Ответ; - + КонецФункции Функция ПолучитьСтандартныеПараметры(Знач Параметры = "") - + // Здесь собрано определение данных, необходимых для работы. // Для Twitter это довольно значительный набор, что обсуловлено наличием сразу 2-х API, // которые, при этом, созданы не для разныз задач, но просто являются версиями друг друга. // Актуальной версией API является v2 и она требует получения временных токенов. Несмотря на то, // что Twitter настаивает на использовании этой актуальной версии, они как-то умудрились не перенести - // механизм загрузки файлов и некоторые другие из старой версии - v1.1. Поэтому что-то нужно делать + // механизм загрузки файлов и некоторые другие из старой версии - v1.1. Поэтому что-то нужно делать // на версии 1.1, а что-то на 2: вплоть до того что они убрали возможность постить твиты из v1.1, // но только через нее в твит можно добавить картинку. При этом способы авторизации и токены у них разные - + // Мировая гигокорпорация Илона Маска, кстати, напоминаю ;) - - // P.S Далее часто упоминается "страница настроек Twitter Developer" - это + + // P.S Далее часто упоминается "страница настроек Twitter Developer" - это // https://developer.twitter.com/en/portal/dashboard и выбор конкретного проекта из списка (значек c ключем) - - Параметры_ = Новый Соответствие; + + Параметры_ = Новый Соответствие; Разрешения = "tweet.read tweet.write tweet.moderate.write users.read " + "follows.read follows.write offline.access space.read mute.read " + "mute.write like.read like.write list.read list.write block.read " - + "block.write bookmark.read bookmark.write"; - + + "block.write bookmark.read bookmark.write"; + // Данные для API v2 - + // redirect_uri - URL вашего http-сервиса (или другого обработчика запросов) для авторизации // scope - набор разрешений для получаемого ключа. Может быть любой, но offline.access обязателен // client_id - Из OAuth 2.0 Client ID and Client Secret страницы настроек Twitter Developer // client_secret - Из OAuth 2.0 Client ID and Client Secret страницы настроек Twitter Developer // access_token - ПолучитьСсылкуАвторизации() -> Браузер -> code придет на redirect_uri -> ПолучитьТокен(code) // refresh_token - Приходит вместе с access_token и используется для его обновления (время жизни access_token - 2 ч) - // Обновление происходит методом ОбновитьТокен с новыми access_token и refresh_token. - // При следующем обновлении нужно использовать уже новый refresh_token, так что захардкодить - // не получится (access_token тоже не получится) - + // Обновление происходит методом ОбновитьТокен с новыми access_token и refresh_token. + // При следующем обновлении нужно использовать уже новый refresh_token, так что захардкодить + // не получится (access_token тоже не получится) + // |--> ОбновитьТокен() ->|access_token --> Используется в т-нии 2-х часов для запросов // | |refresh_token --| // |--------[через 2 ч.]-------------------| - + // Данные для API v1.1 - - // oauth_token - Из Authentication Tokens -> Access Token and Secret страницы настроек Twitter Developer + + // oauth_token - Из Authentication Tokens -> Access Token and Secret страницы настроек Twitter Developer // oauth_token_secret - Из Authentication Tokens -> Access Token and Secret страницы настроек Twitter Developer // oauth_consumer_key - Из Consumer Keys -> Access Token and Secret страницы настроек Twitter Developer // oauth_consumer_secret - Из Consumer Keys -> Access Token and Secret страницы настроек Twitter Developer - + // Эти токены обновлять не надо - + Параметры_.Вставить("redirect_uri" , ""); Параметры_.Вставить("scope" , Разрешения); Параметры_.Вставить("client_id" , ""); @@ -537,9 +537,9 @@ Параметры_.Вставить("oauth_token_secret" , ""); Параметры_.Вставить("oauth_consumer_key" , ""); Параметры_.Вставить("oauth_consumer_secret", ""); - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Параметры); - + Если ТипЗнч(Параметры) = Тип("Структура") Или ТипЗнч(Параметры) = Тип("Соответствие") Тогда Для Каждого ПереданныйПараметр Из Параметры Цикл Параметры_.Вставить(ПереданныйПараметр.Ключ, OPI_Инструменты.ЧислоВСтроку(ПереданныйПараметр.Значение)); @@ -551,7 +551,7 @@ КонецФункции Функция СоздатьЗаголовокАвторизацииV1(Знач Параметры, Знач Поля, Знач ВидЗапроса, Знач URL) - + ТекущаяДата = OPI_Инструменты.ПолучитьТекущуюДату(); ЗаголовокАвторизации = ""; МетодХэширования = "HMAC-SHA1"; @@ -565,123 +565,123 @@ ТаблицаПараметров = Новый ТаблицаЗначений; ТаблицаПараметров.Колонки.Добавить("Ключ"); ТаблицаПараметров.Колонки.Добавить("Значение"); - - Для Каждого Поле Из Поля Цикл - - НоваяСтрока = ТаблицаПараметров.Добавить(); + + Для Каждого Поле Из Поля Цикл + + НоваяСтрока = ТаблицаПараметров.Добавить(); НоваяСтрока.Ключ = Поле.Ключ; НоваяСтрока.Значение = Поле.Значение; - + КонецЦикла; - - НоваяСтрока = ТаблицаПараметров.Добавить(); + + НоваяСтрока = ТаблицаПараметров.Добавить(); НоваяСтрока.Ключ = OCK; НоваяСтрока.Значение = Параметры[OCK]; - - НоваяСтрока = ТаблицаПараметров.Добавить(); + + НоваяСтрока = ТаблицаПараметров.Добавить(); НоваяСтрока.Ключ = OTK; НоваяСтрока.Значение = Параметры[OTK]; - - НоваяСтрока = ТаблицаПараметров.Добавить(); + + НоваяСтрока = ТаблицаПараметров.Добавить(); НоваяСтрока.Ключ = "oauth_version"; НоваяСтрока.Значение = ВерсияАпи; - - НоваяСтрока = ТаблицаПараметров.Добавить(); + + НоваяСтрока = ТаблицаПараметров.Добавить(); НоваяСтрока.Ключ = "oauth_signature_method"; НоваяСтрока.Значение = МетодХэширования; - НоваяСтрока = ТаблицаПараметров.Добавить(); + НоваяСтрока = ТаблицаПараметров.Добавить(); НоваяСтрока.Ключ = "oauth_timestamp"; НоваяСтрока.Значение = ТекущаяДатаUNIX; - НоваяСтрока = ТаблицаПараметров.Добавить(); + НоваяСтрока = ТаблицаПараметров.Добавить(); НоваяСтрока.Ключ = "oauth_nonce"; НоваяСтрока.Значение = ТекущаяДатаUNIX; Для Каждого СтрокаТаблицы Из ТаблицаПараметров Цикл - + СтрокаТаблицы.Ключ = КодироватьСтроку(СтрокаТаблицы.Ключ, СпособКодированияСтроки.КодировкаURL); СтрокаТаблицы.Значение = КодироватьСтроку(СтрокаТаблицы.Значение, СпособКодированияСтроки.КодировкаURL); - + КонецЦикла; - + ТаблицаПараметров.Сортировать("Ключ"); - + Для Каждого СтрокаТаблицы Из ТаблицаПараметров Цикл - - СтрокаСигнатуры = СтрокаСигнатуры - + СтрокаТаблицы.Ключ - + "=" + + СтрокаСигнатуры = СтрокаСигнатуры + + СтрокаТаблицы.Ключ + + " =" + СтрокаТаблицы.Значение + "&"; - + КонецЦикла; - + СтрокаСигнатуры = Лев(СтрокаСигнатуры, СтрДлина(СтрокаСигнатуры) - 1); - СтрокаСигнатуры = вРег(ВидЗапроса) - + "&" - + КодироватьСтроку(URL, СпособКодированияСтроки.КодировкаURL) + СтрокаСигнатуры = вРег(ВидЗапроса) + + "&" + + КодироватьСтроку(URL , СпособКодированияСтроки.КодировкаURL) + "&" + КодироватьСтроку(СтрокаСигнатуры, СпособКодированияСтроки.КодировкаURL); - + Подпись = КодироватьСтроку(Параметры["oauth_consumer_secret"], СпособКодированияСтроки.КодировкаURL) - + "&" + + "&" + КодироватьСтроку(Параметры["oauth_token_secret"], СпособКодированияСтроки.КодировкаURL); - + Сигнатура = OPI_Криптография.HMAC(ПолучитьДвоичныеДанныеИзСтроки(Подпись) , ПолучитьДвоичныеДанныеИзСтроки(СтрокаСигнатуры) , ХешФункция.SHA1 , 64); - + Сигнатура = КодироватьСтроку(Base64Строка(Сигнатура), СпособКодированияСтроки.КодировкаURL); - - Разделитель = ""","; - ЗаголовокАвторизации = ЗаголовокАвторизации + + Разделитель = ""","; + ЗаголовокАвторизации = ЗаголовокАвторизации + "OAuth " - + "oauth_consumer_key=""" + Параметры[OCK] + Разделитель - + "oauth_token=""" + Параметры[OTK] + Разделитель + + "oauth_consumer_key =""" + Параметры[OCK] + Разделитель + + "oauth_token =""" + Параметры[OTK] + Разделитель + "oauth_signature_method=""" + МетодХэширования + Разделитель - + "oauth_timestamp=""" + ТекущаяДатаUNIX + Разделитель - + "oauth_nonce=""" + ТекущаяДатаUNIX + Разделитель - + "oauth_version=""" + ВерсияАпи + Разделитель - + "oauth_signature=""" + Сигнатура; - + + "oauth_timestamp =""" + ТекущаяДатаUNIX + Разделитель + + "oauth_nonce =""" + ТекущаяДатаUNIX + Разделитель + + "oauth_version =""" + ВерсияАпи + Разделитель + + "oauth_signature =""" + Сигнатура; + СоответствиеЗаголовка = Новый Соответствие; СоответствиеЗаголовка.Вставить("authorization", ЗаголовокАвторизации); - + Возврат СоответствиеЗаголовка; - + КонецФункции Функция СоздатьЗаголовокАвторизацииV2(Знач Параметры) - + СоответствиеВозврата = Новый Соответствие; СоответствиеВозврата.Вставить("Authorization", "Bearer " + Параметры["access_token"]); - + Возврат СоответствиеВозврата; - + КонецФункции Функция ПолучитьСтатусОбработки(Знач Параметры, Знач Поля, Знач URL) ProcessingInfo = "processing_info"; - Авторизация = СоздатьЗаголовокАвторизацииV1(Параметры, Поля, "POST", URL); - - Ответ = OPI_Инструменты.Post(URL, Поля, Авторизация, Ложь); + Авторизация = СоздатьЗаголовокАвторизацииV1(Параметры, Поля, "POST", URL); + + Ответ = OPI_Инструменты.Post(URL, Поля, Авторизация, Ложь); Информация = Ответ[ProcessingInfo]; - + Если Не ЗначениеЗаполнено(Информация) Тогда Возврат Ответ; КонецЕсли; - + СтатусОбработки = Информация["state"]; - + Если Не ЗначениеЗаполнено(СтатусОбработки) Тогда Возврат Ответ; Иначе Возврат СтатусОбработки; - КонецЕсли; - + КонецЕсли; + КонецФункции #КонецОбласти diff --git a/src/ru/OPI/src/CommonModules/OPI_VK/Module.bsl b/src/ru/OPI/src/CommonModules/OPI_VK/Module.bsl index ee166bd14b..352ba02489 100644 --- a/src/ru/OPI/src/CommonModules/OPI_VK/Module.bsl +++ b/src/ru/OPI/src/CommonModules/OPI_VK/Module.bsl @@ -1,4 +1,4 @@ -// OneScript: ./OInt/core/Modules/OPI_VK.os +// OneScript: ./OInt/core/Modules/OPI_VK.os // Lib: VK // CLI: vk @@ -22,7 +22,7 @@ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. +// SOFTWARE. // https://github.com/Bayselonarrend/OpenIntegrations // Если в не знаете с чего начать, то стоит найти метод ПолучитьСтандартныеПараметры() @@ -51,37 +51,37 @@ // Создать ссылку получения токена // Получение ссылки для интерактивного получения токена (access_token), который необходим // для дальнейших действий -// +// // Параметры: // app_id - Строка,Число - app_id из настроек приложения - app -// +// // Возвращаемое значение: -// Строка - URL, по которому необходимо перейти в браузере +// Строка - URL, по которому необходимо перейти в браузере Функция СоздатьСсылкуПолученияТокена(Знач App_id) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(App_id); - + // access_token нужно будет забрать из параметра в строке адреса браузера Возврат "https://oauth.vk.com/authorize?client_id=" + App_id + "&scope=offline,wall,groups,photos,stats,stories,ads,market,video" + "&v=5.131&response_type=token&redirect_uri=https://api.vk.com/blank.html"; - + КонецФункции - + #КонецОбласти #Область РаботаСГруппой // Создать пост // Создает пост с картинками -// +// // Параметры: // Текст - Строка - Текст поста - text -// МассивКартинок - Массив из Строка,ДвоичныеДанные - Массив картинок - pictures +// МассивКартинок - Массив из Строка,ДвоичныеДанные - Массив картинок - pictures // Реклама - Булево - Признак ""Это реклама"" - ad // СсылкаПодЗаписью - Строка - Ссылка (URL) под записью - url // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция СоздатьПост(Знач Текст @@ -89,49 +89,49 @@ , Знач Реклама = Ложь , Знач СсылкаПодЗаписью = "" , Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивКартинок); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); - МассивВложений = Новый Массив; - + МассивВложений = Новый Массив; + Для Каждого КартинкаПоста Из МассивКартинок Цикл - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); ОтветСоответствие = ПолучитьСоответствиеКартинки(КартинкаПоста, Параметры_, "Пост"); - + OwnerId = ОтветСоответствие.Получить("owner_id"); ObjectId = ОтветСоответствие.Получить("id"); - + Если Не ЗначениеЗаполнено(OwnerId) Или Не ЗначениеЗаполнено(ObjectId) Тогда Возврат ОтветСоответствие; КонецЕсли; - + OwnerId = OPI_Инструменты.ЧислоВСтроку(OwnerId); ObjectId = OPI_Инструменты.ЧислоВСтроку(ObjectId); - - ФотоID = "photo" + OwnerId + "_" + ObjectId; + + ФотоID = "photo" + OwnerId + "_" + ObjectId; МассивВложений.Добавить(ФотоID); - + КонецЦикла; Ответ = СоздатьСоставнойПост(Текст, МассивВложений, Реклама, СсылкаПодЗаписью, Параметры); - + Возврат Ответ; - + КонецФункции // Создать составной пост // Создает пост на основе массива идетификаторов объектов (картинок, видео и др.) -// +// // Параметры: // Текст - Строка - Текст поста - text -// Объекты - Массив из Строка - Массив идентификаторов вида photo123_123 - objects +// Объекты - Массив из Строка - Массив идентификаторов вида photo123_123 - objects // Реклама - Булево - Признак ""Это реклама"" - ad // СсылкаПодЗаписью - Строка - Ссылка (URL) под записью - url // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция СоздатьСоставнойПост(Знач Текст @@ -139,24 +139,24 @@ , Знач Реклама = Ложь , Знач СсылкаПодЗаписью = "" , Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Текст); - OPI_ПреобразованиеТипов.ПолучитьСтроку(СсылкаПодЗаписью); + OPI_ПреобразованиеТипов.ПолучитьСтроку(СсылкаПодЗаписью); OPI_ПреобразованиеТипов.ПолучитьБулево(Реклама); - + Параметры = ПолучитьСтандартныеПараметры(Параметры); - СтрокаВложений = СтрСоединить(Объекты, ","); + СтрокаВложений = СтрСоединить(Объекты, ","); СтрокаВложений = СтрокаВложений + СсылкаПодЗаписью; - + Параметры.Вставить("message" , Текст); Параметры.Вставить("attachments" , СтрокаВложений); Параметры.Вставить("mark_as_ads" , ?(Реклама, 1, 0)); Параметры.Вставить("close_comments" , ?(Реклама, 1, 0)); Ответ = OPI_Инструменты.Get("api.vk.com/method/wall.post", Параметры); - + Возврат Ответ; - + КонецФункции // Удалить пост @@ -165,20 +165,20 @@ // Параметры: // IDПоста - Строка,Число - ID поста - post // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция УдалитьПост(Знач IDПоста, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDПоста); - - Параметры_ = ПолучитьСтандартныеПараметры(Параметры); + + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("post_id", IDПоста); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/wall.delete", Параметры_); - + Возврат Ответ; - + КонецФункции // Создать опрос @@ -189,72 +189,72 @@ // МассивОтветов - Массив из Строка - Массив вариантов ответа - options // Картинка - Строка,ДвоичныеДанные - Картинка опроса - picture // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция СоздатьОпрос(Знач Вопрос, Знач МассивОтветов, Знач Картинка = "", Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Вопрос); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивОтветов); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Response_ = "response"; Если ЗначениеЗаполнено(Картинка) Тогда - + Ответ = ЗагрузитьФотоНаСервер(Картинка, Параметры_, "Опрос"); - + Фото = Ответ.Получить(Response_); - + Если ЗначениеЗаполнено(Фото) Тогда - + IDФото = Фото["id"]; - + Если Не ЗначениеЗаполнено(IDФото) Тогда Возврат Ответ; КонецЕсли; - + Иначе Возврат Ответ; КонецЕсли; - + КонецЕсли; - + Параметры_.Вставить("is_anonymous", 1); Параметры_.Вставить("is_multiple" , 0); - + Ответы = СтрСоединить(МассивОтветов, ""","""); - Ответы = "[""" + Ответы + """]"; - + Ответы = "[""" + Ответы + """]"; + Параметры_.Вставить("add_answers", Ответы); Параметры_.Вставить("photo_id" , OPI_Инструменты.ЧислоВСтроку(IDФото)); Параметры_.Вставить("question" , Вопрос); - + Опрос = OPI_Инструменты.Get("api.vk.com/method/polls.create", Параметры_); ОпросСоответствие = Опрос.Получить(Response_); - + Если Не ЗначениеЗаполнено(ОпросСоответствие) Тогда Возврат Опрос; КонецЕсли; - + OwnerId = ОпросСоответствие.Получить("owner_id"); ObjectId = ОпросСоответствие.Получить("id"); - + Если Не ЗначениеЗаполнено(OwnerId) Или Не ЗначениеЗаполнено(ObjectId) Тогда Возврат Опрос; КонецЕсли; - + ОпросID = "poll" + OPI_Инструменты.ЧислоВСтроку(OwnerId) - + "_" + + "_" + OPI_Инструменты.ЧислоВСтроку(ObjectId); - + Параметры_.Вставить("attachments", ОпросID); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/wall.post", Параметры_); - + Возврат Ответ; - + КонецФункции // Создать альбом @@ -264,24 +264,24 @@ // Наименование - Строка - Наименование альбома - title // Описание - Строка - Описание альбома - description // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция СоздатьАльбом(Знач Наименование, Знач Описание = "", Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Наименование); OPI_ПреобразованиеТипов.ПолучитьСтроку(Описание); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); - + Параметры_.Вставить("title" , Наименование); Параметры_.Вставить("description" , Описание); Параметры_.Вставить("upload_by_admins_only", 1); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/photos.createAlbum", Параметры_); - + Возврат Ответ; - + КонецФункции // Удалить альбом @@ -290,20 +290,20 @@ // Параметры: // IDАльбома - Строка,Число - ID альбома - album // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция УдалитьАльбом(Знач IDАльбома, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDАльбома); - - Параметры_ = ПолучитьСтандартныеПараметры(Параметры); + + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("album_id", OPI_Инструменты.ЧислоВСтроку(IDАльбома)); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/photos.deleteAlbum", Параметры_); - + Возврат Ответ; - + КонецФункции // Создать историю @@ -313,187 +313,187 @@ // Картинка - Строка,ДвоичныеДанные - Фон истории - picture // URL - Строка - URL для кнопки под историей - url // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция СоздатьИсторию(Знач Картинка, Знач URL = "", Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(URL); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("link_text" , "more"); Параметры_.Вставить("link_url" , URL); Параметры_.Вставить("add_to_news", "1"); - - Ответ = ЗагрузитьФотоНаСервер(Картинка, Параметры_, "История"); + + Ответ = ЗагрузитьФотоНаСервер(Картинка, Параметры_, "История"); Возврат Ответ; - + КонецФункции // Сохранить картинку в альбом // Сохраняет картинку в альбом сообщества // // Параметры: -// IDАльбома - Строка,Число - ID альбома - album +// IDАльбома - Строка,Число - ID альбома - album // Картинка - ДвоичныеДанные,Строка - Файл картинки - picture // Описание - Строка - Описание картинки - description // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция СохранитьКартинкуВАльбом(Знач IDАльбома, Знач Картинка, Знач Описание = "", Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDАльбома); OPI_ПреобразованиеТипов.ПолучитьСтроку(Описание); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); - + Параметры_.Вставить("album_id", IDАльбома); Параметры_.Вставить("caption" , Описание); - + Возврат ЗагрузитьФотоНаСервер(Картинка, Параметры_, "Альбом"); - + КонецФункции // Удалить картинку // Удалить картинку из альбома // // Параметры: -// IDКартинки - Строка,Число - ID картинки - pictureid +// IDКартинки - Строка,Число - ID картинки - pictureid // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция УдалитьКартинку(Знач IDКартинки, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDКартинки); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("photo_id", IDКартинки); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/photos.delete", Параметры_); - + Возврат Ответ; - + КонецФункции // Загрузить видео на сервер // Загружает видео в группу с возможностью его дальнейшего использования -// +// // Параметры: // Видео - Строка, ДвоичныеДанные - Файл видео - file // Наименование - Строка - Наименование видео - title // Описание - Строка - Описание видео - description // Альбом - Строка - ID альбома, если необходимо - album // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ЗагрузитьВидеоНаСервер(Знач Видео , Знач Наименование , Знач Описание = "" , Знач Альбом = "" , Знач Параметры = "") Экспорт - + Строка_ = "Строка"; Параметры = ПолучитьСтандартныеПараметры(Параметры); - + OPI_Инструменты.ДобавитьПоле("name" , Наименование, Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("description", Описание , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("album_id" , Альбом , Строка_, Параметры); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/video.save", Параметры); - + Результат = Ответ["response"]; - + Если Не ЗначениеЗаполнено(Результат) Тогда Возврат Ответ; КонецЕсли; - + URL = Результат["upload_url"]; - + Если Не ЗначениеЗаполнено(URL) Тогда Возврат Ответ; КонецЕсли; - + СоответствиеФайлов = Новый Соответствие; OPI_Инструменты.ДобавитьПоле("video_file.mp4", Видео, "ДвоичныеДанные", СоответствиеФайлов); - + РазмерДанных = СоответствиеФайлов["video_file.mp4"].Размер(); РазмерДанных = OPI_Инструменты.ЧислоВСтроку(РазмерДанных); - + Ответ = OPI_Инструменты.PostMultipart(URL, , СоответствиеФайлов, "video/mp4"); - + Возврат Ответ; - + КонецФункции // Загрузить фото на сервер // Загружает фото на сервер для его дальнейшего использования -// +// // Параметры: // Картинка - Строка, ДвоичныеДанные - Файл картинки - file // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json // Вид - Строка - Вид загрузки (Пост, Товар, История, Опрос, Прочее) - type -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ЗагрузитьФотоНаСервер(Знач Картинка, Знач Параметры = "", Знач Вид = "Пост") Экспорт - + Параметры = ПолучитьСтандартныеПараметры(Параметры); Метод = ОпределитьМетодЗагрузкиИзображений(Вид); Файлы = Новый Соответствие; - + Response_ = "response"; URL = "api.vk.com/method/"; Загрузка = URL + Метод["Загрузка"]; Сохранение = URL + Метод["Сохранение"]; - - Если ТипЗнч(Картинка) = Тип("Строка") Тогда + + Если ТипЗнч(Картинка) = Тип("Строка") Тогда КлючКартинка = СтрЗаменить(Картинка, ".", "___"); OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Картинка); Иначе КлючКартинка = "image___jpeg"; КонецЕсли; - + Файлы.Вставить(КлючКартинка, Картинка); - + Для Н = 1 По 5 Цикл - - Ответ = OPI_Инструменты.Get(Загрузка, Параметры); + + Ответ = OPI_Инструменты.Get(Загрузка, Параметры); Результат = Ответ[Response_]; - + Если ЗначениеЗаполнено(Результат) Тогда - + URL = Результат["upload_url"]; - + Если Не ЗначениеЗаполнено(URL) Тогда Возврат Ответ; КонецЕсли; - + Иначе Возврат Ответ; КонецЕсли; - + Параметры.Вставить("upload_url", URL); Ответ = OPI_Инструменты.PostMultipart(URL, Параметры, Файлы); - + Если ТипЗнч(Ответ) = Тип("Соответствие") Тогда Прервать; КонецЕсли; - + КонецЦикла; - + Если ТипЗнч(Ответ) <> Тип("Соответствие") Тогда Возврат ПолучитьСтрокуИзДвоичныхДанных(Ответ); КонецЕсли; ЗаполнитьПараметрыЗагрузкиФото(Метод, Ответ, Параметры); - + Ответ = OPI_Инструменты.Get(Сохранение, Параметры); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -507,22 +507,22 @@ // Наименование - Строка - Наименование обсуждения - title // ТекстПервогоСообщения - Строка - Текст первого сообщения - text // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция СоздатьОбсуждение(Знач Наименование, Знач ТекстПервогоСообщения, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Наименование); OPI_ПреобразованиеТипов.ПолучитьСтроку(ТекстПервогоСообщения); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("title", Наименование); Параметры_.Вставить("text" , ТекстПервогоСообщения); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/board.addTopic", Параметры_); - + Возврат Ответ; - + КонецФункции // Закрыть обсуждение @@ -532,20 +532,20 @@ // IDОбсуждения - Строка,Число - ID обсуждения - topic // УдалитьПолностью - Булево - Удалить полностью (Истина) или закрыть - remove // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ЗакрытьОбсуждение(Знач IDОбсуждения, Знач УдалитьПолностью = Ложь, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDОбсуждения); OPI_ПреобразованиеТипов.ПолучитьБулево(УдалитьПолностью); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("topic_id", IDОбсуждения); - - Метод = ?(УдалитьПолностью, "deleteTopic", "closeTopic"); + + Метод = ?(УдалитьПолностью, "deleteTopic", "closeTopic"); Ответ = OPI_Инструменты.Get("api.vk.com/method/board." + Метод, Параметры_); - + Возврат Ответ; КонецФункции @@ -556,18 +556,18 @@ // Параметры: // IDОбсуждения - Строка,Число - ID обсуждения - topic // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ОткрытьОбсуждение(Знач IDОбсуждения, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDОбсуждения); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("topic_id", IDОбсуждения); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/board.openTopic", Параметры_); - + Возврат Ответ; КонецФункции @@ -579,20 +579,20 @@ // IDОбсуждения - Строка,Число - ID обсуждения - topic // Текст - Строка - Текст сообщения - text // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция НаписатьВОбсуждение(Знач IDОбсуждения, Знач Текст, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDОбсуждения); OPI_ПреобразованиеТипов.ПолучитьСтроку(Текст); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("topic_id", IDОбсуждения); Параметры_.Вставить("message" , Текст); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/board.createComment", Параметры_); - + Возврат Ответ; КонецФункции @@ -608,26 +608,26 @@ // IDПоста - Строка,Число - ID поста - post // IDСтены - Строка,Число - ID стены расположения поста - wall // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ПоставитьЛайк(Знач IDПоста, Знач IDСтены = "", Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDПоста); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDСтены); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); IDСтены = ?(ЗначениеЗаполнено(IDСтены), IDСтены, Параметры_["owner_id"]); ОбъектВК = "wall" + IDСтены + "_" + OPI_Инструменты.ЧислоВСтроку(IDПоста); - + Параметры_.Вставить("type" , "post"); Параметры_.Вставить("object" , ОбъектВК); Параметры_.Вставить("item_id" , OPI_Инструменты.ЧислоВСтроку(IDПоста)); Параметры_.Вставить("owner_id" , OPI_Инструменты.ЧислоВСтроку(IDСтены)); Параметры_.Вставить("from_group" , 0); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/likes.add", Параметры_); - + Возврат Ответ; КонецФункции @@ -641,7 +641,7 @@ // ЦелеваяСтена - Строка,Число - ID целевой стены или группы - to // Рекламный - Булево - Признак рекламного поста - ad // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция СделатьРепост(Знач IDПоста @@ -649,25 +649,25 @@ , Знач ЦелеваяСтена = "" , Знач Рекламный = Ложь , Знач Параметры = "") Экспорт - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); GroupId = Параметры_["group_id"]; - + OPI_ПреобразованиеТипов.ПолучитьСтроку(GroupId); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDПоста); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDСтены); OPI_ПреобразованиеТипов.ПолучитьСтроку(ЦелеваяСтена); OPI_ПреобразованиеТипов.ПолучитьБулево(Рекламный); - - Источник = ?(ЗначениеЗаполнено(IDСтены), IDСтены, GroupId); + + Источник = ?(ЗначениеЗаполнено(IDСтены), IDСтены, GroupId); Приемник = ?(ЗначениеЗаполнено(ЦелеваяСтена), ЦелеваяСтена, GroupId); Параметры_.Вставить("object" , "wall" + Источник + "_" + OPI_Инструменты.ЧислоВСтроку(IDПоста)); Параметры_.Вставить("group_id" , СтрЗаменить(Приемник, "-", "")); - Параметры_.Вставить("mark_as_ads" , ?(Рекламный, 1, 0)); - + Параметры_.Вставить("mark_as_ads" , ?(Рекламный , 1 , 0)); + Ответ = OPI_Инструменты.Get("api.vk.com/method/wall.repost", Параметры_); - + Возврат Ответ; КонецФункции @@ -681,7 +681,7 @@ // Communitytoken - Строка - Токен бота чата сообщества, котрый можно получить в настройках - ct // Клавиатура - Строка - JSON клавиатуры. См.СформироватьКлавиатуру - keyboard // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция НаписатьСообщение(Знач Текст @@ -689,27 +689,27 @@ , Знач Communitytoken , Знач Клавиатура = "" , Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Текст); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDПользователя); OPI_ПреобразованиеТипов.ПолучитьСтроку(Communitytoken); OPI_ПреобразованиеТипов.ПолучитьСтроку(Клавиатура); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("access_token", Communitytoken); - + Параметры_.Вставить("user_id" , IDПользователя); Параметры_.Вставить("peer_id" , IDПользователя); - Параметры_.Вставить("parse_mode" , "Markdown"); + Параметры_.Вставить("parse_mode" , "Markdown"); Параметры_.Вставить("random_id" , 0); Параметры_.Вставить("message" , Текст); - + Если ЗначениеЗаполнено(Клавиатура) Тогда Параметры_.Вставить("keyboard", Клавиатура); КонецЕсли; - + Ответ = OPI_Инструменты.Get("api.vk.com/method/messages.send", Параметры_); - + Возврат Ответ; КонецФункции @@ -722,28 +722,28 @@ // IDСтены - Строка,Число - ID стены расположения поста - wall // Текст - Строка - Текст комментария - text // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция НаписатьКомментарий(Знач IDПоста, Знач IDСтены, Знач Текст, Знач Параметры = "") Экспорт Параметры_ = ПолучитьСтандартныеПараметры(Параметры); GroupId = Параметры_["group_id"]; - + OPI_ПреобразованиеТипов.ПолучитьСтроку(GroupId); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDПоста); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDСтены); OPI_ПреобразованиеТипов.ПолучитьСтроку(Текст); - - Параметры_.Вставить("owner_id" , IDСтены); + + Параметры_.Вставить("owner_id" , IDСтены); Параметры_.Вставить("from_group" , GroupId); Параметры_.Вставить("post_id" , IDПоста); Параметры_.Вставить("message" , Текст); - + Параметры_.Удалить("group_id"); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/wall.createComment", Параметры_); - + Возврат Ответ; КонецФункции @@ -754,35 +754,35 @@ // Параметры: // URL - Строка - URL для сокращения - url // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: -// Строка - Сокращенный URL +// Строка - Сокращенный URL Функция СократитьСсылку(Знач URL, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(URL); - + Response_ = "response"; Параметры_ = Новый Структура; - Параметры_ = ПолучитьСтандартныеПараметры(Параметры); + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("url", URL); - + Ответ = OPI_Инструменты.Get("https://api.vk.com/method/utils.getShortLink", Параметры_); Результат = Ответ[Response_]; - + Если ЗначениеЗаполнено(Результат) Тогда - + URL = Результат["short_url"]; - + Если ЗначениеЗаполнено(URL) Тогда Возврат URL; Иначе Возврат Ответ; КонецЕсли; - + Иначе Возврат Ответ; КонецЕсли; - + КонецФункции #КонецОбласти @@ -796,27 +796,27 @@ // ДатаНачала - Дата - Дата начала периода - datefrom // ДатаОкончания - Дата - Дата окончания периода - dateto // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ПолучитьСтатистику(Знач ДатаНачала, Знач ДатаОкончания, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьДату(ДатаНачала); OPI_ПреобразованиеТипов.ПолучитьДату(ДатаОкончания); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); - + ДатаНачала = OPI_Инструменты.UNIXTime(ДатаНачала); ДатаОкончания = OPI_Инструменты.UNIXTime(ДатаОкончания); - + Параметры_.Вставить("timestamp_from", ДатаНачала); Параметры_.Вставить("timestamp_to" , ДатаОкончания); Параметры_.Вставить("stats_groups" , "visitors, reach, activity"); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/stats.get", Параметры_); - + Возврат Ответ; - + КонецФункции // Получить статистику по постам @@ -825,47 +825,47 @@ // Параметры: // МассивИДПостов - Массив из Строка,Число - Массив ID постов - posts // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Массив из Произвольный - Массив данных статистики по постам Функция ПолучитьСтатистикуПостов(Знач МассивИДПостов, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивИДПостов); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); МассивОтветов = Новый Массив; МассивНабора = Новый Массив; МаксимумПостов = 30; Response_ = "response"; - + Для Каждого Пост Из МассивИДПостов Цикл - + МассивНабора.Добавить(OPI_Инструменты.ЧислоВСтроку(Пост)); - + Если МассивНабора.Количество() = МаксимумПостов Тогда - + СтрокаНомеров = СтрСоединить(МассивНабора, ","); Параметры_.Вставить("post_ids", СтрокаНомеров); - + Статистика = OPI_Инструменты.Get("api.vk.com/method/stats.getPostReach", Параметры_); МассивСтатистики = Статистика[Response_]; - + Для Каждого ЭлементСтатистики Из МассивСтатистики Цикл МассивОтветов.Добавить(ЭлементСтатистики); КонецЦикла; - + МассивНабора = Новый Массив; - + КонецЕсли; - + КонецЦикла; - + СтрокаНомеров = СтрСоединить(МассивНабора, ","); Параметры_.Вставить("post_ids", СтрокаНомеров); - + Статистика = OPI_Инструменты.Get("api.vk.com/method/stats.getPostReach", Параметры_); МассивСтатистики = Статистика[Response_]; - + Если ТипЗнч(МассивСтатистики) = Тип("Массив") Тогда Для Каждого ЭлементСтатистики Из МассивСтатистики Цикл МассивОтветов.Добавить(ЭлементСтатистики); @@ -873,9 +873,9 @@ КонецЕсли; Возврат МассивОтветов; - + КонецФункции - + #КонецОбласти #Область РаботаСРекламнымКабинетом @@ -887,24 +887,24 @@ // IDКабинета - Строка,Число - ID рекламного кабинета - cabinet // Наименование - Строка - Наименование кампании - title // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция СоздатьРекламнуюКампанию(Знач IDКабинета, Знач Наименование, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDКабинета); OPI_ПреобразованиеТипов.ПолучитьСтроку(Наименование); - + ТекущаяДата = OPI_Инструменты.ПолучитьТекущуюДату(); КонечнаяДата = ДобавитьМесяц(ТекущаяДата, 24); - - Параметры_ = ПолучитьСтандартныеПараметры(Параметры); + + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("account_id", IDКабинета); - + МассивСтруктур = Новый Массив; ДатаСтарт = OPI_Инструменты.UNIXTime(ТекущаяДата); ДатаСтоп = OPI_Инструменты.UNIXTime(КонечнаяДата); - + СтруктураКампании = Новый Структура; СтруктураКампании.Вставить("type" , "promoted_posts"); СтруктураКампании.Вставить("name" , Наименование); @@ -913,17 +913,17 @@ СтруктураКампании.Вставить("start_time" , ДатаСтарт); СтруктураКампании.Вставить("stop_time" , ДатаСтоп); СтруктураКампании.Вставить("status" , 1); - + МассивСтруктур.Добавить(СтруктураКампании); - + JSONДата = OPI_Инструменты.JSONСтрокой(МассивСтруктур); - + Параметры_.Вставить("data", JSONДата); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/ads.createCampaigns", Параметры_); - + Возврат Ответ; - + КонецФункции // Создать рекламное объявление @@ -936,7 +936,7 @@ // IDПоста - Строка,Число - ID поста, используемого в качетсве рекламы - post // IDКабинета - Строка,Число - ID рекламного кабинета - cabinet // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция СоздатьРекламноеОбъявление(Знач НомерКампании @@ -945,20 +945,20 @@ , Знач IDПоста , Знач IDКабинета , Знач Параметры = "") Экспорт - - Параметры_ = ПолучитьСтандартныеПараметры(Параметры); + + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); GroupId = Параметры_["group_id"]; - + OPI_ПреобразованиеТипов.ПолучитьСтроку(GroupId); OPI_ПреобразованиеТипов.ПолучитьСтроку(НомерКампании); OPI_ПреобразованиеТипов.ПолучитьСтроку(ДневнойЛимит); OPI_ПреобразованиеТипов.ПолучитьСтроку(НомерКатегории); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDПоста); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDКабинета); - + Линк = "https://vk.com/wall-" + GroupId + "_" + IDПоста; - - МассивСтруктур = Новый Массив; + + МассивСтруктур = Новый Массив; СтруктураКампании = Новый Структура; СтруктураКампании.Вставить("campaign_id" , НомерКампании); СтруктураКампании.Вставить("ad_format" , 9); @@ -976,18 +976,18 @@ СтруктураКампании.Вставить("status" , 1); СтруктураКампании.Вставить("name" , "Объявление"); СтруктураКампании.Вставить("link_url" , Линк); - + МассивСтруктур.Добавить(СтруктураКампании); - + OPI_ПреобразованиеТипов.ПолучитьСтроку(МассивСтруктур, Истина); - + Параметры_.Вставить("data" , МассивСтруктур); Параметры_.Вставить("account_id" , IDКабинета); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/ads.createAds", Параметры_); - + Возврат Ответ; - + КонецФункции // Приостановить рекламное объявление @@ -995,36 +995,36 @@ // // Параметры: // IDКабинета - Строка,Число - ID рекламного кабинета - cabinet -// IDОбъявления - Строка,Число - ID объявления - adv +// IDОбъявления - Строка,Число - ID объявления - adv // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ПриостановитьРекламноеОбъявление(Знач IDКабинета, Знач IDОбъявления, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(IDКабинета); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDОбъявления); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("account_id", IDКабинета); - - МассивСтруктур = Новый Массив; + + МассивСтруктур = Новый Массив; СтруктураКампании = Новый Структура; - + СтруктураКампании.Вставить("ad_id" , IDОбъявления); СтруктураКампании.Вставить("status" , 0); - + МассивСтруктур.Добавить(СтруктураКампании); - + OPI_ПреобразованиеТипов.ПолучитьСтроку(МассивСтруктур, Истина); - + Параметры_.Вставить("data", МассивСтруктур); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/ads.updateAds", Параметры_); - + Возврат Ответ; - + КонецФункции // Получить список рекламных категорий @@ -1032,14 +1032,14 @@ // // Параметры: // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ПолучитьСписокРекламныхКатегорий(Знач Параметры = "") Экспорт - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Ответ = OPI_Инструменты.Get("api.vk.com/method/ads.getCategories", Параметры_); - + Возврат Ответ; КонецФункции @@ -1053,52 +1053,52 @@ // // Параметры: // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из Строка - Ключ - ID, Значение - Имя Функция ПолучитьСписокКатегорийТоваров(Знач Параметры = "") Экспорт - + Response_ = "response"; Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Ответ = OPI_Инструменты.Get("api.vk.com/method/market.getCategories", Параметры_); Результат = Ответ[Response_]; - + Если ЗначениеЗаполнено(Результат) Тогда - + Количество = Результат["count"]; - + Если Не ЗначениеЗаполнено(Количество) Тогда Возврат Ответ; КонецЕсли; - + Иначе Возврат Ответ; КонецЕсли; - + Параметры_.Вставить("count", Количество); - Ответ = OPI_Инструменты.Get("api.vk.com/method/market.getCategories", Параметры_); - Результат = Ответ[Response_]; - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.getCategories", Параметры_); + Результат = Ответ[Response_]; + Если ЗначениеЗаполнено(Результат) Тогда - + Категории = Результат["items"]; - + Если Не ЗначениеЗаполнено(Категории) Тогда Возврат Ответ; КонецЕсли; - + Иначе Возврат Ответ; КонецЕсли; - + СоответствиеКатегорий = Новый Соответствие; - - Для Каждого Категория Из Категории Цикл + + Для Каждого Категория Из Категории Цикл СоответствиеКатегорий.Вставить(Категория["id"], Категория["name"]); КонецЦикла; - + Возврат СоответствиеКатегорий; - + КонецФункции // Получить список товаров @@ -1107,60 +1107,60 @@ // Параметры: // Подборка - Строка,Число - ID подборки, если нужен отбор - sel // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - Массив соответствий товаров Функция ПолучитьСписокТоваров(Знач Подборка = "", Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Подборка); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("count" , 200); Параметры_.Вставить("extended" , 1); Параметры_.Вставить("with_disabled", 1); - + Если ЗначениеЗаполнено(Подборка) Тогда - Параметры_.Вставить("album_id", Подборка); + Параметры_.Вставить("album_id", Подборка); КонецЕсли; - + МассивТоваров = Новый Массив; ПолучитьСписокТоваровРекурсивно(МассивТоваров, Параметры_); - + Возврат МассивТоваров; - + КонецФункции // Получить товары по ID // Получает информацию о товарах по массиву ID // // Параметры: -// Товары - Строка, Массив Из Строка - Массив ID товаров - items +// Товары - Строка, Массив Из Строка - Массив ID товаров - items // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ПолучитьТоварыПоИД(Знач Товары, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Товары); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); СтрокаТоваров = ""; Owner = "owner_id"; - - Для Каждого Товар Из Товары Цикл + + Для Каждого Товар Из Товары Цикл ТекущийТовар = Параметры_[Owner] + "_" + Товар; ТекущийТовар = OPI_Инструменты.ЧислоВСтроку(ТекущийТовар); СтрокаТоваров = СтрокаТоваров + ТекущийТовар + ","; КонецЦикла; - + СтрокаТоваров = Лев(СтрокаТоваров, СтрДлина(СтрокаТоваров) - 1); Параметры_.Вставить("item_ids", СтрокаТоваров); Параметры_.Вставить("extended", 1); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.getById", Параметры_); - + Возврат Ответ; - + КонецФункции // Добавить товар @@ -1170,13 +1170,13 @@ // ОписаниеТовара - Соответствие Из КлючИЗначение - См.ПолучитьОписаниеТовара - product - JSON описание товара или путь // Подборка - Строка - ID подборка для помещения товара, если необходимо - sel // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK -Функция ДобавитьТовар(Знач ОписаниеТовара, Знач Подборка = "", Знач Параметры = "") Экспорт - - Возврат УправлениеТоваром(ОписаниеТовара, , Подборка, Параметры); - +Функция ДобавитьТовар(Знач ОписаниеТовара, Знач Подборка = "", Знач Параметры = "") Экспорт + + Возврат УправлениеТоваром(ОписаниеТовара, , Подборка, Параметры); + КонецФункции // Изменить товар @@ -1185,15 +1185,15 @@ // Параметры: // Товар - Число,Строка - Идентификатор изменяемого товара - item // ОписаниеТовара - Соответствие Из КлючИЗначение - См.ПолучитьОписаниеТовара - product - JSON описание товара или путь -// Подборка - Строка - Идентификатор новой подборки, если необходимо - sel +// Подборка - Строка - Идентификатор новой подборки, если необходимо - sel // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ИзменитьТовар(Знач Товар, Знач ОписаниеТовара, Знач Подборка = "", Знач Параметры = "") Экспорт - - Возврат УправлениеТоваром(ОписаниеТовара, Товар, Подборка, Параметры); - + + Возврат УправлениеТоваром(ОписаниеТовара, Товар, Подборка, Параметры); + КонецФункции // Удалить товар @@ -1202,20 +1202,20 @@ // Параметры: // Товар - Строка,Число - ID товара - item // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция УдалитьТовар(Знач Товар, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Товар); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("item_id", Товар); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.delete", Параметры_); - + Возврат Ответ; - + КонецФункции // Сгруппировать товары @@ -1225,37 +1225,37 @@ // МассивТоваров - Массив Из Строка - Массив ID товаров - items // СуществующаяГруппа - Строка - ID существующей группы, если необходимо - sellgroup // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция СгруппироватьТовары(Знач МассивТоваров, Знач СуществующаяГруппа = "", Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(СуществующаяГруппа); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивТоваров); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); МассивТоваров_ = Новый Массив; - + Для Каждого Товар Из МассивТоваров Цикл МассивТоваров_.Добавить(OPI_Инструменты.ЧислоВСтроку(Товар)); КонецЦикла; - + Товары = СтрСоединить(МассивТоваров_, ","); - + Параметры_.Вставить("item_ids", Товары); - + Если ЗначениеЗаполнено(СуществующаяГруппа) Тогда Параметры_.Вставить("item_group_id", СуществующаяГруппа); КонецЕсли; - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.groupItems", Параметры_); - + Возврат Ответ; КонецФункции // Получить описание товара. !NOCLI -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - Пустое описание товара: // *Имя - Строка - Имя товара @@ -1275,27 +1275,27 @@ // *SKU - Строка - SKU // *ДоступныйОстаток - Число - Остаток. -1 - не ограничено Функция ПолучитьОписаниеТовара() Экспорт - + Товар = Новый Соответствие(); Товар.Вставить("Имя" , "Новый товар"); // Имя товара Товар.Вставить("Описание" , "Описание товара"); // Описание товара Товар.Вставить("Категория" , "20173"); // См ПолучитьСписокКатегорийТоваров() Товар.Вставить("Цена" , 1); // Цена. - Товар.Вставить("СтараяЦена" , Неопределено); // Для отражения изменения цены + Товар.Вставить("СтараяЦена" , Неопределено); // Для отражения изменения цены Товар.Вставить("ОсновноеФото" , Неопределено); // ДД или путь к осн. фото Товар.Вставить("URL" , Неопределено); // Ссылка на страницу магазина Товар.Вставить("ДополнительныеФото" , Новый Массив); // Массив путей или ДД для доп. фото Товар.Вставить("ЗначенияСвойств" , Новый Массив); // Значения свойств (варианты). Максимум 2 - Товар.Вставить("ГлавныйВГруппе" , Ложь); // Сделать главным в своей группе + Товар.Вставить("ГлавныйВГруппе" , Ложь); // Сделать главным в своей группе Товар.Вставить("Ширина" , Неопределено); // В миллиметрах Товар.Вставить("Высота" , Неопределено); // В миллиметрах Товар.Вставить("Глубина" , Неопределено); // В миллиметрах Товар.Вставить("Вес" , Неопределено); // В граммах Товар.Вставить("SKU" , Неопределено); // Артикул Товар.Вставить("ДоступныйОстаток" , 1); - + Возврат Товар; - + КонецФункции #КонецОбласти @@ -1307,19 +1307,19 @@ // // Параметры: // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - Массив соответствий подборок Функция ПолучитьСписокПодборок(Знач Параметры = "") Экспорт - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("count", 100); - + МассивАльбомов = Новый Массив; ПолучитьСписокАльбомовРекурсивно(МассивАльбомов, Параметры_); - + Возврат МассивАльбомов; - + КонецФункции // Получить подборки по ID @@ -1328,29 +1328,29 @@ // Параметры: // Подборки - Строка, Массив Из Строка - ID подборок - sels // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ПолучитьПодборкиПоИД(Знач Подборки, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Подборки); - - Параметры_ = ПолучитьСтандартныеПараметры(Параметры); + + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Подборки_ = Новый Массив; СтрокаПодборок = ""; - + Для Каждого Подборка Из Подборки Цикл - Подборки_.Добавить(OPI_Инструменты.ЧислоВСтроку(Подборка)); - КонецЦикла; - + Подборки_.Добавить(OPI_Инструменты.ЧислоВСтроку(Подборка)); + КонецЦикла; + СтрокаПодборок = СтрСоединить(Подборки_, ","); - + Параметры_.Вставить("album_ids", СтрокаПодборок); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.getAlbumById", Параметры_); - + Возврат Ответ; - + КонецФункции // Создать подборку товаров @@ -1362,7 +1362,7 @@ // Основная - Булево - Основная - main // Скрытая - Булево - Скрытая - hidden // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция СоздатьПодборкуТоваров(Знач Название @@ -1370,9 +1370,9 @@ , Знач Основная = Ложь , Знач Скрытая = Ложь , Знач Параметры = "") Экспорт - + Возврат УправлениеПодборкой(Название, Картинка, , Основная, Скрытая, Параметры); - + КонецФункции // Изменить подборку товаров @@ -1385,7 +1385,7 @@ // Основная - Булево - Основная - main // Скрытая - Булево - Скрытая - hidden // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ИзменитьПодборкуТоваров(Знач Название @@ -1394,9 +1394,9 @@ , Знач Основная = Ложь , Знач Скрытая = Ложь , Знач Параметры = "") Экспорт - + Возврат УправлениеПодборкой(Название, Картинка, Подборка, Основная, Скрытая, Параметры); - + КонецФункции // Добавить товар в подборку @@ -1406,56 +1406,56 @@ // МассивТоваров - Массив из Строка, Число - Массив товаров или товар - items // Подборка - Строка - ID подборки - sel // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ДобавитьТоварВПодборку(Знач МассивТоваров, Знач Подборка, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивТоваров); OPI_ПреобразованиеТипов.ПолучитьСтроку(Подборка); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); МассивТоваров_ = Новый Массив; - + Для Каждого Товар Из МассивТоваров Цикл - МассивТоваров_.Добавить(OPI_Инструменты.ЧислоВСтроку(Товар)); - КонецЦикла; - + МассивТоваров_.Добавить(OPI_Инструменты.ЧислоВСтроку(Товар)); + КонецЦикла; + СписокТоваров = СтрСоединить(МассивТоваров_, ","); - + Параметры_.Вставить("item_ids" , СписокТоваров); Параметры_.Вставить("album_ids", Подборка); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.addToAlbum", Параметры_); - + Возврат Ответ; - + КонецФункции // Удалить товар из подборки // Удаляет ранее добавленный товар из подборки -// +// // Параметры: // Товар - Строка - ID товара - item // Подборка - Строка - ID подборки - sel // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция УдалитьТоварИзПодборки(Знач Товар, Знач Подборка, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Товар); OPI_ПреобразованиеТипов.ПолучитьСтроку(Подборка); Параметры_ = ПолучитьСтандартныеПараметры(Параметры); - + Параметры_.Вставить("item_id" , Товар); Параметры_.Вставить("album_ids", Подборка); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.removeFromAlbum", Параметры_); - + Возврат Ответ; - + КонецФункции // Удалить подборку @@ -1464,20 +1464,20 @@ // Параметры: // Подборка - Строка - ID подборки - sel // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция УдалитьПодборку(Знач Подборка, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Подборка); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("album_id", Подборка); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.deleteAlbum", Параметры_); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -1486,167 +1486,167 @@ // Получить список свойств // Получает список свойств товаров группы -// +// // Параметры: // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ПолучитьСписокСвойств(Знач Параметры = "") Экспорт - + Response_ = "response"; Параметры_ = ПолучитьСтандартныеПараметры(Параметры); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.getProperties", Параметры_); Свойства = Ответ[Response_]["items"]; - + Возврат Свойства; - + КонецФункции // Создать свойство товара // Создает новое свойство для использования в товарах -// +// // Параметры: // Название - Строка - Название свойства - title // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция СоздатьСвойствоТовара(Знач Название, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Название); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("title", Название); - - Ответ = OPI_Инструменты.Get("api.vk.com/method/market.addProperty", Параметры_); - + + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.addProperty", Параметры_); + Возврат Ответ; КонецФункции // Изменить свойство товара // Изменяет существующее свойство товара -// +// // Параметры: // Название - Строка - Новое название - title // Свойство - Строка,Число - ID свойства - prop // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ИзменитьСвойствоТовара(Знач Название, Знач Свойство, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Название); OPI_ПреобразованиеТипов.ПолучитьСтроку(Свойство); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("title" , Название); Параметры_.Вставить("property_id", Свойство); Параметры_.Вставить("type" , "text"); - - Ответ = OPI_Инструменты.Get("api.vk.com/method/market.editProperty", Параметры_); - + + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.editProperty", Параметры_); + Возврат Ответ; КонецФункции // Удалить свойство товара // Удаляет существующее свойство товара -// +// // Параметры: // Свойство - Строка,Число - ID свойства - prop // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция УдалитьСвойствоТовара(Знач Свойство, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Свойство); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("property_id", Свойство); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.deleteProperty", Параметры_); - + Возврат Ответ; - + КонецФункции // Добавить вариант свойства товара // Добавляет вариант для существующего свойства -// +// // Параметры: // Значение - Строка - Значение свойства - value // Свойство - Строка,Число - ID свойства, куда добавляется вариант - prop // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ДобавитьВариантСвойстваТовара(Знач Значение, Знач Свойство, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Свойство); OPI_ПреобразованиеТипов.ПолучитьСтроку(Значение); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("property_id", Свойство); Параметры_.Вставить("title" , Значение); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.addPropertyVariant", Параметры_); - + Возврат Ответ; - + КонецФункции // Изменить вариант свойства товара // Изменяет значение варианта существующего свойства товара -// +// // Параметры: // Значение - Строка - Новое значение свойства - value // Свойство - Строка,Число - ID свойства - prop // Вариант - Строка,Число - ID варианта - option // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ИзменитьВариантСвойстваТовара(Знач Значение, Знач Свойство, Знач Вариант, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Значение); OPI_ПреобразованиеТипов.ПолучитьСтроку(Свойство); OPI_ПреобразованиеТипов.ПолучитьСтроку(Вариант); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("property_id", Свойство); Параметры_.Вставить("variant_id" , Вариант); Параметры_.Вставить("title" , Значение); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.editPropertyVariant", Параметры_); - + Возврат Ответ; - + КонецФункции // Удалить вариант свойства товара // Удаляет ранее созданный вариант свойства -// +// // Параметры: // Вариант - Строка,Число - ID варианта - option // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция УдалитьВариантСвойстваТовара(Знач Вариант, Знач Параметры = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Вариант); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("variant_id", Вариант); - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market.deletePropertyVariant", Параметры_); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -1655,22 +1655,22 @@ // Получить список заказов // Возвращает список заказов сообщества -// +// // Параметры: // Параметры - Структура из Строка - См.ПолучитьСтандартныеПараметры - auth - JSON авторизации или путь к .json -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от VK Функция ПолучитьСписокЗаказов(Знач Параметры = "") Экспорт - + Параметры = ПолучитьСтандартныеПараметры(Параметры); Параметры.Вставить("count", 50); - + МассивЗаказов = Новый Массив; ПолучитьСписокЗаказовРекурсивно(МассивЗаказов, Параметры); - + Возврат МассивЗаказов; - + КонецФункции #КонецОбласти @@ -1679,40 +1679,40 @@ // Сформировать клавиатуру // Формирует клавиатуру по массиву кнопок -// +// // Параметры: // МассивКнопок - Массив из Строка - Массив заголовков кнопок - buttons -// +// // Возвращаемое значение: // Строка - JSON клавиатуры Функция СформироватьКлавиатуру(Знач МассивКнопок) Экспорт - - OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивКнопок); - + + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивКнопок); + Клавиатура = Новый Структура; МассивКлавиатуры = Новый Массив; МассивБлока = Новый Массив; - + Для Каждого Действие Из МассивКнопок Цикл - + Кнопка = Новый Структура; - Выражение = Новый Структура; - + Выражение = Новый Структура; + Выражение.Вставить("type" , "text"); Выражение.Вставить("label", Действие); - + Кнопка.Вставить("action", Выражение); МассивБлока.Добавить(Кнопка); - + КонецЦикла; - + МассивКлавиатуры.Добавить(МассивБлока); - - Клавиатура.Вставить("buttons" , МассивКлавиатуры); + + Клавиатура.Вставить("buttons" , МассивКлавиатуры); Клавиатура.Вставить("one_time", Ложь); - + Возврат OPI_Инструменты.JSONСтрокой(Клавиатура); - + КонецФункции #КонецОбласти @@ -1722,29 +1722,29 @@ #Область СлужебныеПроцедурыИФункции Функция ПолучитьСтандартныеПараметры(Знач Параметры = "") - + // Здесь собрано определение данных для работы с VK API // Вы можете переопределять их, передавая в качестве параметра // Совпадающие поля будут перезаписаны с приоритетом параметра функции - + Параметры_ = Новый Структура; - + // access_token - можно получить в браузере по URL из функции СоздатьСсылкуПолученияТокена() // from_group - действия будут выполняться от лица группы // owner_id - id группы с "-" в начале. Можно найти в настройках группы ВК или в ее URL, если не был // установлен свой // app_id - id приложения, которое необходимо создать в профиле на странице для разработчиков // group_id - owner_id, но без "-" - + Параметры_.Вставить("access_token" , ""); Параметры_.Вставить("from_group" , "1"); Параметры_.Вставить("owner_id" , ""); Параметры_.Вставить("v" , "5.131"); Параметры_.Вставить("app_id" , ""); Параметры_.Вставить("group_id" , ""); - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Параметры); - + Если ТипЗнч(Параметры) = Тип("Структура") Или ТипЗнч(Параметры) = Тип("Соответствие") Тогда Для Каждого ПереданныйПараметр Из Параметры Цикл Параметры_.Вставить(ПереданныйПараметр.Ключ, OPI_Инструменты.ЧислоВСтроку(ПереданныйПараметр.Значение)); @@ -1756,32 +1756,32 @@ КонецФункции Функция ПолучитьИДКартинки(Знач Картинка, Знач Параметры, Знач Вид) - - Response_ = "response"; + + Response_ = "response"; Ответ = ЗагрузитьФотоНаСервер(Картинка, Параметры, Вид); Результат = Ответ[Response_]; Если ЗначениеЗаполнено(Результат) Тогда ИДФото = Результат["photo_id"]; - + Если Не ЗначениеЗаполнено(ИДФото) Тогда - Возврат Ответ; + Возврат Ответ; КонецЕсли; - + Иначе Возврат Ответ; КонецЕсли; - + ИДФото = OPI_Инструменты.ЧислоВСтроку(ИДФото); Возврат ИДФото; - + КонецФункции Функция ПолучитьСоответствиеКартинки(Знач Картинка, Знач Параметры, Знач Вид) - - Ответ = ЗагрузитьФотоНаСервер(Картинка, Параметры, Вид); + + Ответ = ЗагрузитьФотоНаСервер(Картинка, Параметры, Вид); ОтветМассив = Ответ.Получить("response"); - + Если Не ЗначениеЗаполнено(ОтветМассив) Или Не ТипЗнч(ОтветМассив) = Тип("Массив") Тогда Возврат Ответ; Иначе @@ -1791,140 +1791,140 @@ ОтветСоответствие = ОтветМассив[0]; КонецЕсли; КонецЕсли; - + Возврат ОтветСоответствие; - + КонецФункции Функция ПолучитьМассивПодборок(Знач Подборки, Знач Параметры = "") - - Response_ = "response"; - Подборки = ПолучитьПодборкиПоИД(Подборки, Параметры); + + Response_ = "response"; + Подборки = ПолучитьПодборкиПоИД(Подборки, Параметры); Результат = Подборки[Response_]; - + Если ЗначениеЗаполнено(Результат) Тогда - + МассивПодборок = Результат["items"]; - + Если Не ЗначениеЗаполнено(МассивПодборок) Тогда - Возврат Подборки; + Возврат Подборки; КонецЕсли; - + Иначе Возврат Подборки; КонецЕсли; - + Возврат МассивПодборок; - + КонецФункции Функция ОпределитьМетодЗагрузкиИзображений(Знач Вид) - + СоответствиеМетодов = Новый Соответствие; Загрузка = "Загрузка"; Сохранение = "Сохранение"; Способ = "Способ"; Фото = "Фото"; - + Если Вид = "Пост" Тогда - + СоответствиеМетодов.Вставить(Загрузка , "photos.getWallUploadServer"); СоответствиеМетодов.Вставить(Сохранение, "photos.saveWallPhoto"); СоответствиеМетодов.Вставить(Фото , "photo"); СоответствиеМетодов.Вставить(Способ , 1); - + ИначеЕсли Вид = "Товар" Тогда - + СоответствиеМетодов.Вставить(Загрузка , "market.getProductPhotoUploadServer"); СоответствиеМетодов.Вставить(Сохранение, "market.saveProductPhoto"); СоответствиеМетодов.Вставить(Способ , 2); - + ИначеЕсли Вид = "История" Тогда - + СоответствиеМетодов.Вставить(Загрузка , "stories.getPhotoUploadServer"); СоответствиеМетодов.Вставить(Сохранение, "stories.save"); СоответствиеМетодов.Вставить(Способ , 3); - + ИначеЕсли Вид = "Опрос" Тогда - + СоответствиеМетодов.Вставить(Загрузка , "polls.getPhotoUploadServer"); СоответствиеМетодов.Вставить(Сохранение, "polls.savePhoto"); СоответствиеМетодов.Вставить(Фото , "photo"); СоответствиеМетодов.Вставить(Способ , 1); - + Иначе - + СоответствиеМетодов.Вставить(Загрузка , "photos.getUploadServer"); СоответствиеМетодов.Вставить(Сохранение, "photos.save"); СоответствиеМетодов.Вставить(Фото , "photos_list"); СоответствиеМетодов.Вставить(Способ , 1); - + КонецЕсли; - + Возврат СоответствиеМетодов; - + КонецФункции Функция ПолучитьСоответствиеПараметровТовара() - + Поля = Новый Соответствие(); - Поля.Вставить("Имя" , "name"); - Поля.Вставить("Описание" , "description"); - Поля.Вставить("Категория" , "category_id"); - Поля.Вставить("Цена" , "price"); - Поля.Вставить("СтараяЦена" , "old_price"); + Поля.Вставить("Имя" , "name"); + Поля.Вставить("Описание" , "description"); + Поля.Вставить("Категория" , "category_id"); + Поля.Вставить("Цена" , "price"); + Поля.Вставить("СтараяЦена" , "old_price"); Поля.Вставить("URL" , "url"); - Поля.Вставить("ГлавныйВГруппе" , "is_main_variant"); - Поля.Вставить("Ширина" , "dimension_width"); - Поля.Вставить("Высота" , "dimension_height"); - Поля.Вставить("Глубина" , "dimension_length"); - Поля.Вставить("Вес" , "weight"); - Поля.Вставить("SKU" , "sku"); + Поля.Вставить("ГлавныйВГруппе" , "is_main_variant"); + Поля.Вставить("Ширина" , "dimension_width"); + Поля.Вставить("Высота" , "dimension_height"); + Поля.Вставить("Глубина" , "dimension_length"); + Поля.Вставить("Вес" , "weight"); + Поля.Вставить("SKU" , "sku"); Поля.Вставить("ДоступныйОстаток" , "stock_amount"); - + Возврат Поля; КонецФункции Функция УправлениеТоваром(Знач ОписаниеТовара, Знач ИДТовара = "", Знач Подборка = "", Знач Параметры = "") - + OPI_ПреобразованиеТипов.ПолучитьСтроку(ИДТовара); OPI_ПреобразованиеТипов.ПолучитьСтроку(Подборка); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(ОписаниеТовара); - + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Параметры_.Вставить("v", "5.199"); - + Response_ = "response"; - + ЗаполнитьПоляЗапросаТовара(ОписаниеТовара, Параметры_); - - Если ЗначениеЗаполнено(ИДТовара) Тогда + + Если ЗначениеЗаполнено(ИДТовара) Тогда Параметры_.Вставить("item_id", ИДТовара); - Метод = "edit"; - Иначе + Метод = "edit"; + Иначе Метод = "add"; КонецЕсли; - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market." + Метод, Параметры_); Результат = Ответ[Response_]; - - Если Не ЗначениеЗаполнено(ИДТовара) И ЗначениеЗаполнено(Результат) Тогда - + + Если Не ЗначениеЗаполнено(ИДТовара) И ЗначениеЗаполнено(Результат) Тогда + ИДТовара = Результат["market_item_id"]; - + Если Не ЗначениеЗаполнено(ИДТовара) Тогда - Возврат Ответ; + Возврат Ответ; КонецЕсли; - + Иначе Возврат Ответ; КонецЕсли; - + Если ЗначениеЗаполнено(Подборка) И ЗначениеЗаполнено(ИДТовара) Тогда ДобавитьТоварВПодборку(ИДТовара, Подборка, Параметры_); КонецЕсли; - + Возврат Ответ; КонецФункции @@ -1935,263 +1935,263 @@ , Знач Основная = Ложь , Знач Скрытая = Ложь , Знач Параметры = "") - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Название); OPI_ПреобразованиеТипов.ПолучитьСтроку(ИДПодборки); OPI_ПреобразованиеТипов.ПолучитьБулево(Основная); OPI_ПреобразованиеТипов.ПолучитьБулево(Скрытая); - - Параметры_ = ПолучитьСтандартныеПараметры(Параметры); + + Параметры_ = ПолучитьСтандартныеПараметры(Параметры); Ответ = ДобавитьПараметрКартинки(Картинка, ИДПодборки, Параметры_); - + Если ЗначениеЗаполнено(Ответ) Тогда Возврат Ответ; КонецЕсли; - + Параметры_.Вставить("title" , Название); Параметры_.Вставить("main_album" , ?(Основная, 1, 0)); - Параметры_.Вставить("is_hidden" , ?(Скрытая, 1, 0)); - - Если ЗначениеЗаполнено(ИДПодборки) Тогда + Параметры_.Вставить("is_hidden" , ?(Скрытая , 1, 0)); + + Если ЗначениеЗаполнено(ИДПодборки) Тогда Параметры_.Вставить("album_id", ИДПодборки); - Метод = "editAlbum"; - Иначе + Метод = "editAlbum"; + Иначе Метод = "addAlbum"; КонецЕсли; - + Ответ = OPI_Инструменты.Get("api.vk.com/method/market." + Метод, Параметры_); - + Возврат Ответ; КонецФункции Функция ДобавитьПараметрКартинки(Знач Картинка, Знач ИДПодборки, Параметры) - + PhotoID_ = "photo_id"; - + Если ЗначениеЗаполнено(Картинка) Тогда - + ИДФото = ПолучитьИДКартинки(Картинка, Параметры, "Товар"); - + Если Не ТипЗнч(ИДФото) = Тип("Строка") Тогда - Возврат ИДФото; + Возврат ИДФото; КонецЕсли; - + Параметры.Вставить(PhotoID_, ИДФото); - + Иначе - + Если ЗначениеЗаполнено(ИДПодборки) Тогда - + Подборки = ПолучитьМассивПодборок(ИДПодборки, Параметры); - + Если Не ТипЗнч(Подборки) = Тип("Массив") Тогда - Возврат Подборки; + Возврат Подборки; КонецЕсли; - - Если Не Подборки.Количество() = 0 Тогда + + Если Не Подборки.Количество() = 0 Тогда ИДФото = Подборки[0]["photo"]["id"]; OPI_ПреобразованиеТипов.ПолучитьСтроку(ИДФото); Параметры.Вставить(PhotoID_, ИДФото); КонецЕсли; - + КонецЕсли; - + КонецЕсли; - + Возврат ""; - + КонецФункции Процедура ЗаполнитьПараметрыЗагрузкиФото(Знач Метод, Знач Ответ, Параметры) - + Response_ = "response"; Способ = Метод["Способ"]; СтандартныйСпособ = 1; НовыйСпособ = 2; Если Способ = СтандартныйСпособ Тогда - + Hash = "hash"; Serv = "server"; Aid = "aid"; Фото = Метод["Фото"]; - + Параметры.Вставить(Hash, Ответ[Hash]); Параметры.Вставить(Фото, Ответ[Фото]); - + СерверФото = Ответ.Получить(Serv); - + Если ЗначениеЗаполнено(СерверФото) Тогда СерверФото = OPI_Инструменты.ЧислоВСтроку(СерверФото); - Параметры.Вставить(Serv, СерверФото); + Параметры.Вставить(Serv, СерверФото); КонецЕсли; - + Идентификатор = Ответ.Получить(Aid); - + Если ЗначениеЗаполнено(Идентификатор) Тогда Идентификатор = OPI_Инструменты.ЧислоВСтроку(Идентификатор); - Параметры.Вставить(Aid , Идентификатор); + Параметры.Вставить(Aid , Идентификатор); КонецЕсли; - + ИначеЕсли Способ = НовыйСпособ Тогда - + ОтветСтрокой = OPI_Инструменты.JSONСтрокой(Ответ); Параметры.Вставить("upload_response", ОтветСтрокой); - + Иначе - + Параметры.Вставить("upload_results", Ответ[Response_]["upload_result"]); - + КонецЕсли; КонецПроцедуры Процедура ЗаполнитьПоляЗапросаТовара(Знач ОписаниеТовара, Параметры) - + Response_ = "response"; ОсновноеФото = ОписаниеТовара["ОсновноеФото"]; ДопФото = ОписаниеТовара["ДополнительныеФото"]; Свойства = ОписаниеТовара["ЗначенияСвойств"]; - + Если ЗначениеЗаполнено(ОсновноеФото) Тогда - + Ответ = ЗагрузитьФотоНаСервер(ОсновноеФото, Параметры, "Товар"); Результат = Ответ[Response_]; - + Если ЗначениеЗаполнено(Результат) Тогда ИДФото = Результат["photo_id"]; - + Если Не ЗначениеЗаполнено(ИДФото) Тогда - Возврат; + Возврат; КонецЕсли; - + Иначе Возврат; КонецЕсли; - + ИДФото = OPI_Инструменты.ЧислоВСтроку(ИДФото); - Параметры.Вставить("main_photo_id", ИДФото); - + Параметры.Вставить("main_photo_id", ИДФото); + КонецЕсли; - - Если ТипЗнч(Свойства) = Тип("Массив") Тогда - + + Если ТипЗнч(Свойства) = Тип("Массив") Тогда + Свойства_ = Новый Массив; - + Для Каждого Свойство Из Свойства Цикл - Свойства_.Добавить(OPI_Инструменты.ЧислоВСтроку(Свойство)); + Свойства_.Добавить(OPI_Инструменты.ЧислоВСтроку(Свойство)); КонецЦикла; - - Свойства = СтрСоединить(Свойства_, ","); - + + Свойства = СтрСоединить(Свойства_, ","); + КонецЕсли; - + Если ЗначениеЗаполнено(Свойства) Тогда - Параметры.Вставить("variant_ids", OPI_Инструменты.ЧислоВСтроку(Свойства)); + Параметры.Вставить("variant_ids", OPI_Инструменты.ЧислоВСтроку(Свойства)); КонецЕсли; - + ДобавитьДополнительныеФотоТовара(ДопФото, Параметры); - + Для Каждого Поле Из ПолучитьСоответствиеПараметровТовара() Цикл - + Значение = ОписаниеТовара[Поле.Ключ]; - + Если Значение <> Неопределено Тогда Параметры.Вставить(Поле.Значение, ОписаниеТовара[Поле.Ключ]); КонецЕсли; - + КонецЦикла; КонецПроцедуры Процедура ДобавитьДополнительныеФотоТовара(Знач МассивФото, Параметры) - + Если ТипЗнч(МассивФото) = Тип("Массив") Тогда Если МассивФото.Количество() > 0 Тогда - + СтрокаФотографий = ""; - + Для Каждого Фото Из МассивФото Цикл - + ИДФото = ПолучитьИДКартинки(Фото, Параметры, "Товар"); - + Если Не ТипЗнч(ИДФото) = Тип("Строка") Тогда - Возврат; + Возврат; КонецЕсли; - СтрокаФотографий = СтрокаФотографий + ИДФото + ","; - + СтрокаФотографий = СтрокаФотографий + ИДФото + ","; + КонецЦикла; - + СтрокаФотографий = Лев(СтрокаФотографий, СтрДлина(СтрокаФотографий) - 1); Параметры.Вставить("photo_ids", СтрокаФотографий); КонецЕсли; КонецЕсли; - + КонецПроцедуры Процедура ПолучитьСписокТоваровРекурсивно(МассивТоваров, Параметры, Сдвиг = 0) - + Response_ = "response"; МаксимумВЗапросе = 200; Ответ = OPI_Инструменты.Get("api.vk.com/method/market.get", Параметры); Товары = Ответ[Response_]["items"]; - + Если Товары.Количество() = 0 Тогда Возврат; - КонецЕсли; - + КонецЕсли; + Для Каждого Товар Из Товары Цикл МассивТоваров.Добавить(Товар); КонецЦикла; - + Сдвиг = Сдвиг + МаксимумВЗапросе; Параметры.Вставить("offset", Сдвиг); ПолучитьСписокТоваровРекурсивно(МассивТоваров, Параметры, Сдвиг); - + КонецПроцедуры Процедура ПолучитьСписокАльбомовРекурсивно(МассивАльбомов, Параметры, Сдвиг = 0) - + Response_ = "response"; МаксимумВЗапросе = 100; Ответ = OPI_Инструменты.Get("api.vk.com/method/market.getAlbums", Параметры); Альбомы = Ответ[Response_]["items"]; - + Если Альбомы.Количество() = 0 Тогда Возврат; - КонецЕсли; - + КонецЕсли; + Для Каждого Альбом Из Альбомы Цикл МассивАльбомов.Добавить(Альбом); КонецЦикла; - + Сдвиг = Сдвиг + МаксимумВЗапросе; Параметры.Вставить("offset", Сдвиг); ПолучитьСписокАльбомовРекурсивно(МассивАльбомов, Параметры, Сдвиг); - + КонецПроцедуры Процедура ПолучитьСписокЗаказовРекурсивно(МассивЗаказов, Параметры, Сдвиг = 0) - + Response_ = "response"; МаксимумВЗапросе = 50; Ответ = OPI_Инструменты.Get("api.vk.com/method/market.getGroupOrders", Параметры); Заказы = Ответ[Response_]["items"]; - + Если Заказы.Количество() = 0 Тогда Возврат; - КонецЕсли; - + КонецЕсли; + Для Каждого Заказ Из Заказы Цикл МассивЗаказов.Добавить(Заказ); КонецЦикла; - + Сдвиг = Сдвиг + МаксимумВЗапросе; Параметры.Вставить("offset", Сдвиг); ПолучитьСписокЗаказовРекурсивно(МассивЗаказов, Параметры, Сдвиг); - + КонецПроцедуры #КонецОбласти diff --git a/src/ru/OPI/src/CommonModules/OPI_Viber/Module.bsl b/src/ru/OPI/src/CommonModules/OPI_Viber/Module.bsl index cec7b365bb..7c42ebf44f 100644 --- a/src/ru/OPI/src/CommonModules/OPI_Viber/Module.bsl +++ b/src/ru/OPI/src/CommonModules/OPI_Viber/Module.bsl @@ -1,4 +1,4 @@ -// OneScript: ./OInt/core/Modules/OPI_Viber.os +// OneScript: ./OInt/core/Modules/OPI_Viber.os // Lib: Viber // CLI: viber @@ -23,7 +23,7 @@ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. - + // https://github.com/Bayselonarrend/OpenIntegrations // BSLLS:LatinAndCyrillicSymbolInWord-off @@ -46,55 +46,55 @@ // который будет возвращать 200 и подлинный SSL сертификат. Если есть сертификат и база опубликована // на сервере - можно использовать http-сервис. Туда же будет приходить и информация о новых сообщениях // Viber периодически стучит по адресу Webhook, так что если он будет неактивен, то все перестанет работать -// +// // Параметры: // Токен - Строка - Токен Viber - token // URL - Строка - URL для установки Webhook - url -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Viber Функция УстановитьWebhook(Знач Токен, Знач URL) Экспорт - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("url" , URL , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("auth_token" , Токен, "Строка", Параметры); - + Возврат OPI_Инструменты.Post("https://chatapi.viber.com/pa/set_webhook", Параметры); - + КонецФункции // Получить информацию о канале // Тут можно получить ID пользователей канала. ID для бота необходимо получать из прилетов на Webhook // ID пользователя из информации о канале не подойдет для отправки сообщений через бота - они разные -// +// // Параметры: // Токен - Строка - Токен - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Viber Функция ПолучитьИнформациюОКанале(Знач Токен) Экспорт - - URL = "https://chatapi.viber.com/pa/get_account_info"; + + URL = "https://chatapi.viber.com/pa/get_account_info"; Возврат OPI_Инструменты.Get(URL, , ТокенВЗаголовки(Токен)); - + КонецФункции // Получить данные пользователя // Получает информацию о пользователе по ID -// +// // Параметры: // Токен - Строка - Токен - token // IDПользователя - Строка, Число - ID пользователя Viber - user -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Viber Функция ПолучитьДанныеПользователя(Знач Токен, Знач IDПользователя) Экспорт - + URL = "https://chatapi.viber.com/pa/get_user_details"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("id", IDПользователя, "Строка", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры, ТокенВЗаголовки(Токен)); Возврат Ответ; @@ -103,22 +103,22 @@ // Получить онлайн пользователей // Получает статус пользователя или нескольких пользователей по ID -// +// // Параметры: // Токен - Строка - Токен Viber - token // IDПользователей - Строка,Число,Массив из Строка,Число - ID пользователей(я) Viber - users -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Viber Функция ПолучитьОнлайнПользователей(Знач Токен, Знач IDПользователей) Экспорт - + URL = "https://chatapi.viber.com/pa/get_online"; - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("ids", IDПользователей, "Коллекция", Параметры); - + Ответ = OPI_Инструменты.Post(URL, Параметры, ТокенВЗаголовки(Токен)); - + Возврат Ответ; КонецФункции @@ -129,14 +129,14 @@ // Отправить текстовое сообщение // Отправляет текстовое сообщение в чат или канал -// +// // Параметры: // Токен - Строка - Токен - token // Текст - Строка - Текст сообщения - text // IDПользователя - Строка,Число - ID пользователя. Для канала > администратора, для бота > получателя - user // ОтправкаВКанал - Булево - Отправка в канал или в чат бота - ischannel // Клавиатура - Структура из Строка - См. СформироватьКлавиатуруИзМассиваКнопок - keyboard -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Viber Функция ОтправитьТекстовоеСообщение(Знач Токен @@ -144,40 +144,40 @@ , Знач IDПользователя , Знач ОтправкаВКанал , Знач Клавиатура = "") Экспорт - - Возврат ОтправитьСообщение(Токен, "text", IDПользователя, ОтправкаВКанал, , Текст, Клавиатура); - + + Возврат ОтправитьСообщение(Токен, "text", IDПользователя, ОтправкаВКанал, , Текст, Клавиатура); + КонецФункции // Отправить картинку // Отправляет картинку в чат или канал -// +// // Параметры: // Токен - Строка - Токен - token // URL - Строка - URL картинки - picture // IDПользователя - Строка,Число - ID пользователя. Для канала > администратора, для бота > получателя - user // ОтправкаВКанал - булево - Отправка в канал или в чат бота - ischannel // Описание - Строка - Аннотация к картинке - description -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Viber Функция ОтправитьКартинку(Знач Токен, Знач URL, Знач IDПользователя, Знач ОтправкаВКанал, Знач Описание = "") Экспорт - + Возврат ОтправитьСообщение(Токен, "picture", IDПользователя, ОтправкаВКанал, URL, Описание); - + КонецФункции // Отправить файл // Отправляет файл (документ) в чат или канал -// +// // Параметры: // Токен - Строка - Токен - token -// URL - Строка - URL файла - file -// IDПользователя - Строка,Число - ID пользователя. Для канала > администратора, для бота > получателя - user +// URL - Строка - URL файла - file +// IDПользователя - Строка,Число - ID пользователя. Для канала > администратора, для бота > получателя - user // ОтправкаВКанал - Булево - Отправка в канал или в чат бота - ischannel // Расширение - Строка - Расширение файла - ext // Размер - Число - Размер файла. Если не заполнен > определяется автоматически скачиванием файла - size -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Viber Функция ОтправитьФайл(Знач Токен @@ -186,36 +186,36 @@ , Знач ОтправкаВКанал , Знач Расширение , Знач Размер = "") Экспорт - + Если Не ЗначениеЗаполнено(Размер) Тогда - + Ответ = OPI_Инструменты.Get(URL); Размер = Ответ.Размер(); - + КонецЕсли; - + Строка_ = "Строка"; Расширение = СтрЗаменить(Расширение, ".", ""); - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("URL" , URL , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("Размер" , Размер , Строка_, Параметры); OPI_Инструменты.ДобавитьПоле("Расширение", Расширение, Строка_, Параметры); - + Возврат ОтправитьСообщение(Токен, "file", IDПользователя, ОтправкаВКанал, Параметры); - + КонецФункции // Отправить контакт // Отправляет контакт с номером телефона в чат или канал -// +// // Параметры: // Токен - Строка - Токен - token // ИмяКонтакта - Строка - Имя контакта - name // НомерТелефона - Строка - Номер телефона - phone -// IDПользователя - Строка,Число - ID пользователя. Для канала > администратора, для бота > получателя - user +// IDПользователя - Строка,Число - ID пользователя. Для канала > администратора, для бота > получателя - user // ОтправкаВКанал - Булево - Отправка в канал или в чат бота - ischannel -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Viber Функция ОтправитьКонтакт(Знач Токен @@ -223,91 +223,91 @@ , Знач НомерТелефона , Знач IDПользователя , Знач ОтправкаВКанал) Экспорт - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("name" , ИмяКонтакта , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("phone_number", НомерТелефона, "Строка", Параметры); - - Возврат ОтправитьСообщение(Токен, "contact", IDПользователя, ОтправкаВКанал, Параметры); - + + Возврат ОтправитьСообщение(Токен, "contact", IDПользователя, ОтправкаВКанал, Параметры); + КонецФункции // Отправить локацию // Отправляет географические координаты в чат или канал -// +// // Параметры: // Токен - Строка - Токен - token // Широта - Строка,Число - Географическая широта - lat // Долгота - Строка,Число - Географическая долгота - long -// IDПользователя - Строка,Число - ID пользователя. Для канала > администратора, для бота > получателя - user +// IDПользователя - Строка,Число - ID пользователя. Для канала > администратора, для бота > получателя - user // ОтправкаВКанал - Булево - Отправка в канал или в чат бота - ischannel -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Viber Функция ОтправитьЛокацию(Знач Токен, Знач Широта, Знач Долгота, Знач IDПользователя, Знач ОтправкаВКанал) Экспорт - + Параметры = Новый Структура; OPI_Инструменты.ДобавитьПоле("lat", Широта , "Строка", Параметры); OPI_Инструменты.ДобавитьПоле("lon", Долгота, "Строка", Параметры); - + Возврат ОтправитьСообщение(Токен, "location", IDПользователя, ОтправкаВКанал, Параметры); - + КонецФункции // Отправить ссылку // Отправляет URL с предпросмотром в чат или канал -// +// // Параметры: // Токен - Строка - Токен - token // URL - Строка - Отправляемая ссылка - url -// IDПользователя - Строка,Число - ID пользователя. Для канала > администратора, для бота > получателя - user +// IDПользователя - Строка,Число - ID пользователя. Для канала > администратора, для бота > получателя - user // ОтправкаВКанал - Булево - Отправка в канал или в чат бота - ischannel -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Viber Функция ОтправитьСсылку(Знач Токен, Знач URL, Знач IDПользователя, Знач ОтправкаВКанал) Экспорт - + Возврат ОтправитьСообщение(Токен, "url", IDПользователя, ОтправкаВКанал, URL); - + КонецФункции // Сформировать клавиатуру из массива кнопок // Возвращает структура клавиатуры для сообщений -// +// // Параметры: // МассивКнопок - Массив из Строка - Массив кнопок - buttons // ЦветКнопок - Строка - HEX цвет кнопок с # в начале - color -// +// // Возвращаемое значение: // Структура - Сформировать клавиатуру из массива кнопок: -// * Buttons - Массив из Структура - Массив сформированных кнопок -// * Type - Строка - Тип клавиатуры +// * Buttons - Массив из Структура - Массив сформированных кнопок +// * Type - Строка - Тип клавиатуры Функция СформироватьКлавиатуруИзМассиваКнопок(Знач МассивКнопок, Знач ЦветКнопок = "#2db9b9") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(ЦветКнопок); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(МассивКнопок); - + МассивСтруктурКнопок = Новый Массив; СтруктураКлавиатуры = Новый Структура; - + Для Каждого ТекстКнопки Из МассивКнопок Цикл - + СтруктураКнопки = Новый Структура; СтруктураКнопки.Вставить("ActionType", "reply"); СтруктураКнопки.Вставить("ActionBody", ТекстКнопки); СтруктураКнопки.Вставить("Text" , ТекстКнопки); СтруктураКнопки.Вставить("BgColor" , ЦветКнопок); СтруктураКнопки.Вставить("Coloumns" , 3); - + МассивСтруктурКнопок.Добавить(СтруктураКнопки); - + КонецЦикла; - + СтруктураКлавиатуры.Вставить("Buttons", МассивСтруктурКнопок); СтруктураКлавиатуры.Вставить("Type" , "keyboard"); - + Возврат СтруктураКлавиатуры; - + КонецФункции #КонецОбласти @@ -317,7 +317,7 @@ #Область СлужебныеПроцедурыИФункции // Отправить сообщение. -// +// // Параметры: // Токен - Строка - Токен // Тип - Строка - Тип отправляемого сообщения @@ -328,8 +328,8 @@ // * Размер - Число, Строка - Размер файла в случае отправке // * Расширение - Строка - Расширение файла в случае отправки // Текст - Строка - Текст сообщения -// Клавиатура - Структура из Строка - Клавиатура, если нужна, см. СформироватьКлавиатуруИзМассиваКнопок -// +// Клавиатура - Структура из Строка - Клавиатура, если нужна, см. СформироватьКлавиатуруИзМассиваКнопок +// // Возвращаемое значение: // Произвольный, HTTPОтвет - Отправить сообщение Функция ОтправитьСообщение(Знач Токен @@ -339,28 +339,28 @@ , Знач Значение = "" , Знач Текст = "" , Знач Клавиатура = "") - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Тип); OPI_ПреобразованиеТипов.ПолучитьСтроку(IDПользователя); OPI_ПреобразованиеТипов.ПолучитьСтроку(Текст); OPI_ПреобразованиеТипов.ПолучитьБулево(ЭтоКанал); OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Клавиатура); - + СтруктураПараметров = ВернутьСтандартныеПараметры(); - СтруктураПараметров.Вставить("type", Тип); - + СтруктураПараметров.Вставить("type", Тип); + Если (Тип = "text" Или Тип = "picture") И ЗначениеЗаполнено(Текст) Тогда СтруктураПараметров.Вставить("text", Текст); КонецЕсли; - + Если ТипЗнч(Клавиатура) = Тип("Структура") Тогда СтруктураПараметров.Вставить("keyboard", Клавиатура); КонецЕсли; - + Если ЗначениеЗаполнено(Значение) Тогда - - Если Тип = "file" Тогда + + Если Тип = "file" Тогда СтруктураПараметров.Вставить("media" , Значение["URL"]); СтруктураПараметров.Вставить("size" , Значение["Размер"]); СтруктураПараметров.Вставить("file_name", "Файл." + Значение["Расширение"]); @@ -371,49 +371,49 @@ Иначе СтруктураПараметров.Вставить("media" , Значение); КонецЕсли; - + КонецЕсли; - + Если ЭтоКанал Тогда - СтруктураПараметров.Вставить("from", IDПользователя); + СтруктураПараметров.Вставить("from" , IDПользователя); URL = "https://chatapi.viber.com/pa/post"; - Иначе + Иначе СтруктураПараметров.Вставить("receiver", IDПользователя); URL = "https://chatapi.viber.com/pa/send_message"; КонецЕсли; - + Ответ = OPI_Инструменты.Post(URL, СтруктураПараметров, ТокенВЗаголовки(Токен)); - + Попытка Возврат OPI_Инструменты.JsonВСтруктуру(Ответ.ПолучитьТелоКакДвоичныеДанные()); Исключение Возврат Ответ; КонецПопытки; - + КонецФункции -Функция ВернутьСтандартныеПараметры() - +Функция ВернутьСтандартныеПараметры() + СтруктураОтправителя = Новый Структура; СтруктураОтправителя.Вставить("name" , "Bot"); СтруктураОтправителя.Вставить("avatar", ""); - + СтруктураПараметров = Новый Структура; - СтруктураПараметров.Вставить("sender", СтруктураОтправителя); + СтруктураПараметров.Вставить("sender" , СтруктураОтправителя); СтруктураПараметров.Вставить("min_api_version", 1); - + Возврат СтруктураПараметров; - + КонецФункции Функция ТокенВЗаголовки(Знач Токен) - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + СтруктураЗаголовков = Новый Соответствие; СтруктураЗаголовков.Вставить("X-Viber-Auth-Token", Токен); Возврат СтруктураЗаголовков; - + КонецФункции #КонецОбласти diff --git a/src/ru/OPI/src/CommonModules/OPI_YandexDisk/Module.bsl b/src/ru/OPI/src/CommonModules/OPI_YandexDisk/Module.bsl index ddc0c44ddd..fa893cebe4 100644 --- a/src/ru/OPI/src/CommonModules/OPI_YandexDisk/Module.bsl +++ b/src/ru/OPI/src/CommonModules/OPI_YandexDisk/Module.bsl @@ -1,4 +1,4 @@ -// OneScript: ./OInt/core/Modules/OPI_YandexDisk.os +// OneScript: ./OInt/core/Modules/OPI_YandexDisk.os // Lib: Yandex Disk // CLI: yadisk @@ -37,7 +37,7 @@ //@skip-check wrong-string-literal-content // Раскомментировать, если выполняется OneScript -// #Использовать "../../tools" +// #Использовать "../../tools" #Область ПрограммныйИнтерфейс @@ -45,217 +45,217 @@ // Получить информацию о диске // Получает информацию о текущем диске -// +// // Параметры: // Токен - Строка - Токен - token -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ПолучитьИнформациюОДиске(Знач Токен) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); - + Заголовки = ЗаголовокАвторизации(Токен); Ответ = OPI_Инструменты.Get("https://cloud-api.yandex.net/v1/disk", , Заголовки); - + Возврат Ответ; - + КонецФункции // Создать папку // Создает каталог на диске -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к созаваемой папке - path -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция СоздатьПапку(Знач Токен, Знач Путь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Путь); - + Заголовки = ЗаголовокАвторизации(Токен); URL = "https://cloud-api.yandex.net/v1/disk/resources"; Href = "href"; - + Параметры = Новый Структура; Параметры.Вставить("path", Путь); - - Параметры = OPI_Инструменты.ПараметрыЗапросаВСтроку(Параметры); + + Параметры = OPI_Инструменты.ПараметрыЗапросаВСтроку(Параметры); Ответ = OPI_Инструменты.Put(URL + Параметры, , Заголовки, Ложь); - - URLОтвета = Ответ[Href]; - + + URLОтвета = Ответ[Href]; + Если Не ЗначениеЗаполнено(URLОтвета) Тогда - Возврат Ответ; + Возврат Ответ; КонецЕсли; - + Ответ = OPI_Инструменты.Get(URLОтвета, , Заголовки); - + Возврат Ответ; КонецФункции // Получить объект // Получает информацию об объекте диска по заданному пути -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к папке или файлу - path -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ПолучитьОбъект(Знач Токен, Знач Путь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Путь); - + Заголовки = ЗаголовокАвторизации(Токен); Параметры = Новый Структура; Параметры.Вставить("path", Путь); - + Ответ = OPI_Инструменты.Get("https://cloud-api.yandex.net/v1/disk/resources", Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Удалить объект // Удаляет объект по заданному пути -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к удаляемой папке или файлу - path // ВКорзину - Булево - В корзину - can -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция УдалитьОбъект(Знач Токен, Знач Путь, Знач ВКорзину = Истина) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Путь); OPI_ПреобразованиеТипов.ПолучитьБулево(ВКорзину); - + Заголовки = ЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; Параметры.Вставить("path" , Путь); Параметры.Вставить("permanently", Не ВКорзину); - + Ответ = OPI_Инструменты.Delete("https://cloud-api.yandex.net/v1/disk/resources", Параметры, Заголовки); - + Возврат Ответ; КонецФункции // Создать копию объекта // Создает копию объекта по заданному пути и пути к оригиналу -// +// // Параметры: // Токен - Строка - Токен - token // Оригинал - Строка - Путь к оригинальному файлу или каталогу - from // Путь - Строка - Путь назначения для копии - to // Перезаписывать - Булево - Перезаписывать если файл с таким именем уже существует - rewrite -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция СоздатьКопиюОбъекта(Знач Токен, Знач Оригинал, Знач Путь, Знач Перезаписывать = Ложь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Оригинал); OPI_ПреобразованиеТипов.ПолучитьСтроку(Путь); OPI_ПреобразованиеТипов.ПолучитьБулево(Перезаписывать); - + Заголовки = ЗаголовокАвторизации(Токен); URL = "https://cloud-api.yandex.net/v1/disk/resources/copy"; Href = "href"; - + Параметры = Новый Структура; Параметры.Вставить("from" , Оригинал); Параметры.Вставить("path" , Путь); Параметры.Вставить("overwrite" , Перезаписывать); - - Параметры = OPI_Инструменты.ПараметрыЗапросаВСтроку(Параметры); + + Параметры = OPI_Инструменты.ПараметрыЗапросаВСтроку(Параметры); Ответ = OPI_Инструменты.Post(URL + Параметры, , Заголовки, Ложь); - - URLОтвета = Ответ[Href]; - + + URLОтвета = Ответ[Href]; + Если Не ЗначениеЗаполнено(URLОтвета) Тогда - Возврат Ответ; + Возврат Ответ; КонецЕсли; - + Ответ = OPI_Инструменты.Get(URLОтвета, , Заголовки); - + Возврат Ответ; - + КонецФункции // Получить ссылку для скачивания // Получает ссылку для скачивания файла -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к файлу для скачивания - path -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ПолучитьСсылкуДляСкачивания(Знач Токен, Знач Путь) Экспорт OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Путь); - + Заголовки = ЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; Параметры.Вставить("path", Путь); - + Ответ = OPI_Инструменты.Get("https://cloud-api.yandex.net/v1/disk/resources/download", Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Скачать файл // Скачивает файл по указанному пути -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к файлу для скачивания - path -// ПутьСохранения - Строка - Путь сохранения файла - out -// +// ПутьСохранения - Строка - Путь сохранения файла - out +// // Возвращаемое значение: // ДвоичныеДанные,Строка - Двоичные данные или путь к файлу при указании параметра ПутьСохранения Функция СкачатьФайл(Знач Токен, Знач Путь, Знач ПутьСохранения = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(ПутьСохранения); Ответ = ПолучитьСсылкуДляСкачивания(Токен, Путь); URL = Ответ["href"]; - + Если Не ЗначениеЗаполнено(URL) Тогда Возврат Ответ; КонецЕсли; - + Ответ = OPI_Инструменты.Get(URL, , , ПутьСохранения); - + Возврат Ответ; - + КонецФункции // Получить список файлов // Получает список файлов с или без отбора по типу -// Список доступных типов: audio, backup, book, compressed, data, development, -// diskimage, document, encoded, executable, flash, font, +// Список доступных типов: audio, backup, book, compressed, data, development, +// diskimage, document, encoded, executable, flash, font, // mage, settings, spreadsheet, text, unknown, video, web -// +// // Параметры: // Токен - Строка - Токен - token // Количество - Число,Строка - Количество возвращаемых объектов - amount // СмещениеОтНачала - Число - Смещение для получение объектов не из начала списка - offset // ОтборПоТипу - Строка - Отбор по типу файла - type // СортироватьПоДате - Булево - Истина > сортировать по дате, Ложь > по алфавиту - datesort -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ПолучитьСписокФайлов(Знач Токен @@ -263,50 +263,50 @@ , Знач СмещениеОтНачала = 0 , Знач ОтборПоТипу = "" , Знач СортироватьПоДате = Ложь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Количество); OPI_ПреобразованиеТипов.ПолучитьСтроку(СмещениеОтНачала); OPI_ПреобразованиеТипов.ПолучитьСтроку(ОтборПоТипу); OPI_ПреобразованиеТипов.ПолучитьБулево(СортироватьПоДате); - + Заголовки = ЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; - + Если ЗначениеЗаполнено(Количество) Тогда Параметры.Вставить("limit", OPI_Инструменты.ЧислоВСтроку(Количество)); КонецЕсли; - + Если ЗначениеЗаполнено(СмещениеОтНачала) Тогда Параметры.Вставить("offset", OPI_Инструменты.ЧислоВСтроку(СмещениеОтНачала)); КонецЕсли; - + Если ЗначениеЗаполнено(ОтборПоТипу) Тогда Параметры.Вставить("media_type", ОтборПоТипу); КонецЕсли; - + Если СортироватьПоДате Тогда Назначение = "last-uploaded"; Иначе Назначение = "files"; КонецЕсли; - + Ответ = OPI_Инструменты.Get("https://cloud-api.yandex.net/v1/disk/resources/" + Назначение, Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Переместить объект // Перемещает объект по заданному пути и пути к оригиналу -// +// // Параметры: // Токен - Строка - Токен - token // Оригинал - Строка - Путь к оригинальному файлу или папке - from // Путь - Строка - Путь назначение для перемещения - to // Перезаписывать - Булево - Перезаписывать если файл с таким именем уже существует - rewrite -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ПереместитьОбъект(Знач Токен, Знач Оригинал, Знач Путь, Знач Перезаписывать = Ложь) Экспорт @@ -315,97 +315,97 @@ OPI_ПреобразованиеТипов.ПолучитьСтроку(Оригинал); OPI_ПреобразованиеТипов.ПолучитьСтроку(Путь); OPI_ПреобразованиеТипов.ПолучитьБулево(Перезаписывать); - + Заголовки = ЗаголовокАвторизации(Токен); URL = "https://cloud-api.yandex.net/v1/disk/resources/move"; Href = "href"; - + Параметры = Новый Структура; Параметры.Вставить("from" , Оригинал); Параметры.Вставить("path" , Путь); Параметры.Вставить("overwrite" , Перезаписывать); - - Параметры = OPI_Инструменты.ПараметрыЗапросаВСтроку(Параметры); - Ответ = OPI_Инструменты.Post(URL + Параметры, , Заголовки, Ложь); - URLОтвета = Ответ[Href]; - + + Параметры = OPI_Инструменты.ПараметрыЗапросаВСтроку(Параметры); + Ответ = OPI_Инструменты.Post(URL + Параметры, , Заголовки, Ложь); + URLОтвета = Ответ[Href]; + Если Не ЗначениеЗаполнено(URLОтвета) Тогда - Возврат Ответ; + Возврат Ответ; КонецЕсли; - + Ответ = OPI_Инструменты.Get(URLОтвета, , Заголовки); - + Возврат Ответ; - + КонецФункции // Загрузить файл // Загружает файл на диск по заданному пути -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь для сохранение файла на Диске - path // Файл - Строка,ДвоичныеДанные - Файл для загрузки - file // Перезаписывать - Булево - Перезаписывать, если файл с таким именем уже существует - rewrite -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ЗагрузитьФайл(Знач Токен, Знач Путь, Знач Файл, Знач Перезаписывать = Ложь) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Путь); OPI_ПреобразованиеТипов.ПолучитьБулево(Перезаписывать); OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Файл); - + Заголовки = ЗаголовокАвторизации(Токен); - Href = "href"; + Href = "href"; Файл = Новый Структура("file", Файл); - + Параметры = Новый Структура; Параметры.Вставить("path" , Путь); Параметры.Вставить("overwrite" , Перезаписывать); - + Ответ = OPI_Инструменты.Get("https://cloud-api.yandex.net/v1/disk/resources/upload", Параметры, Заголовки); URL = Ответ[Href]; - + Если Не ЗначениеЗаполнено(URL) Тогда - Возврат Ответ; + Возврат Ответ; КонецЕсли; - + Ответ = OPI_Инструменты.PutMultipart(URL, Новый Структура(), Файл, "multipart", Заголовки); - + Возврат Ответ; - + КонецФункции // Загрузить файл по URL // Загружает файл на диск, забирая его по заданному URL -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь помещения загруженного файла - path // Адрес - Строка - URL файла - url -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ЗагрузитьФайлПоURL(Знач Токен, Знач Путь, Знач Адрес) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Путь); OPI_ПреобразованиеТипов.ПолучитьСтроку(Адрес); - + Заголовки = ЗаголовокАвторизации(Токен); URL = "https://cloud-api.yandex.net/v1/disk/resources/upload"; - + Параметры = Новый Структура; Параметры.Вставить("url" , КодироватьСтроку(Адрес, СпособКодированияСтроки.КодировкаURL)); Параметры.Вставить("path", Путь); - - Параметры = OPI_Инструменты.ПараметрыЗапросаВСтроку(Параметры); + + Параметры = OPI_Инструменты.ПараметрыЗапросаВСтроку(Параметры); Ответ = OPI_Инструменты.Post(URL + Параметры, , Заголовки, Ложь); - + Возврат Ответ; - + КонецФункции #КонецОбласти @@ -414,186 +414,186 @@ // Опубликовать объект // Публикует объект диска в публичный доступ -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к публикуемому объекту - path -// +// // Возвращаемое значение: -// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex +// Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ОпубликоватьОбъект(Знач Токен, Знач Путь) Экспорт - - Возврат ПереключениеОбщегоДоступа(Токен, Путь, Истина); - + + Возврат ПереключениеОбщегоДоступа(Токен, Путь, Истина); + КонецФункции // Отменить публикацию объекта // Отменяет публикацию ранее опубликованного объекта -// +// // Параметры: // Токен - Строка - Токен - token // Путь - Строка - Путь к опубликованному ранее объекту - path -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ОтменитьПубликациюОбъекта(Знач Токен, Знач Путь) Экспорт - + Возврат ПереключениеОбщегоДоступа(Токен, Путь, Ложь); - + КонецФункции // Получить список опубликованных объектов. // Получает список опубликованных объектов -// +// // Параметры: -// Токен - Строка - Токен - token +// Токен - Строка - Токен - token // Количество - Число - Количество возвращаемых объектов - amount // СмещениеОтНачала - Число - Смещение для получение объектов не из начала списка - offset -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ПолучитьСписокОпубликованныхОбъектов(Знач Токен, Знач Количество = 0, Знач СмещениеОтНачала = 0) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Количество); OPI_ПреобразованиеТипов.ПолучитьСтроку(СмещениеОтНачала); - + Заголовки = ЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; - + Если ЗначениеЗаполнено(Количество) Тогда Параметры.Вставить("limit", Количество); КонецЕсли; - + Если ЗначениеЗаполнено(СмещениеОтНачала) Тогда Параметры.Вставить("offset", СмещениеОтНачала); КонецЕсли; - + Ответ = OPI_Инструменты.Get("https://cloud-api.yandex.net/v1/disk/resources/public", Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить публичный объект // Получает информацию об опубликованном объекте по его URL -// +// // Параметры: // Токен - Строка - Токен - token -// URL - Строка - Адрес объекта - url +// URL - Строка - Адрес объекта - url // Количество - Число - Количество возвращаемых вложенных объектов (для каталога) - amount // СмещениеОтНачала - Число - Смещение для получение вложенных объектов не из начала списка - offset -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ПолучитьПубличныйОбъект(Знач Токен, Знач URL, Знач Количество = 0, Знач СмещениеОтНачала = 0) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(URL); OPI_ПреобразованиеТипов.ПолучитьСтроку(Количество); OPI_ПреобразованиеТипов.ПолучитьСтроку(СмещениеОтНачала); - + Заголовки = ЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; - + Если ЗначениеЗаполнено(Количество) Тогда Параметры.Вставить("limit", OPI_Инструменты.ЧислоВСтроку(Количество)); КонецЕсли; - + Если ЗначениеЗаполнено(СмещениеОтНачала) Тогда Параметры.Вставить("offset", OPI_Инструменты.ЧислоВСтроку(СмещениеОтНачала)); КонецЕсли; - + Параметры.Вставить("public_key", URL); - + Ответ = OPI_Инструменты.Get("https://cloud-api.yandex.net/v1/disk/public/resources", Параметры, Заголовки); - + Возврат Ответ; - + КонецФункции // Получить ссылку скачивания публичного объекта // Получает прямую ссылку для скачивания публичного объекта -// +// // Параметры: // Токен - Строка - Токен - token // URL - Строка - Адрес объекта - url // Путь - Строка - Путь внутри объекта - path -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ПолучитьСсылкуСкачиванияПубличногоОбъекта(Знач Токен, Знач URL, Знач Путь = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(URL); OPI_ПреобразованиеТипов.ПолучитьСтроку(Путь); - + Заголовки = ЗаголовокАвторизации(Токен); - + Параметры = Новый Структура; - + Если ЗначениеЗаполнено(Путь) Тогда Параметры.Вставить("path", Путь); КонецЕсли; - + Параметры.Вставить("public_key", URL); - + Ответ = OPI_Инструменты.Get("https://cloud-api.yandex.net/v1/disk/public/resources/download", Параметры, Заголовки); - - Возврат Ответ; - + + Возврат Ответ; + КонецФункции - + // Сохранить публичный объект на диск // Сохраняет публичный объект на ваш диск -// +// // Параметры: // Токен - Строка - Токен - token // URL - Строка - Адрес объекта - url // Откуда - Строка - Путь внутри публичного каталога (только для папок) - from // Куда - Строка - Путь сохранения файла - to -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция СохранитьПубличныйОбъектНаДиск(Знач Токен, Знач URL, Откуда = "", Куда = "") Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(URL); OPI_ПреобразованиеТипов.ПолучитьСтроку(Откуда); OPI_ПреобразованиеТипов.ПолучитьСтроку(Куда); - + Заголовки = ЗаголовокАвторизации(Токен); Адрес = "https://cloud-api.yandex.net/v1/disk/public/resources/save-to-disk"; Href = "href"; - + Параметры = Новый Структура; Параметры.Вставить("public_key", КодироватьСтроку(URL, СпособКодированияСтроки.КодировкаURL)); - + Если ЗначениеЗаполнено(Откуда) Тогда Параметры.Вставить("path", Откуда); КонецЕсли; - + Если ЗначениеЗаполнено(Куда) Тогда Параметры.Вставить("save_path", Куда); КонецЕсли; - - Параметры = OPI_Инструменты.ПараметрыЗапросаВСтроку(Параметры); + + Параметры = OPI_Инструменты.ПараметрыЗапросаВСтроку(Параметры); Ответ = OPI_Инструменты.Post(Адрес + Параметры, , Заголовки, Ложь); - - URLОтвета = Ответ[Href]; - + + URLОтвета = Ответ[Href]; + Если Не ЗначениеЗаполнено(URLОтвета) Тогда - Возврат Ответ; + Возврат Ответ; КонецЕсли; - + Ответ = OPI_Инструменты.Get(URLОтвета, , Заголовки); - + Возврат Ответ; - + КонецФункции - + #КонецОбласти #КонецОбласти @@ -601,42 +601,42 @@ #Область СлужебныеПроцедурыИФункции Функция ЗаголовокАвторизации(Знач Токен) - + Заголовки = Новый Соответствие; Заголовки.Вставить("Authorization", "OAuth " + Токен); - + Возврат Заголовки; - + КонецФункции -Функция ПереключениеОбщегоДоступа(Знач Токен, Знач Путь, Знач ОбщийДоступ) - +Функция ПереключениеОбщегоДоступа(Знач Токен, Знач Путь, Знач ОбщийДоступ) + OPI_ПреобразованиеТипов.ПолучитьСтроку(Токен); OPI_ПреобразованиеТипов.ПолучитьСтроку(Путь); OPI_ПреобразованиеТипов.ПолучитьБулево(ОбщийДоступ); - + Заголовки = ЗаголовокАвторизации(Токен); Назначение = ?(ОбщийДоступ, "publish", "unpublish"); Href = "href"; - + URL = "https://cloud-api.yandex.net/v1/disk/resources/" + Назначение; - + Параметры = Новый Структура; Параметры.Вставить("path", Путь); - - Параметры = OPI_Инструменты.ПараметрыЗапросаВСтроку(Параметры); + + Параметры = OPI_Инструменты.ПараметрыЗапросаВСтроку(Параметры); Ответ = OPI_Инструменты.Put(URL + Параметры, , Заголовки, Ложь); - + URLОтвета = Ответ[Href]; - + Если Не ЗначениеЗаполнено(URLОтвета) Тогда - Возврат Ответ; - КонецЕсли; - + Возврат Ответ; + КонецЕсли; + Ответ = OPI_Инструменты.Get(URLОтвета, , Заголовки); - + Возврат Ответ; - + КонецФункции -#КонецОбласти \ No newline at end of file +#КонецОбласти diff --git a/src/ru/OPI/src/CommonModules/OPI_YandexID/Module.bsl b/src/ru/OPI/src/CommonModules/OPI_YandexID/Module.bsl index 784b01ca0e..da2e10675a 100644 --- a/src/ru/OPI/src/CommonModules/OPI_YandexID/Module.bsl +++ b/src/ru/OPI/src/CommonModules/OPI_YandexID/Module.bsl @@ -1,4 +1,4 @@ -// OneScript: ./OInt/core/Modules/OPI_YandexID.os +// OneScript: ./OInt/core/Modules/OPI_YandexID.os // Lib: Yandex ID // CLI: yandex @@ -41,77 +41,77 @@ // Получить код подтверждения // Получает код подтверждения и адрес страницы, на которой его необходимо ввести -// +// // Параметры: // ClientId - Строка - Client id - id -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ПолучитьКодПодтверждения(Знач ClientId) Экспорт OPI_ПреобразованиеТипов.ПолучитьСтроку(ClientId); - + Параметры = Новый Структура("client_id", ClientId); Ответ = OPI_Инструменты.Post("https://oauth.yandex.ru/device/code", Параметры, , Ложь); - + Возврат Ответ; - + КонецФункции // Преобразовать код в токен // Преобразовывает код в токен после ввода кода при выполнении ПолучитьКодПодтверждения -// +// // Параметры: // ClientId - Строка - Client id - id // ClientSecret - Строка - Client secret - secret // КодУстройства - Строка - device_code из ПолучитьКодПодтверждения() - device -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ПреобразоватьКодВТокен(Знач ClientId, Знач ClientSecret, Знач КодУстройства) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(ClientId); OPI_ПреобразованиеТипов.ПолучитьСтроку(ClientSecret); OPI_ПреобразованиеТипов.ПолучитьСтроку(КодУстройства); - + Параметры = Новый Структура; Параметры.Вставить("grant_type" , "device_code"); Параметры.Вставить("code" , КодУстройства); Параметры.Вставить("client_id" , ClientId); Параметры.Вставить("client_secret" , ClientSecret); - + Ответ = OPI_Инструменты.Post("https://oauth.yandex.ru/token", Параметры, , Ложь); - + Возврат Ответ; - + КонецФункции // Обновить токен // Обновляет токен по Refresh token -// +// // Параметры: // ClientId - Строка - Client id - id // ClientSecret - Строка - Client secret - secret // RefreshToken - Строка - Refresh token - refresh -// +// // Возвращаемое значение: // Соответствие Из КлючИЗначение - сериализованный JSON ответа от Yandex Функция ОбновитьТокен(Знач ClientId, Знач ClientSecret, Знач RefreshToken) Экспорт - + OPI_ПреобразованиеТипов.ПолучитьСтроку(ClientId); OPI_ПреобразованиеТипов.ПолучитьСтроку(ClientSecret); OPI_ПреобразованиеТипов.ПолучитьСтроку(RefreshToken); - + Параметры = Новый Структура; Параметры.Вставить("grant_type" , "refresh_token"); Параметры.Вставить("refresh_token" , RefreshToken); Параметры.Вставить("client_id" , ClientId); Параметры.Вставить("client_secret" , ClientSecret); - + Ответ = OPI_Инструменты.Post("https://oauth.yandex.ru/token", Параметры, , Ложь); - + Возврат Ответ; - + КонецФункции #КонецОбласти diff --git a/src/ru/OPI/src/CommonModules/OPI_Инструменты/Module.bsl b/src/ru/OPI/src/CommonModules/OPI_Инструменты/Module.bsl index c7707fa560..6a603fd0dc 100644 --- a/src/ru/OPI/src/CommonModules/OPI_Инструменты/Module.bsl +++ b/src/ru/OPI/src/CommonModules/OPI_Инструменты/Module.bsl @@ -1,4 +1,4 @@ -// OneScript: ./OInt/tools/Modules/internal/Modules/OPI_Инструменты.os +// OneScript: ./OInt/tools/Modules/internal/Modules/OPI_Инструменты.os // MIT License @@ -56,169 +56,169 @@ #Область ЗапросыСТелом Функция Post(Знач URL - , Знач Параметры = "" + , Знач Параметры = "" , Знач ДопЗаголовки = "" - , Знач JSON = Истина - , Знач ПолныйОтвет = Ложь - , Знач ФайлОтвета = Неопределено) Экспорт - + , Знач JSON = Истина + , Знач ПолныйОтвет = Ложь + , Знач ФайлОтвета = Неопределено) Экспорт + Возврат ВыполнитьЗапросСТелом(URL, "POST", Параметры, ДопЗаголовки, JSON, ПолныйОтвет, ФайлОтвета); - + КонецФункции Функция Patch(Знач URL - , Знач Параметры = "" + , Знач Параметры = "" , Знач ДопЗаголовки = "" - , Знач JSON = Истина - , Знач ПолныйОтвет = Ложь - , Знач ФайлОтвета = Неопределено) Экспорт - + , Знач JSON = Истина + , Знач ПолныйОтвет = Ложь + , Знач ФайлОтвета = Неопределено) Экспорт + Возврат ВыполнитьЗапросСТелом(URL, "PATCH", Параметры, ДопЗаголовки, JSON, ПолныйОтвет, ФайлОтвета); - + КонецФункции Функция Put(Знач URL - , Знач Параметры = "" + , Знач Параметры = "" , Знач ДопЗаголовки = "" - , Знач JSON = Истина - , Знач ПолныйОтвет = Ложь - , Знач ФайлОтвета = Неопределено) Экспорт - + , Знач JSON = Истина + , Знач ПолныйОтвет = Ложь + , Знач ФайлОтвета = Неопределено) Экспорт + Возврат ВыполнитьЗапросСТелом(URL, "PUT", Параметры, ДопЗаголовки, JSON, ПолныйОтвет, ФайлОтвета); - + КонецФункции Функция PostBinary(Знач URL , Знач Тело , Знач ДопЗаголовки , Знач ПолныйОтвет = Ложь - , Знач ТипДанных = "application/octet-stream") Экспорт - + , Знач ТипДанных = "application/octet-stream") Экспорт + Возврат ВыполнитьЗапросСДвоичнымиДанными(URL, "POST", Тело, ДопЗаголовки, ПолныйОтвет, ТипДанных); - + КонецФункции -#КонецОбласти +#КонецОбласти #Область ЗапросыMultipart Функция PostMultipart(Знач URL - , Знач Параметры = "" - , Знач Файлы = "" - , Знач ТипКонтента = "image/jpeg" + , Знач Параметры = "" + , Знач Файлы = "" + , Знач ТипКонтента = "image/jpeg" , Знач ДопЗаголовки = "" - , Знач ФайлОтвета = Неопределено) Экспорт + , Знач ФайлОтвета = Неопределено) Экспорт Возврат ВыполнитьЗапросМультипарт(URL, "POST", Параметры, Файлы, ТипКонтента, ДопЗаголовки, ФайлОтвета); КонецФункции Функция PutMultipart(Знач URL - , Знач Параметры = "" - , Знач Файлы = "" - , Знач ТипКонтента = "image/jpeg" + , Знач Параметры = "" + , Знач Файлы = "" + , Знач ТипКонтента = "image/jpeg" , Знач ДопЗаголовки = "" - , Знач ФайлОтвета = Неопределено) Экспорт + , Знач ФайлОтвета = Неопределено) Экспорт Возврат ВыполнитьЗапросМультипарт(URL, "PUT", Параметры, Файлы, ТипКонтента, ДопЗаголовки, ФайлОтвета); КонецФункции Функция PostMultipartRelated(Знач URL - , Знач JSON = "" - , Знач Файлы = "" + , Знач JSON = "" + , Знач Файлы = "" , Знач ДопЗаголовки = "" - , Знач ФайлОтвета = Неопределено) Экспорт - + , Знач ФайлОтвета = Неопределено) Экспорт + Возврат ВыполнитьЗапросМультипартРелэйтед(URL, "POST", JSON, Файлы, ДопЗаголовки, ФайлОтвета); - + КонецФункции Функция PatchMultipartRelated(Знач URL - , Знач JSON = "" - , Знач Файлы = "" + , Знач JSON = "" + , Знач Файлы = "" , Знач ДопЗаголовки = "" - , Знач ФайлОтвета = Неопределено) Экспорт - + , Знач ФайлОтвета = Неопределено) Экспорт + Возврат ВыполнитьЗапросМультипартРелэйтед(URL, "PATCH", JSON, Файлы, ДопЗаголовки, ФайлОтвета); - + КонецФункции #КонецОбласти #Область Прочее -Процедура ОбработатьОтвет(Ответ, Знач ПолныйОтвет = Ложь) Экспорт - +Процедура ОбработатьОтвет(Ответ, Знач ПолныйОтвет = Ложь) Экспорт + Если ПолныйОтвет Или ТипЗнч(Ответ) <> Тип("HTTPОтвет") Тогда Возврат; КонецЕсли; - + ФайлТела = Ответ.ПолучитьИмяФайлаТела(); - + Если Не ФайлТела = Неопределено Тогда - Ответ = ФайлТела; + Ответ = ФайлТела; Возврат; КонецЕсли; - - GZip = "gzip"; - НужнаРаспаковка = - Ответ.Заголовки.Получить("Content-Encoding") = GZip + + GZip = "gzip"; + НужнаРаспаковка = + Ответ.Заголовки.Получить("Content-Encoding") = GZip Или Ответ.Заголовки.Получить("content-encoding") = GZip; - + Если НужнаРаспаковка Тогда Ответ = РаспаковатьОтвет(Ответ); КонецЕсли; - + Ответ = ?(ТипЗнч(Ответ) = Тип("HTTPОтвет"), Ответ.ПолучитьТелоКакДвоичныеДанные(), Ответ); - + Если ТипЗнч(Ответ) = Тип("ДвоичныеДанные") Тогда - + Попытка Ответ = JsonВСтруктуру(Ответ); Исключение Возврат; КонецПопытки; - + КонецЕсли; - + КонецПроцедуры Функция СоздатьЗапрос(Знач Адрес, Знач ДопЗаголовки = "", Знач ТипДанных = "") Экспорт - + Заголовки = Новый Соответствие; Заголовки.Вставить("Accept-Encoding", "gzip"); Заголовки.Вставить("Accept" , "*/*"); Заголовки.Вставить("Connection" , "keep-alive"); Заголовки.Вставить("Accept-Charset" , "utf-8"); - + Если ЗначениеЗаполнено(ТипДанных) Тогда Заголовки.Вставить("Content-Type", ТипДанных); КонецЕсли; - + Если ТипЗнч(ДопЗаголовки) = Тип("Соответствие") Тогда - + Для Каждого Заголовок Из ДопЗаголовки Цикл Заголовки.Вставить(Заголовок.Ключ, Заголовок.Значение); КонецЦикла; - + КонецЕсли; - + НовыйЗапрос = Новый HTTPЗапрос(Адрес, Заголовки); - + Возврат НовыйЗапрос; - + КонецФункции Функция СоздатьСоединение(Знач Сервер, Знач Пользователь = "", Знач Пароль = "") Экспорт - - Попытка + + Попытка SSL = Новый ЗащищенноеСоединениеOpenSSL; Возврат Новый HTTPСоединение(Сервер, 443, Пользователь, Пароль, , 3000, SSL); Исключение Возврат Новый HTTPСоединение(Сервер, 443, Пользователь, Пароль, , 3000); КонецПопытки; - + КонецФункции #КонецОбласти @@ -236,12 +236,12 @@ СтрокаПараметров = "?"; Для Каждого Параметр Из Параметры Цикл - + ЗначениеПараметра = ПреобразоватьПараметрВСтроку(Параметр.Значение); - - СтрокаПараметров = СтрокаПараметров - + Параметр.Ключ - + "=" + + СтрокаПараметров = СтрокаПараметров + + Параметр.Ключ + + " =" + ЗначениеПараметра + "&"; КонецЦикла; @@ -255,18 +255,18 @@ Функция РазбитьURL(Знач URL) Экспорт URL = СтрЗаменить(URL, "https://", ""); - URL = СтрЗаменить(URL, "http://", ""); - URL = СтрЗаменить(URL, ":443", ""); + URL = СтрЗаменить(URL, "http://" , ""); + URL = СтрЗаменить(URL, ":443" , ""); Адрес = Прав(URL, СтрДлина(URL) - СтрНайти(URL, "/", НаправлениеПоиска.СНачала) + 1); Сервер = Лев(URL, СтрНайти(URL, "/", НаправлениеПоиска.СНачала) - 1); - - Попытка - SSL = Новый ЗащищенноеСоединениеOpenSSL; + + Попытка + SSL = Новый ЗащищенноеСоединениеOpenSSL; Исключение Сервер = "https://" + Сервер; КонецПопытки; - + СтруктураВозврата = Новый Структура; СтруктураВозврата.Вставить("Сервер", Сервер); СтруктураВозврата.Вставить("Адрес" , Адрес); @@ -280,7 +280,7 @@ Если Не ЗначениеЗаполнено(Текст) Тогда Возврат ""; КонецЕсли; - + Текст = ?(ТипЗнч(Текст) = Тип("ДвоичныеДанные"), ПолучитьСтрокуИзДвоичныхДанных(Текст), Текст); ЧтениеJSON = Новый ЧтениеJSON; @@ -305,14 +305,14 @@ , Ложь); Попытка - + ЗаписьJSON = Новый ЗаписьJSON; ЗаписьJSON.УстановитьСтроку(ПараметрыJSON); - + ЗаписатьJSON(ЗаписьJSON, Данные); Возврат ЗаписьJSON.Закрыть(); - - Исключение + + Исключение Возврат "НЕ JSON: " + Строка(Данные); КонецПопытки; @@ -323,15 +323,15 @@ КонецФункции Функция ПрочитатьJSONФайл(Знач Путь) Экспорт - + ЧтениеJSON = Новый ЧтениеJSON; - ЧтениеJSON.ОткрытьФайл(Путь); - Значения = ПрочитатьJSON(ЧтениеJSON); - + ЧтениеJSON.ОткрытьФайл(Путь); + Значения = ПрочитатьJSON(ЧтениеJSON); + ЧтениеJSON.Закрыть(); - + Возврат Значения; - + КонецФункции Функция ПараметрыЗапросаВСоответствие(Знач СтрокаПараметров) Экспорт @@ -355,104 +355,104 @@ КонецФункции Функция ПолучитьТекущуюДату() Экспорт - Возврат МестноеВремя(ТекущаяУниверсальнаяДата()); + Возврат МестноеВремя(ТекущаяУниверсальнаяДата()); КонецФункции Функция UNIXTime(Знач Дата) Экспорт - + ОТД = Новый ОписаниеТипов("Дата"); Дата = ОТД.ПривестиЗначение(Дата); - + UNIX = Формат(Дата - Дата(1970, 1, 1, 1, 0, 0), "ЧЦ=10; ЧДЦ=0; ЧГ=0"); - UNIX = СтрЗаменить(UNIX, ",", ""); + UNIX = СтрЗаменить(UNIX, "," , ""); UNIX = СтрЗаменить(UNIX, Символы.НПП, ""); - UNIX = СтрЗаменить(UNIX, " ", ""); + UNIX = СтрЗаменить(UNIX, " " , ""); UNIX = Лев(UNIX, 10); - + Возврат UNIX; - + КонецФункции Функция ИнформацияОПрогрессе(Знач Текущее, Знач Всего, Знач ЕдИзм, Знач Делитель = 1) Экспорт - + Целое = 100; Текущее = Окр(Текущее / Делитель, 2); - Всего = Окр(Всего / Делитель, 2); + Всего = Окр(Всего / Делитель, 2); Процент = Цел(Текущее / Всего * Целое); - + СтрТекущее = ЧислоВСтроку(Текущее); СтрВсего = ЧислоВСтроку(Всего); СтрПроцент = ЧислоВСтроку(Процент); - + Информация = СтрТекущее + "/" + СтрВсего + " " + ЕдИзм + " ( " + СтрПроцент + "% )"; - + Возврат Информация; - + КонецФункции Функция ПреобразоватьДанныеСПолучениемРазмера(Данные, Знач МинимальныйРазмерДляПотока = 0) Экспорт - + Размер = 0; - + Если ТипЗнч(Данные) = Тип("Строка") Тогда - + ФайлНаДиске = Новый Файл(Данные); - - Если ФайлНаДиске.Существует() Тогда - Размер = ФайлНаДиске.Размер(); + + Если ФайлНаДиске.Существует() Тогда + Размер = ФайлНаДиске.Размер(); Иначе OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Данные); Размер = Данные.Размер(); КонецЕсли; - + Иначе OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Данные); Размер = Данные.Размер(); КонецЕсли; - + Если ЗначениеЗаполнено(МинимальныйРазмерДляПотока) Тогда Если Размер < МинимальныйРазмерДляПотока Тогда OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Данные); Иначе - OPI_ПреобразованиеТипов.ПолучитьДвоичныеИлиПоток(Данные); - КонецЕсли; + OPI_ПреобразованиеТипов.ПолучитьДвоичныеИлиПоток(Данные); + КонецЕсли; Иначе OPI_ПреобразованиеТипов.ПолучитьДвоичныеИлиПоток(Данные); КонецЕсли; - + Возврат Размер; - + КонецФункции Процедура ЗначениеВМассив(Значение) Экспорт - + Значение_ = Новый Массив; Значение_.Добавить(Значение); - Значение = Значение_; + Значение = Значение_; КонецПроцедуры Процедура ЗаменитьСпецСимволы(Текст, Разметка = "Markdown") Экспорт - + СоответствиеСимволов = Новый Соответствие; - + Если Разметка = "HTML" Тогда - + СоответствиеСимволов.Вставить("&", "&"); - + ИначеЕсли Разметка = "MarkdownV2" Тогда - + СоответствиеСимволов.Вставить("-", "\-"); СоответствиеСимволов.Вставить("+", "\+"); - СоответствиеСимволов.Вставить("#", "\#"); + СоответствиеСимволов.Вставить("#", "\#"); СоответствиеСимволов.Вставить("=", "\="); - СоответствиеСимволов.Вставить("{", "\{"); - СоответствиеСимволов.Вставить("}", "\}"); + СоответствиеСимволов.Вставить("{", "\{"); + СоответствиеСимволов.Вставить("}", "\}"); СоответствиеСимволов.Вставить(".", "\."); - + Иначе Возврат; - КонецЕсли; + КонецЕсли; Для Каждого СимволМассива Из СоответствиеСимволов Цикл Текст = СтрЗаменить(Текст, СимволМассива.Ключ, СимволМассива.Значение); @@ -461,80 +461,80 @@ КонецПроцедуры Процедура УдалитьПустыеПоляКоллекции(Коллекция) Экспорт - + ТипКоллекции = ТипЗнч(Коллекция); ВыходнаяКоллекция = Новый(ТипКоллекции); - + Если ТипКоллекции = Тип("Соответствие") Или ТипКоллекции = Тип("Структура") Тогда - + УдалитьПустыеКлючиЗначения(Коллекция, ВыходнаяКоллекция); - + ИначеЕсли ТипКоллекции = Тип("Массив") Тогда - + УдалитьПустыеЭлементыМассива(Коллекция, ВыходнаяКоллекция); - + Иначе - + ВыходнаяКоллекция = Коллекция; - + КонецЕсли; - + Коллекция = ВыходнаяКоллекция; - + КонецПроцедуры Процедура Пауза(Знач Секунды) Экспорт - + Соединение = Новый HTTPСоединение("1C.ru", 11111, , , , Секунды); Попытка Соединение.Получить(Новый HTTPЗапрос("")); Исключение - Возврат; + Возврат; КонецПопытки; - + КонецПроцедуры Процедура ДобавитьПоле(Знач Имя, Знач Значение, Знач Тип, Коллекция) Экспорт - + Заполнено = ЗначениеЗаполнено(Значение); - + Если Не Заполнено Тогда Возврат; КонецЕсли; - - Если Тип = "Дата" Тогда + + Если Тип = "Дата" Тогда OPI_ПреобразованиеТипов.ПолучитьДату(Значение); Значение = UNIXTime(Значение); - + ИначеЕсли Тип = "ДатаISO" Тогда OPI_ПреобразованиеТипов.ПолучитьДату(Значение); - Значение = XMLСтрока(Значение); - + Значение = XMLСтрока(Значение); + ИначеЕсли Тип = "Коллекция" Тогда - OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Значение); - + OPI_ПреобразованиеТипов.ПолучитьКоллекцию(Значение); + ИначеЕсли Тип = "Булево" Тогда - OPI_ПреобразованиеТипов.ПолучитьБулево(Значение); - + OPI_ПреобразованиеТипов.ПолучитьБулево(Значение); + ИначеЕсли Тип = "СтрокаФайла" Тогда OPI_ПреобразованиеТипов.ПолучитьСтроку(Значение, Истина); - + ИначеЕсли Тип = "Массив" Тогда OPI_ПреобразованиеТипов.ПолучитьМассив(Значение); - + ИначеЕсли Тип = "ДвоичныеДанные" Тогда OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Значение); - + ИначеЕсли Тип = "Число" Тогда OPI_ПреобразованиеТипов.ПолучитьЧисло(Значение); - + Иначе OPI_ПреобразованиеТипов.ПолучитьСтроку(Значение); - + КонецЕсли; - + Коллекция.Вставить(Имя, Значение); - + КонецПроцедуры #КонецОбласти @@ -545,24 +545,24 @@ Функция ВыполнитьЗапросСТелом(Знач URL , Знач Вид - , Знач Параметры = "" + , Знач Параметры = "" , Знач ДопЗаголовки = "" - , Знач JSON = Истина - , Знач ПолныйОтвет = Ложь - , Знач ФайлОтвета = Неопределено) - + , Знач JSON = Истина + , Знач ПолныйОтвет = Ложь + , Знач ФайлОтвета = Неопределено) + Если Не ЗначениеЗаполнено(Параметры) Тогда Параметры = Новый Структура; КонецЕсли; - - ТипДанных = ?(JSON, "application/json; charset=utf-8", "application/x-www-form-urlencoded; charset=utf-8"); + + ТипДанных = ?(JSON, "application/json; charset=utf-8", "application/x-www-form-urlencoded; charset=utf-8"); СтруктураURL = РазбитьURL(URL); Сервер = СтруктураURL["Сервер"]; Адрес = СтруктураURL["Адрес"]; - + Запрос = СоздатьЗапрос(Адрес, ДопЗаголовки, ТипДанных); Соединение = СоздатьСоединение(Сервер); - + УстановитьТелоЗапроса(Запрос, Параметры, JSON); Если ЗначениеЗаполнено(ФайлОтвета) Тогда @@ -570,17 +570,17 @@ Иначе Ответ = Соединение.ВызватьHTTPМетод(Вид, Запрос); КонецЕсли; - - Если ЭтоПереадресация(Ответ) Тогда + + Если ЭтоПереадресация(Ответ) Тогда Ответ = ВыполнитьЗапросСТелом(Ответ.Заголовки["Location"] , Вид , Параметры , ДопЗаголовки , JSON , ПолныйОтвет - , ФайлОтвета); - Иначе - ОбработатьОтвет(Ответ, ПолныйОтвет); + , ФайлОтвета); + Иначе + ОбработатьОтвет(Ответ, ПолныйОтвет); КонецЕсли; Возврат Ответ; @@ -593,29 +593,29 @@ , Знач ДопЗаголовки , Знач ПолныйОтвет , Знач ТипДанных) - + СтруктураURL = РазбитьURL(URL); Сервер = СтруктураURL["Сервер"]; Адрес = СтруктураURL["Адрес"]; - + Запрос = СоздатьЗапрос(Адрес, ДопЗаголовки, ТипДанных); Соединение = СоздатьСоединение(Сервер); - + Если Не Данные.Размер() = 0 Тогда Запрос.УстановитьТелоИзДвоичныхДанных(Данные); КонецЕсли; - + Ответ = Соединение.ВызватьHTTPМетод(Вид, Запрос); - Если ЭтоПереадресация(Ответ) Тогда + Если ЭтоПереадресация(Ответ) Тогда Ответ = ВыполнитьЗапросСДвоичнымиДанными(Ответ.Заголовки["Location"] , Вид , Данные , ДопЗаголовки , ПолныйОтвет - , ТипДанных); - Иначе - ОбработатьОтвет(Ответ, ПолныйОтвет); + , ТипДанных); + Иначе + ОбработатьОтвет(Ответ, ПолныйОтвет); КонецЕсли; Возврат Ответ; @@ -624,10 +624,10 @@ Функция ВыполнитьЗапросБезТела(Знач URL , Знач Вид - , Знач Параметры = "" + , Знач Параметры = "" , Знач ДопЗаголовки = "" - , Знач ФайлОтвета = Неопределено) - + , Знач ФайлОтвета = Неопределено) + Если Не ЗначениеЗаполнено(Параметры) Тогда Параметры = Новый Структура; КонецЕсли; @@ -635,34 +635,34 @@ СтруктураURL = РазбитьURL(URL); Сервер = СтруктураURL["Сервер"]; Адрес = СтруктураURL["Адрес"] + ПараметрыЗапросаВСтроку(Параметры); - + Запрос = СоздатьЗапрос(Адрес, ДопЗаголовки); - Соединение = СоздатьСоединение(Сервер); - + Соединение = СоздатьСоединение(Сервер); + Если ЗначениеЗаполнено(ФайлОтвета) Тогда Ответ = Соединение.ВызватьHTTPМетод(Вид, Запрос, ФайлОтвета); Иначе Ответ = Соединение.ВызватьHTTPМетод(Вид, Запрос); КонецЕсли; - - Если ЭтоПереадресация(Ответ) Тогда - Ответ = ВыполнитьЗапросБезТела(Ответ.Заголовки["Location"], Вид, Параметры, ДопЗаголовки, ФайлОтвета); - Иначе - ОбработатьОтвет(Ответ); + + Если ЭтоПереадресация(Ответ) Тогда + Ответ = ВыполнитьЗапросБезТела(Ответ.Заголовки["Location"], Вид, Параметры, ДопЗаголовки, ФайлОтвета); + Иначе + ОбработатьОтвет(Ответ); КонецЕсли; Возврат Ответ; - + КонецФункции Функция ВыполнитьЗапросМультипарт(Знач URL , Знач Вид - , Знач Параметры = "" - , Знач Файлы = "" - , Знач ТипКонтента = "image/jpeg" + , Знач Параметры = "" + , Знач Файлы = "" + , Знач ТипКонтента = "image/jpeg" , Знач ДопЗаголовки = "" - , Знач ФайлОтвета = Неопределено) - + , Знач ФайлОтвета = Неопределено) + Если Не ЗначениеЗаполнено(Параметры) Тогда Параметры = Новый Структура; КонецЕсли; @@ -679,10 +679,10 @@ СтруктураURL = РазбитьURL(URL); Сервер = СтруктураURL["Сервер"]; Адрес = СтруктураURL["Адрес"]; - + Запрос = СоздатьЗапрос(Адрес, ДопЗаголовки, ТипДанных); Соединение = СоздатьСоединение(Сервер); - + ТелоЗапроса = ПолучитьИмяВременногоФайла(); ЗаписьТекста = Новый ЗаписьДанных(ТелоЗапроса , КодировкаТекста.UTF8 @@ -694,47 +694,47 @@ ЗаписатьПараметрыМультипарт(ЗаписьТекста, Boundary, Параметры); ЗаписатьФайлыМультипарт(ЗаписьТекста, Boundary, ТипКонтента, Файлы); - + ЗаписьТекста.ЗаписатьСтроку("--" + boundary + "--" + РазделительСтрок); ЗаписьТекста.Закрыть(); Запрос.УстановитьИмяФайлаТела(ТелоЗапроса); - + Если ЗначениеЗаполнено(ФайлОтвета) Тогда Ответ = Соединение.ВызватьHTTPМетод(Вид, Запрос, ФайлОтвета); Иначе Ответ = Соединение.ВызватьHTTPМетод(Вид, Запрос); КонецЕсли; - + ЭтоПереадресация = Ответ.КодСостояния >= Переадресация И Ответ.КодСостояния < Ошибка; - - Если ЭтоПереадресация Тогда + + Если ЭтоПереадресация Тогда Ответ = ВыполнитьЗапросМультипарт(Ответ.Заголовки["Location"] , Вид , Параметры , Файлы , ТипКонтента , ДопЗаголовки - , ФайлОтвета); - Иначе - ОбработатьОтвет(Ответ); + , ФайлОтвета); + Иначе + ОбработатьОтвет(Ответ); КонецЕсли; - + Запрос = Неопределено; ЗаписьТекста = Неопределено; - + УдалитьФайлы(ТелоЗапроса); Возврат Ответ; - + КонецФункции Функция ВыполнитьЗапросМультипартРелэйтед(Знач URL , Знач Вид - , Знач JSON = "" - , Знач Файлы = "" + , Знач JSON = "" + , Знач Файлы = "" , Знач ДопЗаголовки = "" - , Знач ФайлОтвета = Неопределено) - + , Знач ФайлОтвета = Неопределено) + Переадресация = 300; Ошибка = 400; Boundary = СтрЗаменить(Строка(Новый УникальныйИдентификатор), "-", ""); @@ -743,10 +743,10 @@ СтруктураURL = РазбитьURL(URL); Сервер = СтруктураURL["Сервер"]; Адрес = СтруктураURL["Адрес"]; - + Запрос = СоздатьЗапрос(Адрес, ДопЗаголовки, ТипДанных); Соединение = СоздатьСоединение(Сервер); - + ТелоЗапроса = ПолучитьИмяВременногоФайла(); ЗаписьТекста = Новый ЗаписьДанных(ТелоЗапроса , КодировкаТекста.UTF8 @@ -755,36 +755,36 @@ , Ложь , "" , Ложь); - + ЗаписатьJSONМультипарт(ЗаписьТекста, Boundary, JSON); - ЗаписатьФайлыРелэйтед(ЗаписьТекста, Boundary, Файлы); - + ЗаписатьФайлыРелэйтед(ЗаписьТекста, Boundary, Файлы); + ЗаписьТекста.ЗаписатьСтроку("--" + boundary + "--" + РазделительСтрок); ЗаписьТекста.Закрыть(); - + ДобавитьContentLength(Запрос); - + Запрос.УстановитьИмяФайлаТела(ТелоЗапроса); - + Если ЗначениеЗаполнено(ФайлОтвета) Тогда Ответ = Соединение.ВызватьHTTPМетод(Вид, Запрос, ФайлОтвета); Иначе Ответ = Соединение.ВызватьHTTPМетод(Вид, Запрос); КонецЕсли; - + ЭтоПереадресация = Ответ.КодСостояния >= Переадресация И Ответ.КодСостояния < Ошибка; - - Если ЭтоПереадресация Тогда + + Если ЭтоПереадресация Тогда Ответ = ВыполнитьЗапросМультипартРелэйтед(Ответ.Заголовки["Location"] , Вид , JSON , Файлы , ДопЗаголовки - , ФайлОтвета); - Иначе - ОбработатьОтвет(Ответ); + , ФайлОтвета); + Иначе + ОбработатьОтвет(Ответ); КонецЕсли; - + Запрос = Неопределено; ЗаписьТекста = Неопределено; @@ -794,31 +794,31 @@ КонецФункции Функция ЭтоПереадресация(Знач Ответ) - + Переадресация = 300; Ошибка = 400; - ЭтоПереадресация = Ответ.КодСостояния >= Переадресация + ЭтоПереадресация = Ответ.КодСостояния >= Переадресация И Ответ.КодСостояния < Ошибка И ЗначениеЗаполнено(Ответ.Заголовки["Location"]); - + Возврат ЭтоПереадресация; - + КонецФункции Функция ПреобразоватьПараметрВСтроку(Знач Значение) Если ТипЗнч(Значение) = Тип("Массив") Тогда - Значение = СтрСоединить(Значение, ","); - Значение = КодироватьСтроку(Значение, СпособКодированияСтроки.URLВКодировкеURL); - Значение = "[" + Значение + "]"; + Значение = СтрСоединить(Значение, ","); + Значение = КодироватьСтроку(Значение, СпособКодированияСтроки.URLВКодировкеURL); + Значение = "[" + Значение + "]"; Иначе - Значение = ЧислоВСтроку(Значение); - Значение = КодироватьСтроку(Значение, СпособКодированияСтроки.URLВКодировкеURL); + Значение = ЧислоВСтроку(Значение); + Значение = КодироватьСтроку(Значение, СпособКодированияСтроки.URLВКодировкеURL); КонецЕсли; - + Возврат Значение; - + КонецФункции Функция РазобратьКлючФайла(Знач ДанныеФайла, Знач ТипКонтента) @@ -827,134 +827,134 @@ ИмяФайла = СтрЗаменить(ДанныеФайла, ЗаменаТочки, "."); МассивИмени = СтрРазделить(ИмяФайла, "|", Ложь); ЧастейИмени = 2; - + Если МассивИмени.Количество() = ЧастейИмени Тогда ИмяПоля = МассивИмени[0]; ИмяФайла = МассивИмени[1]; Иначе - + Если ТипКонтента = "image/jpeg" Тогда - ИмяПоля = "photo"; + ИмяПоля = "photo"; Иначе - ИмяПоля = Лев(ИмяФайла, СтрНайти(ИмяФайла, ".") - 1); - ИмяПоля = ?(ЗначениеЗаполнено(ИмяПоля), ИмяПоля, СтрЗаменить(ДанныеФайла, + ИмяПоля = Лев(ИмяФайла, СтрНайти(ИмяФайла, ".") - 1); + ИмяПоля = ?(ЗначениеЗаполнено(ИмяПоля), ИмяПоля, СтрЗаменить(ДанныеФайла, ЗаменаТочки, ".")); КонецЕсли; - + КонецЕсли; - + СтруктураВозврата = Новый Структура("ИмяПоля,ИмяФайла", ИмяПоля, ИмяФайла); - + Возврат СтруктураВозврата; - + КонецФункции Процедура УстановитьТелоЗапроса(Запрос, Знач Параметры, Знач JSON) - - Коллекция = ТипЗнч(Параметры) = Тип("Структура") + + Коллекция = ТипЗнч(Параметры) = Тип("Структура") Или ТипЗнч(Параметры) = Тип("Соответствие") Или ТипЗнч(Параметры) = Тип("Массив"); - + Если JSON Тогда Данные = JSONСтрокой(Параметры); ИначеЕсли Не Коллекция Тогда - Данные = Параметры; + Данные = Параметры; Иначе СтрокаПараметров = ПараметрыЗапросаВСтроку(Параметры); Данные = Прав(СтрокаПараметров, СтрДлина(СтрокаПараметров) - 1); КонецЕсли; - + Если ТипЗнч(Данные) = Тип("Строка") Тогда Запрос.УстановитьТелоИзСтроки(Данные); Иначе //@skip-check wrong-type-expression Запрос.УстановитьТелоИзДвоичныхДанных(Данные); КонецЕсли; - + КонецПроцедуры Процедура ЗаписатьПараметрыМультипарт(ЗаписьТекста, Знач Boundary, Знач Параметры) - + РазделительСтрок = Символы.ВК + Символы.ПС; - + Для Каждого Параметр Из Параметры Цикл - - Если Параметр.Значение = Неопределено + + Если Параметр.Значение = Неопределено Или Параметр.Значение = NULL Тогда Продолжить; КонецЕсли; - + ЗаписьТекста.ЗаписатьСтроку("--" + boundary + РазделительСтрок); ЗаписьТекста.ЗаписатьСтроку("Content-Disposition: form-data; name=""" + Параметр.Ключ + """"); ЗаписьТекста.ЗаписатьСтроку(РазделительСтрок); ЗаписьТекста.ЗаписатьСтроку(РазделительСтрок); - - Если ТипЗнч(Параметр.Значение) = Тип("Строка") + + Если ТипЗнч(Параметр.Значение) = Тип("Строка") Или ТипЗнч(Параметр.Значение) = Тип("Число") Тогда - + ЗначениеСтрокой = ЧислоВСтроку(Параметр.Значение); ЗаписьТекста.ЗаписатьСтроку(ЗначениеСтрокой); - + ИначеЕсли ТипЗнч(Параметр.Значение) = Тип("Булево") Тогда - + ЗаписьТекста.ЗаписатьСтроку(?(Параметр.Значение, "true", "false")); - + Иначе - + ЗаписьТекста.Записать(Параметр.Значение); - + КонецЕсли; - + ЗаписьТекста.ЗаписатьСтроку(РазделительСтрок); - + КонецЦикла; - + КонецПроцедуры Процедура ЗаписатьФайлыМультипарт(ЗаписьТекста, Знач Boundary, Знач ТипКонтента, Знач Файлы) - + ТипКонтента = СокрЛП(ТипКонтента); РазделительСтрок = Символы.ВК + Символы.ПС; - + Для Каждого Файл Из Файлы Цикл - + СтруктураИнформации = РазобратьКлючФайла(Файл.Ключ, ТипКонтента); - + ИмяПоля = СтруктураИнформации["ИмяПоля"]; ИмяФайла = СтруктураИнформации["ИмяФайла"]; - + ЗаписьТекста.ЗаписатьСтроку("--" + boundary + РазделительСтрок); - ЗаписьТекста.ЗаписатьСтроку("Content-Disposition: form-data; name=""" - + ИмяПоля - + """; filename=""" + ЗаписьТекста.ЗаписатьСтроку("Content-Disposition: form-data; name=""" + + ИмяПоля + + """; filename=""" + ИмяФайла + """"); - ЗаписьТекста.ЗаписатьСтроку(РазделительСтрок); - + ЗаписьТекста.ЗаписатьСтроку(РазделительСтрок); + Если ЗначениеЗаполнено(ТипКонтента) Тогда ЗаписьТекста.ЗаписатьСтроку("Content-Type: " + ТипКонтента); КонецЕсли; - + ЗаписьТекста.ЗаписатьСтроку(РазделительСтрок); ЗаписьТекста.ЗаписатьСтроку(РазделительСтрок); ЗаписатьДвоичныеДанные(ЗаписьТекста, Файл.Значение); ЗаписьТекста.ЗаписатьСтроку(РазделительСтрок); - + КонецЦикла; КонецПроцедуры Процедура ЗаписатьФайлыРелэйтед(ЗаписьТекста, Знач Boundary, Знач Файлы) - + Если Не ЗначениеЗаполнено(Файлы) Тогда Возврат; КонецЕсли; - + РазделительСтрок = Символы.ВК + Символы.ПС; - + Если ТипЗнч(Файлы) = Тип("Соответствие") Тогда Для Каждого Файл Из Файлы Цикл - + ЗаписьТекста.ЗаписатьСтроку("--" + boundary + РазделительСтрок); ЗаписьТекста.ЗаписатьСтроку("Content-Type: " + Файл.Значение); ЗаписьТекста.ЗаписатьСтроку(РазделительСтрок); @@ -962,51 +962,51 @@ ЗаписатьДвоичныеДанные(ЗаписьТекста, Файл.Ключ); ЗаписьТекста.ЗаписатьСтроку(РазделительСтрок); ЗаписьТекста.ЗаписатьСтроку(РазделительСтрок); - + КонецЦикла; - + КонецЕсли; КонецПроцедуры Процедура ЗаписатьДвоичныеДанные(ЗаписьДанных, Знач ДвоичныеДанные) - + РазмерЧасти = 268435456; ПрочитанноБайт = 0; ТекущаяПозиция = 0; ОбщийРазмер = ДвоичныеДанные.Размер(); Пока ПрочитанноБайт < ОбщийРазмер Цикл - + ЧтениеДанных = Новый ЧтениеДанных(ДвоичныеДанные); ПрочитанноБайт = ЧтениеДанных.Пропустить(ТекущаяПозиция); Результат = ЧтениеДанных.Прочитать(РазмерЧасти); ТекущиеДанные = Результат.ПолучитьДвоичныеДанные(); РазмерТекущих = ТекущиеДанные.Размер(); - + Если Не ЗначениеЗаполнено(ТекущиеДанные) Тогда Прервать; КонецЕсли; ЗаписьДанных.Записать(ТекущиеДанные); - + // !OInt ОсвободитьОбъект(ТекущиеДанные); // !OInt ВыполнитьСборкуМусора(); ТекущаяПозиция = ТекущаяПозиция + РазмерТекущих; - + КонецЦикла; КонецПроцедуры Процедура ЗаписатьJSONМультипарт(ЗаписьТекста, Знач Boundary, Знач JSON) - + Если Не ЗначениеЗаполнено(JSON) Тогда Возврат; КонецЕсли; - + РазделительСтрок = Символы.ВК + Символы.ПС; - + ЗаписьТекста.ЗаписатьСтроку("--" + boundary + РазделительСтрок); ЗаписьТекста.ЗаписатьСтроку("Content-Type: application/json; charset=UTF-8"); ЗаписьТекста.ЗаписатьСтроку(РазделительСтрок); @@ -1018,46 +1018,46 @@ КонецПроцедуры Процедура ДобавитьContentLength(Запрос) - + ТелоЗапроса = Запрос.ПолучитьТелоКакДвоичныеДанные(); - + Если ЗначениеЗаполнено(ТелоЗапроса) Тогда - + Размер = ТелоЗапроса.Размер(); Запрос.Заголовки.Вставить("Content-Length", ЧислоВСтроку(Размер)); - + КонецЕсли; КонецПроцедуры Процедура УдалитьПустыеКлючиЗначения(Знач Коллекция, ВыходнаяКоллекция) - + Для Каждого ЭлементКоллекции Из Коллекция Цикл - + Если Не ЭлементКоллекции.Значение = Неопределено И Не ЭлементКоллекции.Значение = NULL Тогда ВыходнаяКоллекция.Вставить(ЭлементКоллекции.Ключ, ЭлементКоллекции.Значение); КонецЕсли; - + КонецЦикла; - + КонецПроцедуры Процедура УдалитьПустыеЭлементыМассива(Знач Коллекция, ВыходнаяКоллекция) - + Для Каждого ЭлементКоллекции Из Коллекция Цикл - + Если Не ЭлементКоллекции = Неопределено И Не ЭлементКоллекции = NULL Тогда ВыходнаяКоллекция.Добавить(ЭлементКоллекции); КонецЕсли; - + КонецЦикла; - + КонецПроцедуры #Область GZip // Описание структур см. здесь https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT -// Источник: https://github.com/vbondarevsky/Connector +// Источник: https://github.com/vbondarevsky/Connector // Коннектор: удобный HTTP-клиент для 1С:Предприятие 8 // @@ -1096,22 +1096,22 @@ РазмерПрефиксаGZip = 10; РазмерПостфиксаGZip = 8; - + РазмерДД = ZipРазмерDD(); РазмерСДХ = ZipРазмерCDH(); РазмерЕСД = ZipРазмерEOCD(); РазмерЛФХ = ZipРазмерLFH(); - ЧтениеДанных = Новый ЧтениеДанных(СжатыеДанные); + ЧтениеДанных = Новый ЧтениеДанных(СжатыеДанные); ЧтениеДанных.Пропустить(РазмерПрефиксаGZip); РазмерСжатыхДанных = ЧтениеДанных.ИсходныйПоток().Размер() - РазмерПрефиксаGZip - РазмерПостфиксаGZip; - ПотокZip = Новый ПотокВПамяти(РазмерЛФХ - + РазмерСжатыхДанных - + РазмерДД - + РазмерСДХ + ПотокZip = Новый ПотокВПамяти(РазмерЛФХ + + РазмерСжатыхДанных + + РазмерДД + + РазмерСДХ + РазмерЕСД); - + ЗаписьДанных = Новый ЗаписьДанных(ПотокZip); ЗаписьДанных.ЗаписатьБуферДвоичныхДанных(ZipLFH()); ЧтениеДанных.КопироватьВ(ЗаписьДанных, РазмерСжатыхДанных); @@ -1123,7 +1123,7 @@ РазмерНесжатыхДанных = ЧтениеДанных.ПрочитатьЦелое32(); ЧтениеДанных.Закрыть(); - ЗаписьДанных.ЗаписатьБуферДвоичныхДанных(ZipDD(CRC32, РазмерСжатыхДанных, РазмерНесжатыхДанных)); + ЗаписьДанных.ЗаписатьБуферДвоичныхДанных(ZipDD(CRC32 , РазмерСжатыхДанных, РазмерНесжатыхДанных)); ЗаписьДанных.ЗаписатьБуферДвоичныхДанных(ZipCDH(CRC32, РазмерСжатыхДанных, РазмерНесжатыхДанных)); ЗаписьДанных.ЗаписатьБуферДвоичныхДанных(ZipEOCD(РазмерСжатыхДанных)); ЗаписьДанных.Закрыть(); @@ -1134,9 +1134,9 @@ Функция ПрочитатьZip(СжатыеДанные, ТекстОшибки = Неопределено) - Каталог = ПолучитьИмяВременногоФайла(); - ЧтениеZip = Новый ЧтениеZipФайла(СжатыеДанные); - ИмяФайла = ЧтениеZip.Элементы[0].Имя; + Каталог = ПолучитьИмяВременногоФайла(); + ЧтениеZip = Новый ЧтениеZipФайла(СжатыеДанные); + ИмяФайла = ЧтениеZip.Элементы[0].Имя; Попытка ЧтениеZip.Извлечь(ЧтениеZip.Элементы[0], Каталог, РежимВосстановленияПутейФайловZIP.НеВосстанавливать); Исключение @@ -1177,12 +1177,12 @@ КонецФункции Функция ZipLFH() - + // Local file header Буфер = Новый БуферДвоичныхДанных(ZipРазмерLFH()); Буфер.ЗаписатьЦелое32(0, 67324752); // signature 0x04034b50 Буфер.ЗаписатьЦелое16(4, 20); // version - Буфер.ЗаписатьЦелое16(6, 10); // bit flags + Буфер.ЗаписатьЦелое16(6, 10); // bit flags Буфер.ЗаписатьЦелое16(8, 8); // compression method Буфер.ЗаписатьЦелое16(10, 0); // time Буфер.ЗаписатьЦелое16(12, 0); // date @@ -1198,7 +1198,7 @@ КонецФункции Функция ZipDD(CRC32, РазмерСжатыхДанных, РазмерНесжатыхДанных) - + // Data descriptor Буфер = Новый БуферДвоичныхДанных(ZipРазмерDD()); Буфер.ЗаписатьЦелое32(0, 134695760); @@ -1211,7 +1211,7 @@ КонецФункции Функция ZipCDH(CRC32, РазмерСжатыхДанных, РазмерНесжатыхДанных) - + // Central directory header Буфер = Новый БуферДвоичныхДанных(ZipРазмерCDH()); Буфер.ЗаписатьЦелое32(0, 33639248); // signature 0x02014b50 @@ -1238,7 +1238,7 @@ КонецФункции Функция ZipEOCD(РазмерСжатыхДанных) - + // End of central directory РазмерCDH = 50; Буфер = Новый БуферДвоичныхДанных(ZipРазмерEOCD()); @@ -1247,7 +1247,7 @@ Буфер.ЗаписатьЦелое16(6, 0); // number of the disk with the start of the central directory Буфер.ЗаписатьЦелое16(8, 1); // total number of entries in the central directory on this disk Буфер.ЗаписатьЦелое16(10, 1); // total number of entries in the central directory - Буфер.ЗаписатьЦелое32(12, РазмерCDH); // size of the central directory + Буфер.ЗаписатьЦелое32(12, РазмерCDH); // size of the central directory // offset of start of central directory with respect to the starting disk number Буфер.ЗаписатьЦелое32(16, ZipРазмерLFH() + РазмерСжатыхДанных + ZipРазмерDD()); Буфер.ЗаписатьЦелое16(20, 0); // the starting disk number @@ -1258,4 +1258,4 @@ #КонецОбласти -#КонецОбласти \ No newline at end of file +#КонецОбласти diff --git a/src/ru/OPI/src/CommonModules/OPI_Криптография/Module.bsl b/src/ru/OPI/src/CommonModules/OPI_Криптография/Module.bsl index 6e0835b3e5..c3f43789e2 100644 --- a/src/ru/OPI/src/CommonModules/OPI_Криптография/Module.bsl +++ b/src/ru/OPI/src/CommonModules/OPI_Криптография/Module.bsl @@ -1,4 +1,4 @@ -// OneScript: ./OInt/tools/Modules/internal/Modules/OPI_Криптография.os +// OneScript: ./OInt/tools/Modules/internal/Modules/OPI_Криптография.os // MIT License @@ -39,75 +39,75 @@ /////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2019, ООО 1С-Софт -// Все права защищены. Эта программа и сопроводительные материалы предоставляются +// Все права защищены. Эта программа и сопроводительные материалы предоставляются // в соответствии с условиями лицензии Attribution 4.0 International (CC BY 4.0) // Текст лицензии доступен по ссылке: // https://creativecommons.org/licenses/by/4.0/legalcode /////////////////////////////////////////////////////////////////////////////////////////////////////// Функция HMACSHA256(Знач Ключ, Знач Данные) Экспорт - + Возврат HMAC(Ключ, Данные, ХешФункция.SHA256, 64); - + КонецФункции Функция Хеш(ДвоичныеДанные, Тип) Экспорт - + Хеширование = Новый ХешированиеДанных(Тип); Хеширование.Добавить(ДвоичныеДанные); - + Возврат Хеширование.ХешСумма; - + КонецФункции Функция HMAC(Знач Ключ, Знач Данные, Тип, РазмерБлока) Экспорт - + Дважды = 2; - + Если Ключ.Размер() > РазмерБлока Тогда Ключ = Хеш(Ключ, Тип); КонецЕсли; - + Если Ключ.Размер() <= РазмерБлока Тогда - Ключ = ПолучитьHexСтрокуИзДвоичныхДанных(Ключ); - Ключ = Лев(Ключ + ПовторитьСтроку("00", РазмерБлока), РазмерБлока * Дважды); + Ключ = ПолучитьHexСтрокуИзДвоичныхДанных(Ключ); + Ключ = Лев(Ключ + ПовторитьСтроку("00", РазмерБлока), РазмерБлока * Дважды); КонецЕсли; - + Ключ = ПолучитьБуферДвоичныхДанныхИзДвоичныхДанных(ПолучитьДвоичныеДанныеИзHexСтроки(Ключ)); - + Ipad = ПолучитьБуферДвоичныхДанныхИзHexСтроки(ПовторитьСтроку("36", РазмерБлока)); Opad = ПолучитьБуферДвоичныхДанныхИзHexСтроки(ПовторитьСтроку("5c", РазмерБлока)); - + Ipad.ЗаписатьПобитовоеИсключительноеИли(0, Ключ); Ikeypad = ПолучитьДвоичныеДанныеИзБуфераДвоичныхДанных(ipad); - + Opad.ЗаписатьПобитовоеИсключительноеИли(0, Ключ); Okeypad = ПолучитьДвоичныеДанныеИзБуфераДвоичныхДанных(opad); - + Возврат Хеш(СклеитьДвоичныеДанные(okeypad, Хеш(СклеитьДвоичныеДанные(ikeypad, Данные), Тип)), Тип); - + КонецФункции Функция СклеитьДвоичныеДанные(ДвоичныеДанные1, ДвоичныеДанные2) Экспорт - + МассивДвоичныхДанных = Новый Массив; МассивДвоичныхДанных.Добавить(ДвоичныеДанные1); МассивДвоичныхДанных.Добавить(ДвоичныеДанные2); - + Возврат СоединитьДвоичныеДанные(МассивДвоичныхДанных); - + КонецФункции Функция ПовторитьСтроку(Строка, Количество) Экспорт - + Части = Новый Массив(Количество); - + Для К = 1 По Количество Цикл Части.Добавить(Строка); КонецЦикла; Возврат СтрСоединить(Части, ""); - + КонецФункции #КонецОбласти diff --git a/src/ru/OPI/src/CommonModules/OPI_ПолучениеДанныхТестов/Module.bsl b/src/ru/OPI/src/CommonModules/OPI_ПолучениеДанныхТестов/Module.bsl index 2aabd5cc94..4566951959 100644 --- a/src/ru/OPI/src/CommonModules/OPI_ПолучениеДанныхТестов/Module.bsl +++ b/src/ru/OPI/src/CommonModules/OPI_ПолучениеДанныхТестов/Module.bsl @@ -1,4 +1,4 @@ -// OneScript: ./OInt/tools/Modules/OPI_ПолучениеДанныхТестов.os +// OneScript: ./OInt/tools/Modules/OPI_ПолучениеДанныхТестов.os // MIT License @@ -46,10 +46,10 @@ #Область СлужебныйПрограммныйИнтерфейс Функция ПолучитьСоответствиеРазделовТестирования() Экспорт - + СтандартныеЗависимости = "[Decode, Build]"; ЗависимостиГугл = "Testing-GoogleWorkspace"; - + Разделы = Новый Структура; Разделы.Вставить("Telegram" , СтандартныеЗависимости); Разделы.Вставить("VK" , СтандартныеЗависимости); @@ -57,7 +57,7 @@ Разделы.Вставить("Twitter" , СтандартныеЗависимости); Разделы.Вставить("YandexDisk" , СтандартныеЗависимости); Разделы.Вставить("GoogleWorkspace", СтандартныеЗависимости); - Разделы.Вставить("GoogleCalendar" , ЗависимостиГугл); + Разделы.Вставить("GoogleCalendar" , ЗависимостиГугл); Разделы.Вставить("GoogleDrive" , ЗависимостиГугл); Разделы.Вставить("GoogleSheets" , ЗависимостиГугл); Разделы.Вставить("Notion" , СтандартныеЗависимости); @@ -65,13 +65,13 @@ Разделы.Вставить("Airtable" , СтандартныеЗависимости); Разделы.Вставить("Dropbox" , СтандартныеЗависимости); Разделы.Вставить("Bitrix24" , СтандартныеЗависимости); - + Возврат Разделы; - + КонецФункции Функция ПолучитьТаблицуТестов() Экспорт - + Телеграм = "Telegram"; ВКонтакте = "VK"; ЯДиск = "YandexDisk"; @@ -86,13 +86,13 @@ АирТ = "Airtable"; ДропБокс = "Dropbox"; Битрикс = "Bitrix24"; - + ТаблицаТестов = Новый ТаблицаЗначений; ТаблицаТестов.Колонки.Добавить("Метод"); ТаблицаТестов.Колонки.Добавить("Синоним"); ТаблицаТестов.Колонки.Добавить("Раздел"); - - НовыйТест(ТаблицаТестов, "Телеграм_ПолучитьИнформациюБота" , "Получить информацию бота" , Телеграм); + + НовыйТест(ТаблицаТестов, "Телеграм_ПолучитьИнформациюБота" , "Получить информацию бота" , Телеграм); НовыйТест(ТаблицаТестов, "Телеграм_ПолучитьОбновления" , "Получить обновления" , Телеграм); НовыйТест(ТаблицаТестов, "Телеграм_УстановитьWebhook" , "Установить Webhook" , Телеграм); НовыйТест(ТаблицаТестов, "Телеграм_ОтправитьТекстовоеСообщение" , "Отправить текстовое сообщение" , Телеграм); @@ -114,7 +114,7 @@ НовыйТест(ТаблицаТестов, "Телеграм_СоздатьУдалитьТемуФорума" , "Создать/Удалить тему форума" , Телеграм); НовыйТест(ТаблицаТестов, "Телеграм_ИзменитьИмяГлавнойТемы" , "Изменить имя главной темы" , Телеграм); НовыйТест(ТаблицаТестов, "Телеграм_СкрытьПоказатьГлавнуюТему" , "Скрыть/Показать главную тему" , Телеграм); - + НовыйТест(ТаблицаТестов, "ВК_СоздатьСсылкуТокена" , "Создать ссылку получения токена", ВКонтакте); НовыйТест(ТаблицаТестов, "ВК_СоздатьУдалитьПост" , "Создать/Удалить пост" , ВКонтакте); НовыйТест(ТаблицаТестов, "ВК_СоздатьСоставнойПост" , "Создать/Удалить составной пост" , ВКонтакте); @@ -135,7 +135,7 @@ НовыйТест(ТаблицаТестов, "ВК_ПолучитьСписокСвойств" , "Получить список свойств" , ВКонтакте); НовыйТест(ТаблицаТестов, "ВК_ПолучитьСписокЗаказов" , "Получить список заказов" , ВКонтакте); НовыйТест(ТаблицаТестов, "ВК_ЗагрузитьВидео" , "Загрузить видео" , ВКонтакте); - + НовыйТест(ТаблицаТестов, "ЯДиск_ПолучитьИнформациюОДиске" , "Получить информацию о диске" , ЯДиск); НовыйТест(ТаблицаТестов, "ЯДиск_СоздатьПапку" , "Создать папку" , ЯДиск); НовыйТест(ТаблицаТестов, "ЯДиск_ЗагрузитьПоАдресуПолучитьОбъект", "Загрузить по URL и получить" , ЯДиск); @@ -146,25 +146,25 @@ НовыйТест(ТаблицаТестов, "ЯДиск_ПереместитьОбъект" , "Переместить объект" , ЯДиск); НовыйТест(ТаблицаТестов, "ЯДиск_ДействияПубличныхОбъектов" , "Действия с публичными объектами", ЯДиск); НовыйТест(ТаблицаТестов, "ЯДиск_ПолучитьСписокОпубликованных" , "Получить список опубликованных" , ЯДиск); - + НовыйТест(ТаблицаТестов, "ГВ_ПолучитьСсылкуАвторизации" , "Получить ссылку авторизации" , ВСпейс); НовыйТест(ТаблицаТестов, "ГВ_ПолучитьТокен" , "Получить токен" , ВСпейс); НовыйТест(ТаблицаТестов, "ГВ_ОбновитьТокен" , "Обновить токен" , ВСпейс); - + НовыйТест(ТаблицаТестов, "ГК_ПолучитьСписокКалендарей" , "Получить список календарей" , Календарь); НовыйТест(ТаблицаТестов, "ГК_СоздатьУдалитьКалендарь" , "Создать/Удалить календарь" , Календарь); НовыйТест(ТаблицаТестов, "ГК_СоздатьУдалитьСобытие" , "Создать/Удалить событие" , Календарь); НовыйТест(ТаблицаТестов, "ГК_ПолучитьСписокСобытий" , "Получить список событий" , Календарь); - + НовыйТест(ТаблицаТестов, "ГД_ПолучитьСписокКаталогов" , "Получить список каталогов" , Драйв); НовыйТест(ТаблицаТестов, "ГД_ЗагрузитьУдалитьФайл" , "Загрузить/Удалить Файл" , Драйв); НовыйТест(ТаблицаТестов, "ГД_СоздатьУдалитьКомментарий" , "Создать/Удалить кооментарий" , Драйв); НовыйТест(ТаблицаТестов, "ГД_СоздатьКаталог" , "Создать/Удалить каталог" , Драйв); - + НовыйТест(ТаблицаТестов, "ГТ_СоздатьТаблицу" , "Создать таблицу" , Таблицы); НовыйТест(ТаблицаТестов, "ГТ_ПолучитьТаблицу" , "Получить таблицу" , Таблицы); НовыйТест(ТаблицаТестов, "ГТ_ЗаполнитьОчиститьЯчейки" , "Заполнить/Очистить ячейки" , Таблицы); - + НовыйТест(ТаблицаТестов, "Твиттер_ПолучитьСсылкуАвторизации" , "Получить ссылку авторизации" , Твиттер); НовыйТест(ТаблицаТестов, "Твиттер_ОбновитьТокен" , "Обновить токен" , Твиттер); НовыйТест(ТаблицаТестов, "Твиттер_СоздатьТекстовыйТвит" , "Текстовый твит" , Твиттер); @@ -172,7 +172,7 @@ НовыйТест(ТаблицаТестов, "Твиттер_СоздатьТвитСВидео" , "Твит с видео" , Твиттер); НовыйТест(ТаблицаТестов, "Твиттер_СоздатьТвитСГиф" , "Твит с гиф" , Твиттер); НовыйТест(ТаблицаТестов, "Твиттер_СоздатьТвитСОпросом" , "Твит с опросом" , Твиттер); - + НовыйТест(ТаблицаТестов, "Вайбер_ПолучитьИнформациюОКанале" , "Получить информацию канала" , Вайбер); НовыйТест(ТаблицаТестов, "Вайбер_ПолучитьДанныеПользователя" , "Получить данные пользователя" , Вайбер); НовыйТест(ТаблицаТестов, "Вайбер_ПолучитьОнлайнПользователей" , "Получить онлайн пользователей" , Вайбер); @@ -182,7 +182,7 @@ НовыйТест(ТаблицаТестов, "Вайбер_ОтправитьКонтакт" , "Отправить контакт" , Вайбер); НовыйТест(ТаблицаТестов, "Вайбер_ОтправитьЛокацию" , "Отправить локацию" , Вайбер); НовыйТест(ТаблицаТестов, "Вайбер_ОтправитьСсылку" , "Отправить ссылку" , Вайбер); - + НовыйТест(ТаблицаТестов, "Ноушн_СоздатьСтраницу" , "Создать страницу" , Ноушн); НовыйТест(ТаблицаТестов, "Ноушн_СоздатьИзменитьБазу" , "Создать/Изменить базу" , Ноушн); НовыйТест(ТаблицаТестов, "Ноушн_ПолучитьИнформациюОСтранице" , "Получить информацию о странице" , Ноушн); @@ -192,7 +192,7 @@ НовыйТест(ТаблицаТестов, "Ноушн_СоздатьУдалитьБлок" , "Создать/Удалить блок" , Ноушн); НовыйТест(ТаблицаТестов, "Ноушн_ПолучитьПользователей" , "Получить пользователей" , Ноушн); НовыйТест(ТаблицаТестов, "Ноушн_ПолучитьДанныеПользователя" , "Получить данные пользователя" , Ноушн); - + НовыйТест(ТаблицаТестов, "Слак_ПолучитьИнформациюОБоте" , "Получить информацию о боте" , Слак); НовыйТест(ТаблицаТестов, "Слак_ПолучитьСписокПользователей" , "Получить список пользователей" , Слак); НовыйТест(ТаблицаТестов, "Слак_ПолучитьСписокОбластей" , "Получить список областей" , Слак); @@ -206,12 +206,12 @@ НовыйТест(ТаблицаТестов, "Слак_ЗагрузитьУдалитьФайл" , "Загрузить/Удалить файл" , Слак); НовыйТест(ТаблицаТестов, "Слак_ПолучитьСписокВФ" , "Получить список внеш. файлов" , Слак); НовыйТест(ТаблицаТестов, "Слак_ЗагрузитьУдалитьВФ" , "Загрузить/Удалить внеш. файл" , Слак); - + НовыйТест(ТаблицаТестов, "АТ_СоздатьБазу" , "Создать/Изменить базу" , АирТ); НовыйТест(ТаблицаТестов, "АТ_СоздатьТаблицу" , "Создать/Изменить таблицу" , АирТ); НовыйТест(ТаблицаТестов, "АТ_СоздатьПоле" , "Создать/Изменить поле" , АирТ); НовыйТест(ТаблицаТестов, "АТ_СоздатьУдалитьЗаписи" , "Создать/Удалить записи" , АирТ); - + НовыйТест(ТаблицаТестов, "ДропБокс_ПолучитьОбновитьТокен" , "Получить/Обновить токен" , ДропБокс); НовыйТест(ТаблицаТестов, "ДропБокс_ЗагрузитьФайл" , "Загрузить файл" , ДропБокс); НовыйТест(ТаблицаТестов, "ДропБокс_ЗагрузитьФайлПоURL" , "Загрузить файл по URL" , ДропБокс); @@ -220,7 +220,7 @@ НовыйТест(ТаблицаТестов, "ДропБокс_ПолучитьАккаунт" , "Получить данные аккаунта" , ДропБокс); НовыйТест(ТаблицаТестов, "ДропБокс_РаботаСДоступами" , "Работа с доступами" , ДропБокс); НовыйТест(ТаблицаТестов, "ДропБокс_ПолучитьСписокФайловПапки" , "Получить список файлов папки" , ДропБокс); - + НовыйТест(ТаблицаТестов, "Б24_РаботаСТокеном" , "Работа с токеном" , Битрикс); НовыйТест(ТаблицаТестов, "Б24_СерверноеВремя" , "Серверное время" , Битрикс); НовыйТест(ТаблицаТестов, "Б24_РаботаСНовостями" , "Работа с новостями" , Битрикс); @@ -231,215 +231,215 @@ НовыйТест(ТаблицаТестов, "Б24_УчетРабочегоВремени" , "Учет рабочего времени" , Битрикс); НовыйТест(ТаблицаТестов, "Б24_РаботаСЧатами" , "Работа с чатами" , Битрикс); НовыйТест(ТаблицаТестов, "Б24_РаботаСУведомлениями" , "Работа с уведомлениями" , Битрикс); - + Возврат ТаблицаТестов; - -КонецФункции + +КонецФункции Функция ОжидаетЧто(Значение) Экспорт - + Попытка - + Модуль = ПолучитьОбщийМодуль("ЮТест"); Ожидаем = ТипЗнч(Модуль) = Тип("ОбщийМодуль"); - Возврат Модуль.ОжидаетЧто(Значение); - + Возврат Модуль.ОжидаетЧто(Значение); + Исключение Возврат Ожидаем.Что(Значение); КонецПопытки; - + КонецФункции Функция СформироватьТестыЯкс() Экспорт - + Модуль = ПолучитьОбщийМодуль("ЮТТесты"); Разделы = ПолучитьСоответствиеРазделовТестирования(); ТаблицаТестов = ПолучитьТаблицуТестов(); - + Для Каждого Раздел Из Разделы Цикл - + ТекущийРаздел = Раздел.Ключ; Отбор = Новый Структура("Раздел", ТекущийРаздел); ТестыРаздела = ТаблицаТестов.НайтиСтроки(Отбор); - + Набор = Модуль.ДобавитьТестовыйНабор(ТекущийРаздел); - + Для Каждого Тест Из ТестыРаздела Цикл Набор.ДобавитьСерверныйТест(Тест.Метод, Тест.Синоним); КонецЦикла; - + КонецЦикла; - + Возврат ""; - + КонецФункции Функция СформироватьТестыАссертс() Экспорт - + ТаблицаТестов = ПолучитьТаблицуТестов(); МассивТестов = Новый Массив; - - Для Каждого Тест Из ТаблицаТестов Цикл + + Для Каждого Тест Из ТаблицаТестов Цикл МассивТестов.Добавить(Тест.Метод); КонецЦикла; - + Возврат МассивТестов; - + КонецФункции -Функция ПолучитьПараметр(Параметр) Экспорт +Функция ПолучитьПараметр(Параметр) Экспорт - Путь = ПутьКФайлуДанных(); + Путь = ПутьКФайлуДанных(); Возврат ПолучитьЗначениеИзФайла(Параметр, Путь); КонецФункции Функция ПолучитьДвоичные(Параметр) Экспорт - - Путь = ПутьКФайлуДанных(); + + Путь = ПутьКФайлуДанных(); ПараметрЛокальный = Параметр + "Local"; ЗначениеОсновной = ПолучитьЗначениеИзФайла(Параметр , Путь); ЗначениеЛокальный = ПолучитьЗначениеИзФайла(ПараметрЛокальный, Путь); - + ФайлЛокальный = Новый Файл(ЗначениеЛокальный); - + Если ФайлЛокальный.Существует() Тогда Значение = Новый ДвоичныеДанные(ЗначениеЛокальный); Иначе Значение = ЗначениеОсновной; КонецЕсли; - + Если ТипЗнч(Значение) = Тип("Строка") Тогда - Значение = ПолучитьФайлПути(Значение, ПараметрЛокальный); + Значение = ПолучитьФайлПути(Значение, ПараметрЛокальный); КонецЕсли; - + Возврат Значение; - + КонецФункции Функция ПолучитьФайлПути(Знач Путь, ПараметрЛокальный, Знач СохранятьЛокально = Истина) Экспорт - - Если СтрНайти(Путь, "http") > 0 + + Если СтрНайти(Путь, "http") > 0 Или СтрНайти(Путь, "www") > 0 Тогда - - ИВФ = ПолучитьИмяВременногоФайла(); + + ИВФ = ПолучитьИмяВременногоФайла(); КопироватьФайл(Путь, ИВФ); - Путь = ИВФ; + Путь = ИВФ; Двоичные = Новый ДвоичныеДанные(Путь); - + Если СохранятьЛокально Тогда ЗаписатьПараметр(ПараметрЛокальный, ИВФ); Иначе УдалитьФайлы(ИВФ); КонецЕсли; - + Иначе - + Двоичные = Новый ДвоичныеДанные(Путь); - + КонецЕсли; - + Возврат Двоичные; - + КонецФункции Процедура ПараметрВКоллекцию(Параметр, Коллекция) Экспорт Значение = ПолучитьПараметр(Параметр); Коллекция.Вставить(Параметр, Значение); - + КонецПроцедуры Процедура ДвоичныеВКоллекцию(Параметр, Коллекция) Экспорт Значение = ПолучитьДвоичные(Параметр); Коллекция.Вставить(Параметр, Значение); - + КонецПроцедуры Процедура ЗаписатьПараметр(Параметр, Значение) Экспорт - - Путь = ПутьКФайлуДанных(); + + Путь = ПутьКФайлуДанных(); ЗаписатьПараметрВФайл(Параметр, Значение, Путь); - + КонецПроцедуры Процедура ЗаписатьЛог(Знач Результат, Знач Метод, Знач Библиотека = "") Экспорт - + Шапка = Строка(OPI_Инструменты.ПолучитьТекущуюДату()) + " | " + Метод; - + Попытка Данные = OPI_Инструменты.JSONСтрокой(Результат); Исключение Данные = "Не JSON: " + Строка(Результат); КонецПопытки; - - Данные = " " + Данные; - + + Данные = " " + Данные; + Сообщить(Шапка); Сообщить(Символы.ПС); Сообщить(Данные); Сообщить(Символы.ПС); Сообщить("---------------------------------"); Сообщить(Символы.ПС); - + Если ЗначениеЗаполнено(Библиотека) Тогда ЗаписатьФайлЛога(Данные, Метод, Библиотека); КонецЕсли; - + КонецПроцедуры #КонецОбласти #Область СлужебныеПроцедурыИФункции -Функция ПолучитьЗначениеИзФайла(Параметр, Путь) - - Значения = OPI_Инструменты.ПрочитатьJSONФайл(Путь); +Функция ПолучитьЗначениеИзФайла(Параметр, Путь) + + Значения = OPI_Инструменты.ПрочитатьJSONФайл(Путь); Возврат ?(Значения.Свойство(Параметр), Значения[Параметр], ""); - + КонецФункции Функция ПутьКФайлуДанных() - - Путь = ""; + + Путь = ""; ВозможныеПути = Новый Массив; ВозможныеПути.Добавить("./data.json"); ВозможныеПути.Добавить("C:\GDrive\Мой диск\data.json"); ВозможныеПути.Добавить("D:\GD\Мой диск\data.json"); - + Для Каждого ВозможныйПуть Из ВозможныеПути Цикл - + ФайлРепозитория = Новый Файл(ВозможныйПуть); - + Если ФайлРепозитория.Существует() Тогда Путь = ВозможныйПуть; - КонецЕсли; - + КонецЕсли; + КонецЦикла; - + Возврат Путь; - + КонецФункции Функция ПолучитьОбщийМодуль(Знач Имя) - УстановитьБезопасныйРежим(Истина); - Модуль = Вычислить(Имя); - УстановитьБезопасныйРежим(Ложь); - Возврат Модуль; + УстановитьБезопасныйРежим(Истина); + Модуль = Вычислить(Имя); + УстановитьБезопасныйРежим(Ложь); + Возврат Модуль; КонецФункции Процедура НовыйТест(ТаблицаЗначений, Знач Метод, Знач Синоним, Знач Раздел) - - НовыйТест = ТаблицаЗначений.Добавить(); + + НовыйТест = ТаблицаЗначений.Добавить(); НовыйТест.Метод = Метод; НовыйТест.Синоним = Синоним; НовыйТест.Раздел = Раздел; - + КонецПроцедуры Процедура ЗаписатьПараметрВФайл(Знач Параметр, Знач Значение, Знач Путь) - + Значения = OPI_Инструменты.ПрочитатьJSONФайл(Путь); Значения.Вставить(Параметр, Значение); @@ -452,37 +452,37 @@ КонецПроцедуры Процедура ЗаписатьФайлЛога(Знач Данные, Знач Метод, Знач Библиотека) - + Попытка - + ПутьЛогов = "./docs/ru/results"; ПутьЛоговБиблиотеки = ПутьЛогов + "/" + Библиотека; - + КаталогЛогов = Новый Файл(ПутьЛогов); - + Если Не КаталогЛогов.Существует() Тогда СоздатьКаталог(ПутьЛогов); КонецЕсли; - + КаталогЛоговБиблиотеки = Новый Файл(ПутьЛоговБиблиотеки); - + Если Не КаталогЛоговБиблиотеки.Существует() Тогда СоздатьКаталог(ПутьЛоговБиблиотеки); КонецЕсли; - + ПутьКФайлу = ПутьЛоговБиблиотеки + "/" + Метод + ".log"; ФайлЛога = Новый Файл(ПутьКФайлу); - + Если Не ФайлЛога.Существует() Тогда ДокументЛога = Новый ТекстовыйДокумент; ДокументЛога.УстановитьТекст(Данные); ДокументЛога.Записать(ПутьКФайлу); КонецЕсли; - + Исключение - Сообщить("Не удалось записать файл лога!: " + ОписаниеОшибки()); + Сообщить("Не удалось записать файл лога!: " + ОписаниеОшибки()); КонецПопытки; - + КонецПроцедуры #КонецОбласти diff --git a/src/ru/OPI/src/CommonModules/OPI_ПреобразованиеТипов/Module.bsl b/src/ru/OPI/src/CommonModules/OPI_ПреобразованиеТипов/Module.bsl index 784aba6294..5662dfda66 100644 --- a/src/ru/OPI/src/CommonModules/OPI_ПреобразованиеТипов/Module.bsl +++ b/src/ru/OPI/src/CommonModules/OPI_ПреобразованиеТипов/Module.bsl @@ -1,4 +1,4 @@ -// OneScript: ./OInt/tools/Modules/OPI_ПреобразованиеТипов.os +// OneScript: ./OInt/tools/Modules/OPI_ПреобразованиеТипов.os // MIT License @@ -39,268 +39,268 @@ #Область СлужебныйПрограммныйИнтерфейс Процедура ПолучитьДвоичныеДанные(Значение) Экспорт - + Если Значение = Неопределено Тогда Возврат; КонецЕсли; - - Попытка - + + Попытка + Если ТипЗнч(Значение) = Тип("ДвоичныеДанные") Тогда Возврат; Иначе - + Файл = Новый Файл(Значение); - + Если Файл.Существует() Тогда Значение = Новый ДвоичныеДанные(Значение); - + ИначеЕсли СтрНайти(Значение, "//") Тогда - + Значение = OPI_Инструменты.Get(Значение); - + Иначе - + Значение = Base64Значение(Значение); - + КонецЕсли; - + КонецЕсли; - + Исключение ВызватьИсключение "Ошибка получения двоичных данных из параметра: " + ОписаниеОшибки(); КонецПопытки; - + КонецПроцедуры Процедура ПолучитьДвоичныеИлиПоток(Значение) Экспорт - + Если Значение = Неопределено Тогда Возврат; КонецЕсли; - + Если ТипЗнч(Значение) <> Тип("Строка") Тогда ПолучитьДвоичныеДанные(Значение); Возврат; КонецЕсли; - + Файл = Новый Файл(Значение); - + Если Файл.Существует() Тогда - Значение = Новый ФайловыйПоток(Значение, РежимОткрытияФайла.Открыть); + Значение = Новый ФайловыйПоток(Значение, РежимОткрытияФайла.Открыть); Иначе ПолучитьДвоичныеДанные(Значение); КонецЕсли; - + КонецПроцедуры Процедура ПолучитьКоллекцию(Значение) Экспорт - + Если Значение = Неопределено Тогда Возврат; КонецЕсли; - - Попытка - + + Попытка + ИсходноеЗначение = Значение; - + Если ЭтоКоллекция(Значение) Тогда Возврат; Иначе - + Если ТипЗнч(Значение) = Тип("ДвоичныеДанные") Тогда - Значение = ПолучитьСтрокуИзДвоичныхДанных(Значение); + Значение = ПолучитьСтрокуИзДвоичныхДанных(Значение); Иначе - Значение = OPI_Инструменты.ЧислоВСтроку(Значение); + Значение = OPI_Инструменты.ЧислоВСтроку(Значение); КонецЕсли; - + Файл = Новый Файл(Значение); ЧтениеJSON = Новый ЧтениеJSON; - + Если Файл.Существует() Тогда - + ЧтениеJSON.ОткрытьФайл(Значение); - + ИначеЕсли СтрНачинаетсяС(нРег(Значение), "http") Тогда - + ИВФ = ПолучитьИмяВременногоФайла(); КопироватьФайл(Значение, ИВФ); ЧтениеJSON.ОткрытьФайл(ИВФ); ЧтениеJSON.Прочитать(); - + УдалитьФайлы(ИВФ); - + Иначе - + ЧтениеJSON.УстановитьСтроку(СокрЛП(Значение)); - + КонецЕсли; - + Значение = ПрочитатьJSON(ЧтениеJSON, Истина, Неопределено, ФорматДатыJSON.ISO); ЧтениеJSON.Закрыть(); - + Если (Не ЭтоКоллекция(Значение)) Или Не ЗначениеЗаполнено(Значение) Тогда - + Значение = ИсходноеЗначение; ПолучитьМассив(Значение); - + КонецЕсли; - + КонецЕсли; - + Исключение - + Значение = ИсходноеЗначение; - ПолучитьМассив(Значение); - + ПолучитьМассив(Значение); + КонецПопытки; - + КонецПроцедуры Процедура ПолучитьМассив(Значение) Экспорт - + Если ТипЗнч(Значение) = Тип("Массив") Тогда Возврат; КонецЕсли; - - Если ТипЗнч(Значение) = Тип("Строка") + + Если ТипЗнч(Значение) = Тип("Строка") И СтрНачинаетсяС(Значение, "[") И СтрЗаканчиваетсяНа(Значение, "]") Тогда - + ЗапятаяВКавычках = "','"; - + Значение = СтрЗаменить(Значение, "['" , ""); Значение = СтрЗаменить(Значение, "']" , ""); Значение = СтрЗаменить(Значение, "', '" , ЗапятаяВКавычках); Значение = СтрЗаменить(Значение, "' , '", ЗапятаяВКавычках); Значение = СтрЗаменить(Значение, "' ,'" , ЗапятаяВКавычках); - + Значение = СтрРазделить(Значение, ЗапятаяВКавычках, Ложь); - - Для Н = 0 По Значение.ВГраница() Цикл + + Для Н = 0 По Значение.ВГраница() Цикл Значение[Н] = СокрЛП(Значение[Н]); КонецЦикла; - + Иначе - + Если ТипЗнч(Значение) = Тип("Число") Тогда - Значение = OPI_Инструменты.ЧислоВСтроку(Значение); + Значение = OPI_Инструменты.ЧислоВСтроку(Значение); КонецЕсли; - + OPI_Инструменты.ЗначениеВМассив(Значение); - + КонецЕсли; - + КонецПроцедуры Процедура ПолучитьБулево(Значение) Экспорт - + Если Значение = Неопределено Тогда Возврат; КонецЕсли; - - Попытка - + + Попытка + Если ТипЗнч(Значение) = Тип("Булево") Тогда Возврат; Иначе - Значение = Булево(Значение); + Значение = Булево(Значение); КонецЕсли; - + Исключение ВызватьИсключение "Ошибка получения данных булево из параметра"; КонецПопытки; - + КонецПроцедуры Процедура ПолучитьСтроку(Значение, Знач ИзИсточника = Ложь) Экспорт - + Если Значение = Неопределено Тогда Возврат; КонецЕсли; - - Попытка - + + Попытка + Если ЭтоСимвольное(Значение) Тогда - + Если Не ИзИсточника Тогда Значение = OPI_Инструменты.ЧислоВСтроку(Значение); - Возврат; + Возврат; КонецЕсли; - - Значение = OPI_Инструменты.ЧислоВСтроку(Значение); + + Значение = OPI_Инструменты.ЧислоВСтроку(Значение); Файл = Новый Файл(Значение); - + Если Файл.Существует() Тогда - + ЧтениеТекста = Новый ЧтениеТекста(Значение); Значение = ЧтениеТекста.Прочитать(); ЧтениеТекста.Закрыть(); - + ИначеЕсли СтрНачинаетсяС(нРег(Значение), "http") Тогда - + ИВФ = ПолучитьИмяВременногоФайла(); КопироватьФайл(Значение, ИВФ); - + ЧтениеТекста = Новый ЧтениеТекста(ИВФ); Значение = ЧтениеТекста.Прочитать(); ЧтениеТекста.Закрыть(); - + УдалитьФайлы(ИВФ); - + Иначе - + Возврат; - + КонецЕсли; - + ИначеЕсли ТипЗнч(Значение) = Тип("ДвоичныеДанные") Тогда - + Значение = ПолучитьСтрокуИзДвоичныхДанных(Значение); - + ИначеЕсли ЭтоКоллекция(Значение) Тогда - - Значение = OPI_Инструменты.JSONСтрокой(Значение); - + + Значение = OPI_Инструменты.JSONСтрокой(Значение); + Иначе Возврат; КонецЕсли; - + Исключение Значение = Строка(Значение); Возврат; КонецПопытки; - + КонецПроцедуры Процедура ПолучитьДату(Значение) Экспорт - + Если Значение = Неопределено Тогда Возврат; КонецЕсли; - + Дата = "Дата"; - - Попытка - + + Попытка + Если ТипЗнч(Значение) = Тип(Дата) Тогда Возврат; - Иначе - Значение = XMLЗначение(Тип(Дата), Значение); + Иначе + Значение = XMLЗначение(Тип(Дата), Значение); КонецЕсли; - + Исключение - ООД = Новый ОписаниеТипов(Дата); + ООД = Новый ОписаниеТипов(Дата); Значение = ООД.ПривестиЗначение(Значение); КонецПопытки; - + КонецПроцедуры Процедура ПолучитьЧисло(Значение) Экспорт - + ОписаниеТипа = Новый ОписаниеТипов("Число"); - Значение = ОписаниеТипа.ПривестиЗначение(Значение); - + Значение = ОписаниеТипа.ПривестиЗначение(Значение); + КонецПроцедуры #КонецОбласти @@ -308,19 +308,19 @@ #Область СлужебныеПроцедурыИФункции Функция ЭтоКоллекция(Знач Значение) - - Возврат ТипЗнч(Значение) = Тип("Массив") + + Возврат ТипЗнч(Значение) = Тип("Массив") Или ТипЗнч(Значение) = Тип("Структура") Или ТипЗнч(Значение) = Тип("Соответствие"); - -КонецФункции + +КонецФункции Функция ЭтоСимвольное(Знач Значение) - - Возврат ТипЗнч(Значение) = Тип("Строка") - Или ТипЗнч(Значение) = Тип("Число") - Или ТипЗнч(Значение) = Тип("Дата"); - -КонецФункции -#КонецОбласти \ No newline at end of file + Возврат ТипЗнч(Значение) = Тип("Строка") + Или ТипЗнч(Значение) = Тип("Число") + Или ТипЗнч(Значение) = Тип("Дата"); + +КонецФункции + +#КонецОбласти diff --git a/src/ru/OPI/src/CommonModules/OPI_Тесты/Module.bsl b/src/ru/OPI/src/CommonModules/OPI_Тесты/Module.bsl index 1f202279fb..2f4b795ee4 100644 --- a/src/ru/OPI/src/CommonModules/OPI_Тесты/Module.bsl +++ b/src/ru/OPI/src/CommonModules/OPI_Тесты/Module.bsl @@ -1,4 +1,4 @@ -// OneScript: ./OInt/tests/Modules/internal/OPI_Тесты.os +// OneScript: ./OInt/tests/Modules/internal/OPI_Тесты.os // MIT License @@ -67,22 +67,22 @@ #Область Telegram Процедура Телеграм_ПолучитьИнформациюБота() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token", ПараметрыТеста); - + Telegram_ПолучитьИнформациюБота(ПараметрыТеста); - + КонецПроцедуры Процедура Телеграм_ПолучитьОбновления() Экспорт ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token", ПараметрыТеста); - + Telegram_УдалитьWebhook(ПараметрыТеста); Telegram_ПолучитьОбновления(ПараметрыТеста); - + КонецПроцедуры Процедура Телеграм_УстановитьWebhook() Экспорт @@ -93,7 +93,7 @@ Telegram_УстановитьWebhook(ПараметрыТеста); Telegram_УдалитьWebhook(ПараметрыТеста); - + КонецПроцедуры Процедура Телеграм_ОтправитьТекстовоеСообщение() Экспорт @@ -103,9 +103,9 @@ OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChatID" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelID", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("String" , ПараметрыТеста); - + Telegram_ОтправитьТекстовоеСообщение(ПараметрыТеста); - + КонецПроцедуры Процедура Телеграм_ОтправитьКартинку() Экспорт @@ -116,7 +116,7 @@ OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelID", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("String" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture" , ПараметрыТеста); - + Telegram_ОтправитьКартинку(ПараметрыТеста); Telegram_СкачатьФайл(ПараметрыТеста); @@ -130,7 +130,7 @@ OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelID", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("String" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Video" , ПараметрыТеста); - + Telegram_ОтправитьВидео(ПараметрыТеста); Telegram_СкачатьФайл(ПараметрыТеста); @@ -144,7 +144,7 @@ OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelID", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("String" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Audio" , ПараметрыТеста); - + Telegram_ОтправитьАудио(ПараметрыТеста); Telegram_СкачатьФайл(ПараметрыТеста); @@ -158,7 +158,7 @@ OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelID", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("String" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Document" , ПараметрыТеста); - + Telegram_ОтправитьДокумент(ПараметрыТеста); КонецПроцедуры @@ -171,13 +171,13 @@ OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelID", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("String" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("GIF" , ПараметрыТеста); - + Telegram_ОтправитьГифку(ПараметрыТеста); КонецПроцедуры Процедура Телеграм_ОтправитьМедиагруппу() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChatID" , ПараметрыТеста); @@ -186,26 +186,26 @@ OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Video" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Document" , ПараметрыТеста); - + Telegram_ОтправитьМеидагруппу(ПараметрыТеста); КонецПроцедуры Процедура Телеграм_ОтправитьМестоположение() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChatID" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelID", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Long" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Lat" , ПараметрыТеста); - + Telegram_ОтправитьМестоположение(ПараметрыТеста); КонецПроцедуры Процедура Телеграм_ОтправитьКонтакт() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChatID" , ПараметрыТеста); @@ -219,18 +219,18 @@ КонецПроцедуры Процедура Телеграм_ОтправитьОпрос() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChatID" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelID", ПараметрыТеста); - + Telegram_ОтправитьОпрос(ПараметрыТеста); КонецПроцедуры Процедура Телеграм_ПереслатьСообщение() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChatID" , ПараметрыТеста); @@ -238,38 +238,38 @@ OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelMessageID", ПараметрыТеста); Telegram_ПереслатьСообщение(ПараметрыТеста); - + КонецПроцедуры Процедура Телеграм_БанРазбан() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChatID" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelID" , ПараметрыТеста); - + Telegram_Бан(ПараметрыТеста); Telegram_Разбан(ПараметрыТеста); - + КонецПроцедуры Процедура Телеграм_СоздатьСсылкуПриглашение() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelID", ПараметрыТеста); - + Telegram_СоздатьСсылкуПриглашение(ПараметрыТеста); КонецПроцедуры Процедура Телеграм_ЗакрепитьОткрепитьСообщение() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelID" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelMessageID", ПараметрыТеста); - + Telegram_ЗакрепитьСообщение(ПараметрыТеста); Telegram_ОткрепитьСообщение(ПараметрыТеста); Telegram_УдалитьСообщение(ПараметрыТеста); @@ -277,32 +277,32 @@ КонецПроцедуры Процедура Телеграм_ПолучитьЧислоУчастников() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ChannelID", ПараметрыТеста); - + Telegram_ПолучитьЧислоУчастников(ПараметрыТеста); КонецПроцедуры Процедура Телеграм_ПолучитьСписокАватаровФорума() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token", ПараметрыТеста); - + Telegram_ПолучитьСписокАватаровФорума(ПараметрыТеста); - + КонецПроцедуры Процедура Телеграм_СоздатьУдалитьТемуФорума() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ForumID", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("String" , ПараметрыТеста); - + Telegram_СоздатьТемуФорума(ПараметрыТеста); Telegram_ИзменитьТемуФорума(ПараметрыТеста); Telegram_ЗакрытьТемуФорума(ПараметрыТеста); @@ -313,7 +313,7 @@ КонецПроцедуры Процедура Телеграм_СкрытьПоказатьГлавнуюТему() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ForumID", ПараметрыТеста); @@ -324,13 +324,13 @@ КонецПроцедуры Процедура Телеграм_ИзменитьИмяГлавнойТемы() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Telegram_ForumID", ПараметрыТеста); Telegram_ИзменитьИмяГлавнойТемыФорума(ПараметрыТеста); - + КонецПроцедуры #КонецОбласти @@ -338,251 +338,251 @@ #Область VK Процедура ВК_СоздатьСсылкуТокена() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("VK_AppID", ПараметрыТеста); - VK_СоздатьСсылкуПолученияТокена(ПараметрыТеста); - + VK_СоздатьСсылкуПолученияТокена(ПараметрыТеста); + КонецПроцедуры Процедура ВК_СоздатьУдалитьПост() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture2", ПараметрыТеста); - + VK_СоздатьПост(ПараметрыТеста); VK_УдалитьПост(ПараметрыТеста); КонецПроцедуры Процедура ВК_СоздатьСоставнойПост() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Video" , ПараметрыТеста); - + VK_СоздатьСоставнойПост(ПараметрыТеста); - + КонецПроцедуры Процедура ВК_СоздатьОпрос() Экспорт - + VK_СоздатьОпрос(); - + КонецПроцедуры Процедура ВК_СохранитьУдалитьКартинку() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture" , ПараметрыТеста); - + VK_СоздатьАльбом(ПараметрыТеста); VK_СохранитьКартинкуВАльбом(ПараметрыТеста); VK_УдалитьКартинку(ПараметрыТеста); VK_УдалитьАльбом(ПараметрыТеста); - + КонецПроцедуры Процедура ВК_СоздатьИсторию() Экспорт - + ПараметрыТеста = Новый Соответствие; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture" , ПараметрыТеста); - + VK_СоздатьИсторию(ПараметрыТеста); - + КонецПроцедуры Процедура ВК_МетодыОбсуждений() Экспорт - + ПараметрыТеста = Новый Структура; Параметры = ПолучитьПараметрыВК(); - + VK_СоздатьОбсуждение(ПараметрыТеста); VK_ЗакрытьОбсуждение(ПараметрыТеста); VK_ОткрытьОбсуждение(ПараметрыТеста); - VK_НаписатьВОбсуждение(ПараметрыТеста); - + VK_НаписатьВОбсуждение(ПараметрыТеста); + OPI_VK.ЗакрытьОбсуждение(ПараметрыТеста["VK_ConvID"], Истина, Параметры); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ВК_ЛайкРепостКоммент() Экспорт - + ПараметрыТеста = Новый Структура(); Параметры = ПолучитьПараметрыВК(); Текст = "Пост из автотеста"; - - Результат = OPI_VK.СоздатьПост(Текст, Новый Массив, , , Параметры); - ИДПоста = Результат["response"]["post_id"]; - + + Результат = OPI_VK.СоздатьПост(Текст, Новый Массив, , , Параметры); + ИДПоста = Результат["response"]["post_id"]; + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_PostID", ИДПоста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("VK_PostID", ПараметрыТеста); - - VK_ПоставитьЛайк(ПараметрыТеста); - VK_СделатьРепост(ПараметрыТеста); - VK_НаписатьКомментарий(ПараметрыТеста); - - OPI_VK.УдалитьПост(ИДПоста, Параметры); + + VK_ПоставитьЛайк(ПараметрыТеста); + VK_СделатьРепост(ПараметрыТеста); + VK_НаписатьКомментарий(ПараметрыТеста); + + OPI_VK.УдалитьПост(ИДПоста , Параметры); OPI_VK.УдалитьПост(ПараметрыТеста["Repost"], Параметры); - + OPI_Инструменты.Пауза(5); КонецПроцедуры Процедура ВК_ПолучитьСтатистику() Экспорт - + ПараметрыТеста = Новый Структура(); - + VK_ПолучитьСтатистику(ПараметрыТеста); - + OPI_Инструменты.Пауза(5); КонецПроцедуры Процедура ВК_ПолучитьСтатистикуПостов() Экспорт - + ПараметрыТеста = Новый Структура(); - + VK_ПолучитьСтатистикуПостов(ПараметрыТеста); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ВК_СоздатьРекламнуюКампанию() Экспорт - + Параметры = ПолучитьПараметрыВК(); Текст = "Пост из автотеста"; - - Результат = OPI_VK.СоздатьПост(Текст, Новый Массив, , , Параметры); - ИДПоста = Результат["response"]["post_id"]; - + + Результат = OPI_VK.СоздатьПост(Текст, Новый Массив, , , Параметры); + ИДПоста = Результат["response"]["post_id"]; + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_PostID", ИДПоста); - + ПараметрыТеста = Новый Структура(); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("VK_AdsCabinetID", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("VK_PostID" , ПараметрыТеста); - + VK_СоздатьРекламнуюКампанию(ПараметрыТеста); VK_СоздатьРекламноеОбъявление(ПараметрыТеста); VK_ПриостановитьРекламноеОбъявление(ПараметрыТеста); - + OPI_VK.УдалитьПост(ИДПоста, Параметры); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ВК_ОтправитьСообщение() Экспорт - + ПараметрыТеста = Новый Структура; - - OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("VK_UserID", ПараметрыТеста); + + OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("VK_UserID" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("VK_CommunityToken", ПараметрыТеста); VK_СформироватьКлавиатуру(ПараметрыТеста); VK_НаписатьСообщение(ПараметрыТеста); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ВК_ПолучитьКатегорииТоваров() Экспорт - + ПараметрыТеста = Новый Структура; - + VK_ПолучитьСписокКатегорийТоваров(ПараметрыТеста); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ВК_СоздатьТоварПодборку() Экспорт - + ПараметрыТеста = Новый Структура; - OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture", ПараметрыТеста); + OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture2", ПараметрыТеста); - + VK_СоздатьПодборкуТоваров(ПараметрыТеста); VK_ИзменитьПодборкуТоваров(ПараметрыТеста); VK_ДобавитьТовар(ПараметрыТеста); VK_ИзменитьТовар(ПараметрыТеста); - VK_ДобавитьТоварВПодборку(ПараметрыТеста); + VK_ДобавитьТоварВПодборку(ПараметрыТеста); VK_УдалитьТоварИзПодборки(ПараметрыТеста); VK_УдалитьТовар(ПараметрыТеста); VK_УдалитьПодборку(ПараметрыТеста); OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ВК_СоздатьТоварСоСвойствами() Экспорт - + Параметры = ПолучитьПараметрыВК(); - + ПараметрыТеста = Новый Структура; - OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture", ПараметрыТеста); + OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture2", ПараметрыТеста); - + VK_СоздатьСвойствоТовара(ПараметрыТеста); - VK_ИзменитьСвойствоТовара(ПараметрыТеста); - VK_ДобавитьВариантСвойстваТовара(ПараметрыТеста); - VK_ИзменитьВариантСвойстваТовара(ПараметрыТеста); + VK_ИзменитьСвойствоТовара(ПараметрыТеста); + VK_ДобавитьВариантСвойстваТовара(ПараметрыТеста); + VK_ИзменитьВариантСвойстваТовара(ПараметрыТеста); VK_СоздатьТоварСоСвойством(ПараметрыТеста); VK_ПолучитьТоварыПоИД(ПараметрыТеста); VK_СгруппироватьТовары(ПараметрыТеста); - + OPI_VK.УдалитьТовар(ПараметрыТеста["VK_MarketItemID2"], Параметры); OPI_VK.УдалитьТовар(ПараметрыТеста["VK_MarketItemID3"], Параметры); - + VK_УдалитьВариантСвойстваТовара(ПараметрыТеста); VK_УдалитьСвойствоТовара(ПараметрыТеста); - + КонецПроцедуры Процедура ВК_ПолучитьСписокТоваров() Экспорт - + ПараметрыТеста = Новый Структура; - + VK_ПолучитьСписокТоваров(ПараметрыТеста); - + КонецПроцедуры Процедура ВК_ПолучитьСписокПодборок() Экспорт - + ПараметрыТеста = Новый Структура; - + VK_ПолучитьСписокПодборок(ПараметрыТеста); - + КонецПроцедуры Процедура ВК_ПолучитьСписокСвойств() Экспорт - + ПараметрыТеста = Новый Структура; - + VK_ПолучитьСписокСвойств(ПараметрыТеста); КонецПроцедуры Процедура ВК_ПолучитьСписокЗаказов() Экспорт - + ПараметрыТеста = Новый Структура; - + VK_ПолучитьСписокЗаказов(ПараметрыТеста); - + КонецПроцедуры Процедура ВК_ЗагрузитьВидео() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Video", ПараметрыТеста); - + VK_ЗагрузитьВидеоНаСервер(ПараметрыТеста); - + КонецПроцедуры #КонецОбласти @@ -590,48 +590,48 @@ #Область YandexDisk Процедура ЯДиск_ПолучитьИнформациюОДиске() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("YandexDisk_Token", ПараметрыТеста); - + YandexDisk_ПолучитьИнформациюОДиске(ПараметрыТеста); - + КонецПроцедуры Процедура ЯДиск_СоздатьПапку() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("YandexDisk_Token", ПараметрыТеста); - + YandexDisk_СоздатьПапку(ПараметрыТеста); - + КонецПроцедуры Процедура ЯДиск_ЗагрузитьПоАдресуПолучитьОбъект() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("YandexDisk_Token"); Путь = "/" + Строка(Новый УникальныйИдентификатор) + ".png"; URL = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/Media/logo.png"; OPI_YandexDisk.ЗагрузитьФайлПоURL(Токен, Путь, URL); OPI_Инструменты.Пауза(5); - + Результат = OPI_YandexDisk.ПолучитьОбъект(Токен, Путь); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьОбъект"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["type"]).Равно("file"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["path"]).Равно("disk:" + Путь); OPI_YandexDisk.УдалитьОбъект(Токен, Путь, Ложь); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ЯДиск_ЗагрузитьУдалитьФайл() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("YandexDisk_Token"); Путь = "/" + Строка(Новый УникальныйИдентификатор) + ".png"; Картинка = OPI_ПолучениеДанныхТестов.ПолучитьДвоичные("Picture"); @@ -639,39 +639,39 @@ Картинка.Записать(ИВФ); Результат = OPI_YandexDisk.ЗагрузитьФайл(Токен, Путь, Картинка, Истина); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗагрузитьФайл"); - + Проверка_Пусто(Результат); OPI_Инструменты.Пауза(5); - + Результат = OPI_YandexDisk.УдалитьОбъект(Токен, Путь, Ложь); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьОбъект"); - + Проверка_Пусто(Результат); - + Результат = OPI_YandexDisk.ЗагрузитьФайл(Токен, Путь, ИВФ, Истина); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗагрузитьФайл"); - + Проверка_Пусто(Результат); OPI_Инструменты.Пауза(5); - - Результат = OPI_YandexDisk.УдалитьОбъект(Токен, Путь, Ложь); - + + Результат = OPI_YandexDisk.УдалитьОбъект(Токен, Путь, Ложь); + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьОбъект"); - - Проверка_Пусто(Результат); + + Проверка_Пусто(Результат); УдалитьФайлы(ИВФ); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ЯДиск_СоздатьКопиюОбъекта() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("YandexDisk_Token"); ПутьОригинала = "/" + Строка(Новый УникальныйИдентификатор) + ".png"; ПутьКопии = "/" + Строка(Новый УникальныйИдентификатор) + ".png"; @@ -680,45 +680,45 @@ OPI_YandexDisk.ЗагрузитьФайлПоURL(Токен, ПутьОригинала, URL); OPI_Инструменты.Пауза(25); - + Результат = OPI_YandexDisk.СоздатьКопиюОбъекта(Токен, ПутьОригинала, ПутьКопии, Истина); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьКопиюОбъекта"); - + OPI_Инструменты.Пауза(5); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["type"]).Равно("file"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["path"]).Равно("disk:" + ПутьКопии); OPI_YandexDisk.УдалитьОбъект(Токен, ПутьОригинала, Ложь); - OPI_YandexDisk.УдалитьОбъект(Токен, ПутьКопии, Ложь); - + OPI_YandexDisk.УдалитьОбъект(Токен, ПутьКопии , Ложь); + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ЯДиск_ПолучитьСсылкуНаСкачивание() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("YandexDisk_Token"); Путь = "/" + Строка(Новый УникальныйИдентификатор) + ".png"; URL = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/Media/logo.png"; OPI_YandexDisk.ЗагрузитьФайлПоURL(Токен, Путь, URL); OPI_Инструменты.Пауза(5); - + Результат = OPI_YandexDisk.ПолучитьСсылкуДляСкачивания(Токен, Путь); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСсылкуДляСкачивания"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["method"]).Равно("GET"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["href"]).ИмеетТип("Строка").Заполнено(); - + URL = Результат["href"]; - + Результат = OPI_YandexDisk.СкачатьФайл(Токен, Путь); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("ДвоичныеДанные").Заполнено(); OPI_YandexDisk.УдалитьОбъект(Токен, Путь, Ложь); @@ -726,26 +726,26 @@ КонецПроцедуры Процедура ЯДиск_ПолучитьСписокФайлов() Экспорт - - Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("YandexDisk_Token"); + + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("YandexDisk_Token"); Количество = 2; Отступ = 1; - + Результат = OPI_YandexDisk.ПолучитьСписокФайлов(Токен, Количество, Отступ, "image"); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокФайлов"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["limit"]).Равно(Количество); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["offset"]).Равно(Отступ); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["items"]).ИмеетТип("Массив"); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ЯДиск_ПереместитьОбъект() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("YandexDisk_Token"); ПутьОригинала = "/" + Строка(Новый УникальныйИдентификатор) + ".png"; ПутьКопии = "/" + Строка(Новый УникальныйИдентификатор) + ".png"; @@ -753,104 +753,104 @@ + "OpenIntegrations/main/Media/logo.png"; Результат = OPI_YandexDisk.ЗагрузитьФайлПоURL(Токен, ПутьОригинала, URL); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗагрузитьФайлПоURL"); - + OPI_Инструменты.Пауза(15); - + Результат = OPI_YandexDisk.ПереместитьОбъект(Токен, ПутьОригинала, ПутьКопии, Истина); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереместитьОбъект"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["type"]).Равно("file"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["path"]).Равно("disk:" + ПутьКопии); OPI_YandexDisk.УдалитьОбъект(Токен, ПутьОригинала, Ложь); - OPI_YandexDisk.УдалитьОбъект(Токен, ПутьКопии, Ложь); - + OPI_YandexDisk.УдалитьОбъект(Токен, ПутьКопии , Ложь); + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ЯДиск_ДействияПубличныхОбъектов() Экспорт - + PUrl = "public_url"; Соответствие = "Соответствие"; Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("YandexDisk_Token"); Путь = "/" + Строка(Новый УникальныйИдентификатор) + ".png"; URL = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/Media/logo.png"; - + OPI_YandexDisk.ЗагрузитьФайлПоURL(Токен, Путь, URL); OPI_Инструменты.Пауза(5); - + МассивРезультатов = Новый Массив; - - МассивРезультатов.Добавить(OPI_YandexDisk.ОпубликоватьОбъект(Токен, Путь)); + + МассивРезультатов.Добавить(OPI_YandexDisk.ОпубликоватьОбъект(Токен, Путь)); ПубличныйURL = МассивРезультатов[0][PUrl]; - + Результат = OPI_YandexDisk.ПолучитьСсылкуСкачиванияПубличногоОбъекта(Токен, ПубличныйURL); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСсылкуСкачиванияПубличногоОбъекта"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип(Соответствие).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["method"]).Равно("GET"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["href"]).ИмеетТип("Строка").Заполнено(); - + Результат = OPI_YandexDisk.ПолучитьПубличныйОбъект(Токен, ПубличныйURL); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьПубличныйОбъект"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип(Соответствие).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["type"]).Равно("file"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["path"]).Равно("/"); - + МассивРезультатов.Добавить(OPI_YandexDisk.СохранитьПубличныйОбъектНаДиск(Токен, ПубличныйURL)); - + МассивРезультатов.Добавить(OPI_YandexDisk.ОтменитьПубликациюОбъекта(Токен, Путь)); - + Счетчик = 0; Для Каждого Результат Из МассивРезультатов Цикл - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "Изменение публикации"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип(Соответствие).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["type"]).Равно("file"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["path"]).Заполнено(); - - Если Счетчик = 0 Тогда + + Если Счетчик = 0 Тогда OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[PUrl]).ИмеетТип("Строка").Заполнено(); Иначе OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[PUrl]).ИмеетТип("Неопределено"); КонецЕсли; - + Счетчик = Счетчик + 1; - + КонецЦикла; - + OPI_YandexDisk.УдалитьОбъект(Токен, Путь, Ложь); - + OPI_Инструменты.Пауза(5); КонецПроцедуры Процедура ЯДиск_ПолучитьСписокОпубликованных() Экспорт - - Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("YandexDisk_Token"); + + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("YandexDisk_Token"); Количество = 2; Отступ = 1; - + Результат = OPI_YandexDisk.ПолучитьСписокОпубликованныхОбъектов(Токен, Количество, Отступ); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокОпубликованныхОбъектов"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["limit"]).Равно(Количество); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["offset"]).Равно(Отступ); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["items"]).ИмеетТип("Массив"); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры #КонецОбласти @@ -858,12 +858,12 @@ #Область Viber Процедура Вайбер_ПолучитьИнформациюОКанале() Экспорт - - Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelToken"); + + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelToken"); Результат = OPI_Viber.ПолучитьИнформациюОКанале(Токен); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИнформациюОКанале"); - + Проверка_ВайберОк(Результат); OPI_Инструменты.Пауза(5); @@ -871,13 +871,13 @@ КонецПроцедуры Процедура Вайбер_ПолучитьДанныеПользователя() Экспорт - - Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelToken"); + + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelToken"); Пользователь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelAdminID"); Результат = OPI_Viber.ПолучитьДанныеПользователя(Токен, Пользователь); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьДанныеПользователя"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["chat_hostname"]).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["status_message"]).Заполнено(); OPI_Инструменты.Пауза(5); @@ -885,51 +885,51 @@ КонецПроцедуры Процедура Вайбер_ПолучитьОнлайнПользователей() Экспорт - - Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelToken"); + + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelToken"); Пользователь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_UserID"); Результат = OPI_Viber.ПолучитьОнлайнПользователей(Токен, Пользователь); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьОнлайнПользователей"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["users"]).ИмеетТип("Массив"); Проверка_ВайберОк(Результат); - + OPI_Инструменты.Пауза(5); КонецПроцедуры Процедура Вайбер_ОтправитьТекстовоеСообщение() Экспорт - + Текст = "Тестовое сообщение"; ТокенКанал = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelToken"); - ТокенБота = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_Token"); + ТокенБота = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_Token"); Пользователь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_UserID"); Администратор = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelAdminID"); - + МассивКнопок = Новый Массив; МассивКнопок.Добавить("Кнопка 1"); МассивКнопок.Добавить("Кнопка 2"); МассивКнопок.Добавить("Кнопка 3"); - + Клавиатура = OPI_Viber.СформироватьКлавиатуруИзМассиваКнопок(МассивКнопок); - + Результат = OPI_Viber.ОтправитьТекстовоеСообщение(ТокенБота, Текст, Пользователь, Ложь, Клавиатура); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьТекстовоеСообщение"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message_token"]).Заполнено(); Проверка_ВайберОк(Результат); - + Результат = OPI_Viber.ОтправитьТекстовоеСообщение(ТокенКанал, Текст, Администратор, Истина, Клавиатура); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьТекстовоеСообщение"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message_token"]).Заполнено(); Проверка_ВайберОк(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Вайбер_ОтправитьКартинку() Экспорт @@ -937,79 +937,79 @@ Текст = "Тестовое сообщение"; Картинка = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Picture"); ТокенКанал = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelToken"); - ТокенБота = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_Token"); + ТокенБота = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_Token"); Пользователь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_UserID"); Администратор = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelAdminID"); - + Результат = OPI_Viber.ОтправитьКартинку(ТокенБота, Картинка, Пользователь, Ложь, Текст); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьКартинку"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message_token"]).Заполнено(); Проверка_ВайберОк(Результат); - + Результат = OPI_Viber.ОтправитьКартинку(ТокенКанал, Картинка, Администратор, Истина, Текст); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьКартинку"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message_token"]).Заполнено(); Проверка_ВайберОк(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Вайбер_ОтправитьФайл() Экспорт - + Документ = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Document"); ТокенКанал = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelToken"); - ТокенБота = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_Token"); + ТокенБота = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_Token"); Пользователь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_UserID"); Администратор = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelAdminID"); - + Результат = OPI_Viber.ОтправитьФайл(ТокенБота, Документ, Пользователь, Ложь, "docx"); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьФайл"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message_token"]).Заполнено(); Проверка_ВайберОк(Результат); - + Результат = OPI_Viber.ОтправитьФайл(ТокенКанал, Документ, Администратор, Истина, "docx"); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьФайл"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message_token"]).Заполнено(); Проверка_ВайберОк(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Вайбер_ОтправитьКонтакт() Экспорт - + Имя = "Петр Петров"; Телефон = "+123456789"; ТокенКанал = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelToken"); - ТокенБота = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_Token"); + ТокенБота = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_Token"); Пользователь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_UserID"); Администратор = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelAdminID"); - + Результат = OPI_Viber.ОтправитьКонтакт(ТокенБота, Имя, Телефон, Пользователь, Ложь); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьКонтакт"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message_token"]).Заполнено(); Проверка_ВайберОк(Результат); - + Результат = OPI_Viber.ОтправитьКонтакт(ТокенКанал, Имя, Телефон, Администратор, Истина); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьКонтакт"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message_token"]).Заполнено(); Проверка_ВайберОк(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Вайбер_ОтправитьЛокацию() Экспорт @@ -1017,52 +1017,52 @@ Широта = "48.87373649724122"; Долгота = "2.2954639195323967"; ТокенКанал = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelToken"); - ТокенБота = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_Token"); + ТокенБота = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_Token"); Пользователь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_UserID"); Администратор = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelAdminID"); - + Результат = OPI_Viber.ОтправитьЛокацию(ТокенБота, Широта, Долгота, Пользователь, Ложь); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьЛокацию"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message_token"]).Заполнено(); Проверка_ВайберОк(Результат); - + Результат = OPI_Viber.ОтправитьЛокацию(ТокенКанал, Широта, Долгота, Администратор, Истина); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьЛокацию"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message_token"]).Заполнено(); Проверка_ВайберОк(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Вайбер_ОтправитьСсылку() Экспорт URL = "https://github.com/Bayselonarrend/OpenIntegrations"; ТокенКанал = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelToken"); - ТокенБота = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_Token"); + ТокенБота = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_Token"); Пользователь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_UserID"); Администратор = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Viber_ChannelAdminID"); - + Результат = OPI_Viber.ОтправитьСсылку(ТокенБота, URL, Пользователь, Ложь); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьСсылку"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message_token"]).Заполнено(); Проверка_ВайберОк(Результат); - + Результат = OPI_Viber.ОтправитьСсылку(ТокенКанал, URL, Администратор, Истина); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьСсылку"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message_token"]).Заполнено(); Проверка_ВайберОк(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры #КонецОбласти @@ -1070,53 +1070,53 @@ #Область GoogleWorkspace Процедура ГВ_ПолучитьСсылкуАвторизации() Экспорт - - ClientID = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_ClientID"); + + ClientID = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_ClientID"); Результат = OPI_GoogleWorkspace.СформироватьСсылкуПолученияКода(ClientID); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат) - .ИмеетТип("Строка") + .ИмеетТип("Строка") .Заполнено(); - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Google_Link", Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ГВ_ПолучитьТокен() Экспорт - + ClientID = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_ClientID"); ClientSecret = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_ClientSecret"); Code = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Code"); - + Результат = OPI_GoogleWorkspace.ПолучитьТокенПоКоду(ClientID, ClientSecret, Code); - + Если ЗначениеЗаполнено(Результат["access_token"]) И ЗначениеЗаполнено(Результат["refresh_token"]) Тогда - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Google_Token" , Результат["access_token"]); OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Google_Refresh", Результат["refresh_token"]); - + КонецЕсли; - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ГВ_ОбновитьТокен() Экспорт - + ClientID = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_ClientID"); ClientSecret = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_ClientSecret"); RefreshToken = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Refresh"); - + Результат = OPI_GoogleWorkspace.ОбновитьТокен(ClientID, ClientSecret, RefreshToken); - - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие"); + + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["access_token"]).Заполнено(); - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Google_Token", Результат["access_token"]); - + OPI_Инструменты.Пауза(5); КонецПроцедуры @@ -1126,22 +1126,22 @@ #Область GoogleCalendar Процедура ГК_ПолучитьСписокКалендарей() Экспорт - - Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); + + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); Результат = OPI_GoogleCalendar.ПолучитьСписокКалендарей(Токен); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокКалендарей"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат) .ИмеетТип("Массив"); OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ГК_СоздатьУдалитьКалендарь() Экспорт - - Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); + + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); Наименование = "Тестовый календарь"; Описание = "Тестовое описание"; НаименованиеИзмененное = Наименование + " (изм.)"; @@ -1150,82 +1150,82 @@ Summary = "summary"; Черный = "#000000"; Желтый = "#ffd800"; - - Результат = OPI_GoogleCalendar.СоздатьКалендарь(Токен, Наименование); - + + Результат = OPI_GoogleCalendar.СоздатьКалендарь(Токен, Наименование); + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьКалендарь"); - - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип(ТипСоответствие); + + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип(ТипСоответствие); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Summary]).Равно(Наименование); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["id"]).ИмеетТип(ТипСтрока).Заполнено(); - + Календарь = Результат["id"]; - + Результат = OPI_GoogleCalendar.ИзменитьМетаданныеКалендаря(Токен , Календарь , НаименованиеИзмененное , Описание); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьМетаданныеКалендаря"); - + Проверка_ГКОбъект(Результат, НаименованиеИзмененное, Описание); - + Результат = OPI_GoogleCalendar.ПолучитьМетаданныеКалендаря(Токен, Календарь); - - // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьМетаданныеКалендаря"); - + + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьМетаданныеКалендаря"); + Проверка_ГКОбъект(Результат, НаименованиеИзмененное, Описание); Результат = OPI_GoogleCalendar.ДобавитьКалендарьВСписок(Токен, Календарь); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьКалендарьВСписок"); - + Проверка_ГКОбъект(Результат, НаименованиеИзмененное, Описание); - + Результат = OPI_GoogleCalendar.ИзменитьКалендарьСписка(Токен, Календарь, Черный, Желтый, Ложь); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьКалендарьСписка"); - - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип(ТипСоответствие); + + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип(ТипСоответствие); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Summary]).Равно(НаименованиеИзмененное); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["foregroundColor"]).Равно(Черный); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["backgroundColor"]).Равно(Желтый); - + Результат = OPI_GoogleCalendar.ПолучитьКалендарьСписка(Токен, Календарь); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьКалендарьСписка"); - - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип(ТипСоответствие); + + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип(ТипСоответствие); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Summary]).Равно(НаименованиеИзмененное); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["foregroundColor"]).Равно(Черный); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["backgroundColor"]).Равно(Желтый); Результат = OPI_GoogleCalendar.ОчиститьОсновнойКалендарь(Токен); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОчиститьОсновнойКалендарь"); - + Проверка_Пусто(Результат); - + Результат = OPI_GoogleCalendar.УдалитьКалендарьИзСписка(Токен, Календарь); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьКалендарьИзСписка"); - + Проверка_Пусто(Результат); - + Результат = OPI_GoogleCalendar.УдалитьКалендарь(Токен, Календарь); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьКалендарь"); - + Проверка_Пусто(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ГК_СоздатьУдалитьСобытие() Экспорт - + ТекущаяДата = OPI_Инструменты.ПолучитьТекущуюДату(); - Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); Календарь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_CalendarID"); Наименование = "Новое событие"; Описание = "Описание тестового события"; @@ -1234,12 +1234,12 @@ Час = 3600; Вложения = Новый Соответствие; - + Вложения.Вставить("Картинка1" , "https://opi.neocities.org/assets/images/logo_long-e8fdcca6ff8b32e679ea49a1ccdd3eac.png"); Вложения.Вставить("Картинка2" , "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/Media/logo.png?v1"); - + СоответствиеСобытия = Новый Соответствие; СоответствиеСобытия.Вставить("Описание" , Описание); СоответствиеСобытия.Вставить("Заголовок" , Наименование); @@ -1248,59 +1248,59 @@ СоответствиеСобытия.Вставить("ДатаОкончания" , СоответствиеСобытия["ДатаНачала"] + Час); СоответствиеСобытия.Вставить("МассивURLФайловВложений" , Вложения); СоответствиеСобытия.Вставить("ОтправлятьУведомления" , Истина); - + Результат = OPI_GoogleCalendar.СоздатьСобытие(Токен, Календарь, СоответствиеСобытия); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьСобытие"); - + Событие = Результат[UID]; - + Проверка_ГКОбъект(Результат, Наименование, Описание); - - СоответствиеСобытия = Новый Соответствие; + + СоответствиеСобытия = Новый Соответствие; СоответствиеСобытия.Вставить("Описание", ОписаниеИзм); - + Результат = OPI_GoogleCalendar.ИзменитьСобытие(Токен, Календарь, СоответствиеСобытия, Событие); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьСобытие"); - + Проверка_ГКОбъект(Результат, Наименование, ОписаниеИзм); - + Результат = OPI_GoogleCalendar.ПолучитьСобытие(Токен, Календарь, Событие); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСобытие"); - + Проверка_ГКОбъект(Результат, Наименование, ОписаниеИзм); Результат = OPI_GoogleCalendar.ПереместитьСобытие(Токен, Календарь, Календарь, Событие); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереместитьСобытие"); - + Проверка_ГКОбъект(Результат, Наименование, ОписаниеИзм); - - Результат = OPI_GoogleCalendar.УдалитьСобытие(Токен, Календарь, Событие); - + + Результат = OPI_GoogleCalendar.УдалитьСобытие(Токен, Календарь, Событие); + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьСобытие"); - + Проверка_Пусто(Результат); - + OPI_Инструменты.Пауза(5); КонецПроцедуры Процедура ГК_ПолучитьСписокСобытий() Экспорт - - Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); + + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); Календарь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_CalendarID"); Результат = OPI_GoogleCalendar.ПолучитьСписокСобытий(Токен, Календарь); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокСобытий"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Массив"); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры #КонецОбласти @@ -1308,121 +1308,121 @@ #Область GoogleDrive Процедура ГД_ПолучитьСписокКаталогов() Экспорт - + MimeType_ = "mimeType"; Name_ = "name"; Имя = "Тестовая папка"; Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); Результат = OPI_GoogleDrive.ПолучитьСписокКаталогов(Токен, Имя, Истина); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокКаталогов"); - + Результат = Результат[0]; - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["files"]).ИмеетТип("Массив"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[MimeType_]).Равно("application/vnd.google-apps.folder"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Name_]).Заполнено(); - + OPI_Инструменты.Пауза(5); Идентификатор = Результат["id"]; - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("GD_Catalog", Идентификатор); - + Результат = OPI_GoogleDrive.ПолучитьИнформациюОбОбъекте(Токен, Идентификатор); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИнформациюОбОбъекте"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[MimeType_]).Равно("application/vnd.google-apps.folder"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Name_]).Заполнено(); - + OPI_Инструменты.Пауза(5); КонецПроцедуры Процедура ГД_ЗагрузитьУдалитьФайл() Экспорт - + ЛишниеБайты = 2; - + Kind_ = "kind"; Content_ = "content"; MIME_ = "MIME"; MimeType_ = "mimeType"; Name_ = "name"; Id_ = "id"; - + МассивУдаляемых = Новый Массив; Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); Картинка = OPI_ПолучениеДанныхТестов.ПолучитьДвоичные("Picture"); КартинкаЗамены = OPI_ПолучениеДанныхТестов.ПолучитьДвоичные("Picture2"); Каталог = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("GD_Catalog"); - + Описание = OPI_GoogleDrive.ПолучитьОписаниеФайла(); Описание.Вставить("Родитель", Каталог); - + Результат = OPI_GoogleDrive.ЗагрузитьФайл(Токен, Картинка, Описание); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗагрузитьФайл"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[MimeType_]).Равно(Описание[MIME_]); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Name_]).Равно(Описание["Имя"]); Идентификатор = Результат[Id_]; МассивУдаляемых.Добавить(Идентификатор); - + НовоеИмя = "Скопированный файл.jpeg"; Результат = OPI_GoogleDrive.СкопироватьОбъект(Токен, Идентификатор, НовоеИмя, "root"); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СкоприроватьОбъект"); - + OPI_Инструменты.Пауза(5); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[MimeType_]).Равно(Описание[MIME_]); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Name_]).Равно(НовоеИмя); - + МассивУдаляемых.Добавить(Результат[Id_]); - + Результат = OPI_GoogleDrive.СкачатьФайл(Токен, Идентификатор); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СкачатьФайл"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат.Размер()).Равно(Картинка.Размер() + ЛишниеБайты); OPI_Инструменты.Пауза(5); - + НовоеИмя = "Обновленный файл.jpg"; Результат = OPI_GoogleDrive.ОбновитьФайл(Токен, Идентификатор, КартинкаЗамены, НовоеИмя); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОбновитьФайл"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[MimeType_]).Равно(Описание[MIME_]); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Name_]).Равно(НовоеИмя); OPI_Инструменты.Пауза(5); - + Комментарий = "Yo"; Результат = OPI_GoogleDrive.СоздатьКомментарий(Токен, Идентификатор, Комментарий); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьКомментарий"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Content_]).Равно(Комментарий); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Kind_]).Равно("drive#comment"); - + OPI_Инструменты.Пауза(5); - + Для Каждого Удаляемый Из МассивУдаляемых Цикл - Результат = OPI_GoogleDrive.УдалитьОбъект(Токен, Удаляемый); - + Результат = OPI_GoogleDrive.УдалитьОбъект(Токен, Удаляемый); + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьОбъект"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(ЗначениеЗаполнено(Результат)).Равно(Ложь); OPI_Инструменты.Пауза(2); КонецЦикла; - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура ГД_СоздатьУдалитьКомментарий() Экспорт - + Kind_ = "kind"; Content_ = "content"; Id_ = "id"; @@ -1430,75 +1430,75 @@ Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); Каталог = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("GD_Catalog"); Картинка = OPI_ПолучениеДанныхТестов.ПолучитьДвоичные("Picture"); - + Описание = OPI_GoogleDrive.ПолучитьОписаниеФайла(); Описание.Вставить("Родитель", Каталог); - + Результат = OPI_GoogleDrive.ЗагрузитьФайл(Токен, Картинка, Описание); Идентификатор = Результат[Id_]; - + Комментарий = "Новый комментарий"; МассивРезультатов = Новый Массив; Результат = OPI_GoogleDrive.СоздатьКомментарий(Токен, Идентификатор, Комментарий); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьКомментарий"); - + ИДКомментария = Результат[Id_]; - + МассивРезультатов.Добавить(Результат); - + Результат = OPI_GoogleDrive.ПолучитьКомментарий(Токен, Идентификатор, ИДКомментария); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьКомментарий"); - + МассивРезультатов.Добавить(Результат); - + Результат = OPI_GoogleDrive.ПолучитьСписокКомментариев(Токен, Идентификатор); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокКомментариев"); - + Комментарии = Результат[Comments_]; ОбъектКомментарий = Комментарии[Комментарии.ВГраница()]; - + МассивРезультатов.Добавить(ОбъектКомментарий); - - Для Каждого Результат Из МассивРезультатов Цикл + + Для Каждого Результат Из МассивРезультатов Цикл OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Content_]).Равно(Комментарий); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Kind_]).Равно("drive#comment"); КонецЦикла; - - Результат = OPI_GoogleDrive.УдалитьКомментарий(Токен, Идентификатор, ИДКомментария); - + + Результат = OPI_GoogleDrive.УдалитьКомментарий(Токен, Идентификатор, ИДКомментария); + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьКомментарий"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(ЗначениеЗаполнено(Результат)).Равно(Ложь); OPI_GoogleDrive.УдалитьОбъект(Токен, Идентификатор); - + КонецПроцедуры Процедура ГД_СоздатьКаталог() Экспорт - + Name_ = "name"; Имя = "Тестовая папка"; Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); Каталог = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("GD_Catalog"); - + МассивРезультатов = Новый Массив; - + МассивРезультатов.Добавить(OPI_GoogleDrive.СоздатьПапку(Токен, Имя)); МассивРезультатов.Добавить(OPI_GoogleDrive.СоздатьПапку(Токен, Имя, Каталог)); - + Для Каждого Результат Из МассивРезультатов Цикл - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьПапку"); - + ИДКаталога = Результат["id"]; - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Name_]).Равно(Имя); - + OPI_GoogleDrive.УдалитьОбъект(Токен, ИДКаталога); - + КонецЦикла; КонецПроцедуры @@ -1508,90 +1508,90 @@ #Область GoogleSheets Процедура ГТ_СоздатьТаблицу() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); Наименование = "Тестовая таблица"; - + МассивЛистов = Новый Массив; МассивЛистов.Добавить("Лист1"); МассивЛистов.Добавить("Лист2"); - + Результат = OPI_GoogleSheets.СоздатьКнигу(Токен, Наименование, МассивЛистов); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьКнигу"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["properties"]["title"]).Равно(Наименование); Для Н = 0 По МассивЛистов.ВГраница() Цикл - + ИмяЛиста = Результат["sheets"][Н]["properties"]["title"]; OPI_ПолучениеДанныхТестов.ОжидаетЧто(ИмяЛиста).Равно(МассивЛистов[Н]); - Лист = Результат["sheets"][Н]["properties"]["sheetId"]; - Лист = OPI_Инструменты.ЧислоВСтроку(Лист); - + Лист = Результат["sheets"][Н]["properties"]["sheetId"]; + Лист = OPI_Инструменты.ЧислоВСтроку(Лист); + КонецЦикла; - + Книга = Результат["spreadsheetId"]; - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("GS_Spreadsheet", Книга); OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("GS_Sheet" , Лист); - + Наименование = "Тестовая таблица (доп.)"; Результат = OPI_GoogleSheets.СоздатьКнигу(Токен, Наименование, МассивЛистов); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "КопироватьЛист (доп.)"); - + Книга2 = Результат["spreadsheetId"]; - + Результат = OPI_GoogleSheets.КопироватьЛист(Токен, Книга, Книга2, Лист); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "КопироватьЛист"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["title"]).Заполнено(); - + Наименование = "Тестовый лист"; - + Результат = OPI_GoogleSheets.ДобавитьЛист(Токен, Книга, Наименование); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьЛист"); НовыйЛист = Результат["replies"][0]["addSheet"]["properties"]["sheetId"]; НовыйЛист = OPI_Инструменты.ЧислоВСтроку(НовыйЛист); - - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["spreadsheetId"]).Равно(Книга); + + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["spreadsheetId"]).Равно(Книга); Результат = OPI_GoogleSheets.УдалитьЛист(Токен, Книга, НовыйЛист); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьЛист"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["spreadsheetId"]).Равно(Книга); - + Наименование = "Тестовая таблица (изм.)"; - + Результат = OPI_GoogleSheets.ИзменитьНаименованиеКниги(Токен, Книга, Наименование); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьНаименованиеКниги"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["spreadsheetId"]).Равно(Книга); - + КонецПроцедуры Процедура ГТ_ПолучитьТаблицу() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); Книга = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("GS_Spreadsheet"); Наименование = "Тестовая таблица (изм.)"; Результат = OPI_GoogleSheets.ПолучитьКнигу(Токен, Книга); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьТаблицу"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["properties"]["title"]).Равно(Наименование); КонецПроцедуры Процедура ГТ_ЗаполнитьОчиститьЯчейки() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Google_Token"); Книга = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("GS_Spreadsheet"); Лист = "Лист2"; @@ -1605,41 +1605,41 @@ СтруктураЯчеек.Вставить("A4", "Это A4"); СтруктураЯчеек.Вставить("B1", "Это B1"); СтруктураЯчеек.Вставить("B4", "Это B4"); - + МассивЯчеек = Новый Массив; МассивЯчеек.Добавить("B2"); МассивЯчеек.Добавить("A3"); МассивЯчеек.Добавить("B4"); Результат = OPI_GoogleSheets.УстановитьЗначенияЯчеек(Токен, Книга, СтруктураЯчеек, Лист); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УстановитьЗначенияЯчеек"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["spreadsheetId"]).Равно(Книга); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["totalUpdatedCells"]).Равно(СтруктураЯчеек.Количество()); - + Результат = OPI_GoogleSheets.ПолучитьЗначенияЯчеек(Токен, Книга, МассивЯчеек, Лист); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьЗначенияЯчеек"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["spreadsheetId"]).Равно(Книга); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["valueRanges"].Количество()).Равно(МассивЯчеек.Количество()); - + Результат = OPI_GoogleSheets.ПолучитьЗначенияЯчеек(Токен, Книга, , Лист); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьЗначенияЯчеек"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["spreadsheetId"]).Равно(Книга); - + МассивЯчеек = Новый Массив; МассивЯчеек.Добавить("B2"); МассивЯчеек.Добавить("A3"); МассивЯчеек.Добавить("B4"); Результат = OPI_GoogleSheets.ОчиститьЯчейки(Токен, Книга, МассивЯчеек, Лист); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОчиститьЯчейки"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["spreadsheetId"]).Равно(Книга); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["clearedRanges"].Количество()).Равно(МассивЯчеек.Количество()); @@ -1650,154 +1650,154 @@ #Область Twitter Процедура Твиттер_ПолучитьСсылкуАвторизации() Экспорт - + Параметры = ПолучитьПараметрыТвиттер(); Результат = OPI_Twitter.ПолучитьСсылкуАвторизации(Параметры); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Строка").Заполнено(); - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Twitter_URL", Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Твиттер_ОбновитьТокен() Экспорт - + Параметры = ПолучитьПараметрыТвиттер(); Результат = OPI_Twitter.ОбновитьТокен(Параметры); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["access_token"]).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["refresh_token"]).Заполнено(); - + Рефреш = Результат["refresh_token"]; Токен = Результат["access_token"]; - - Если ЗначениеЗаполнено(Рефреш) И Не Рефреш = "null" Тогда + + Если ЗначениеЗаполнено(Рефреш) И Не Рефреш = "null" Тогда OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Twitter_Refresh", Рефреш); КонецЕсли; - + Если ЗначениеЗаполнено(Токен) И Не Токен = "null" Тогда OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Twitter_Token" , Токен); КонецЕсли; - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Твиттер_СоздатьТекстовыйТвит() Экспорт - + Параметры = ПолучитьПараметрыТвиттер(); Текст = "Тестовый твитт" + Строка(Новый УникальныйИдентификатор); - + Результат = OPI_Twitter.СоздатьТекстовыйТвит(Текст, Параметры); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьТекстовыйТвит"); - + Проверка_ТвиттерТекст(Результат, Текст); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Твиттер_СоздатьТвитСКартинкой() Экспорт - + Параметры = ПолучитьПараметрыТвиттер(); Текст = "Тестовый твитт" + Строка(Новый УникальныйИдентификатор); Картинка = OPI_ПолучениеДанныхТестов.ПолучитьДвоичные("Picture"); ИВФ = ПолучитьИмяВременногоФайла("png"); Картинка.Записать(ИВФ); - - Результат = OPI_Twitter.СоздатьТвитКартинки(Текст, Картинка, Параметры); - + + Результат = OPI_Twitter.СоздатьТвитКартинки(Текст, Картинка, Параметры); + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьТвитКартинки"); - - Проверка_ТвиттерТекст(Результат, Текст); - + + Проверка_ТвиттерТекст(Результат, Текст); + Текст = "Тестовый твитт" + Строка(Новый УникальныйИдентификатор); Результат = OPI_Twitter.СоздатьТвитКартинки(Текст, ИВФ, Параметры); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьТвитКартинки"); - + Проверка_ТвиттерТекст(Результат, Текст); - + УдалитьФайлы(ИВФ); - + OPI_Инструменты.Пауза(20); - + КонецПроцедуры Процедура Твиттер_СоздатьТвитСВидео() Экспорт - + Параметры = ПолучитьПараметрыТвиттер(); Текст = "Тестовый твитт" + Строка(Новый УникальныйИдентификатор); Видео = OPI_ПолучениеДанныхТестов.ПолучитьДвоичные("Video"); ИВФ = ПолучитьИмяВременногоФайла("mp4"); Видео.Записать(ИВФ); - - Результат = OPI_Twitter.СоздатьТвитВидео(Текст, Видео, Параметры); - + + Результат = OPI_Twitter.СоздатьТвитВидео(Текст, Видео, Параметры); + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьТвитВидео"); - - Проверка_ТвиттерТекст(Результат, Текст); - + + Проверка_ТвиттерТекст(Результат, Текст); + Текст = "Тестовый твитт" + Строка(Новый УникальныйИдентификатор); Результат = OPI_Twitter.СоздатьТвитВидео(Текст, ИВФ, Параметры); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьТвитВидео"); - + Проверка_ТвиттерТекст(Результат, Текст); - + УдалитьФайлы(ИВФ); - + OPI_Инструменты.Пауза(20); - + КонецПроцедуры Процедура Твиттер_СоздатьТвитСГиф() Экспорт - + Параметры = ПолучитьПараметрыТвиттер(); Текст = "Тестовый твитт" + Строка(Новый УникальныйИдентификатор); Гифка = OPI_ПолучениеДанныхТестов.ПолучитьДвоичные("GIF"); ИВФ = ПолучитьИмяВременногоФайла("gif"); Гифка.Записать(ИВФ); - - Результат = OPI_Twitter.СоздатьТвитГифки(Текст, Гифка, Параметры); - + + Результат = OPI_Twitter.СоздатьТвитГифки(Текст, Гифка, Параметры); + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьТвитГифки"); - - Проверка_ТвиттерТекст(Результат, Текст); - + + Проверка_ТвиттерТекст(Результат, Текст); + Текст = "Тестовый твитт" + Строка(Новый УникальныйИдентификатор); Результат = OPI_Twitter.СоздатьТвитГифки(Текст, ИВФ, Параметры); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьТвитГифки"); - + Проверка_ТвиттерТекст(Результат, Текст); - + УдалитьФайлы(ИВФ); - + OPI_Инструменты.Пауза(20); - + КонецПроцедуры Процедура Твиттер_СоздатьТвитСОпросом() Экспорт - + Параметры = ПолучитьПараметрыТвиттер(); Текст = "Тестовый твитт" + Строка(Новый УникальныйИдентификатор); МассивОтветов = Новый Массив; МассивОтветов.Добавить("Вариант 1"); МассивОтветов.Добавить("Вариант 2"); - + Результат = OPI_Twitter.СоздатьТвитОпрос(Текст, МассивОтветов, 60, Параметры); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьТвитОпрос"); - + Проверка_ТвиттерТекст(Результат, Текст); - + OPI_Инструменты.Пауза(20); - + КонецПроцедуры #КонецОбласти @@ -1805,25 +1805,25 @@ #Область Notion Процедура Ноушн_СоздатьСтраницу() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Token"); Родитель = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Parent"); Заголовок = "Тестовый заголовок"; - + Результат = OPI_Notion.СоздатьСтраницу(Токен, Родитель, Заголовок); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьСтраницу"); - + Проверка_НоушнОбъект(Результат); КонецПроцедуры Процедура Ноушн_СоздатьИзменитьБазу() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Token"); Родитель = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Parent"); Заголовок = "Тестовый заголовок"; - + Свойства = Новый Соответствие; Свойства.Вставить("Имя" , "title"); Свойства.Вставить("Описание" , "rich_text"); @@ -1836,69 +1836,69 @@ Свойства.Вставить("Почта" , "email"); Свойства.Вставить("Телефон" , "phone_number"); Свойства.Вставить("Пользователь" , "people"); - + ВыборЗначения = Новый Соответствие; - ВыборЗначения.Вставить("Новый", "green"); - ВыборЗначения.Вставить("В работе", "yellow"); + ВыборЗначения.Вставить("Новый" , "green"); + ВыборЗначения.Вставить("В работе" , "yellow"); ВыборЗначения.Вставить("Удаленный", "red"); Свойства.Вставить("Статус", ВыборЗначения); - - Результат = OPI_Notion.СоздатьБазуДанных(Токен, Родитель, Заголовок, Свойства); - + + Результат = OPI_Notion.СоздатьБазуДанных(Токен, Родитель, Заголовок, Свойства); + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьБазуДанных"); - + Проверка_НоушнОбъект(Результат, "database"); - + База = Результат["id"]; Заголовок = "Тестовый заголовок"; - Описание = "Тестовое описание"; - + Описание = "Тестовое описание"; + Свойства = Новый Соответствие; Свойства.Вставить("Почта", "rich_text"); // Тип поля "Почта" будет изменен с email на текст Свойства.Вставить("Сайт"); // Поле "Сайт" будет удалено - + Результат = OPI_Notion.ИзменитьСвойстваБазы(Токен, База, Свойства, Заголовок, Описание); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьСвойстваБазы"); - + Проверка_НоушнОбъект(Результат, "database"); КонецПроцедуры Процедура Ноушн_ПолучитьИнформациюОСтранице() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Token"); Страница = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Page"); - + Результат = OPI_Notion.ПолучитьСтраницу(Токен, Страница); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСтраницу"); - - Проверка_НоушнОбъект(Результат); - + + Проверка_НоушнОбъект(Результат); + КонецПроцедуры Процедура Ноушн_ПолучитьИнформациюОБазе() Экспорт Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Token"); База = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Base"); - + Результат = OPI_Notion.ПолучитьБазуДанных(Токен, База); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьБазуДанных"); - + Проверка_НоушнОбъект(Результат, "database"); - + КонецПроцедуры Процедура Ноушн_СоздатьСтраницуВБазу() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Token"); База = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Base"); - + Картинка = Новый Соответствие; Картинка.Вставить("Лого", OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Picture")); - + Свойства = Новый Соответствие; Свойства.Вставить("Имя" , "ООО Вектор"); Свойства.Вставить("Описание" , "Наш первый клиент"); @@ -1910,98 +1910,98 @@ Свойства.Вставить("Сайт" , "https://vector.ru"); Свойства.Вставить("Почта" , "mail@vector.ru"); Свойства.Вставить("Телефон" , "88005553535"); - Свойства.Вставить("Статус" , "Новый"); - + Свойства.Вставить("Статус" , "Новый"); + Результат = OPI_Notion.СоздатьСтраницуВБазу(Токен, База, Свойства); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьСтраницуВБазу"); - + Проверка_НоушнОбъект(Результат); - + Родитель = СтрЗаменить(Результат["parent"]["database_id"], "-", ""); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Родитель).Равно(База); - + КонецПроцедуры Процедура Ноушн_ИзменитьСвойстваСтраницы() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Token"); Страница = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Page"); Иконка = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Picture"); Обложка = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Picture2"); Архивировать = Ложь; - + Свойства = Новый Соответствие; Свойства.Вставить("Активен" , Ложь); Свойства.Вставить("Почта" , "vector@mail.ru"); - + Результат = OPI_Notion.ИзменитьСвойстваСтраницы(Токен , Страница , Свойства , Иконка , Обложка , Архивировать); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьСвойстваСтраницы"); - + Проверка_НоушнОбъект(Результат); - + КонецПроцедуры Процедура Ноушн_СоздатьУдалитьБлок() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Token"); Родитель = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Parent"); Блок = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Block"); - - Результат = OPI_Notion.ВернутьБлок(Токен, Блок); - + + Результат = OPI_Notion.ВернутьБлок(Токен, Блок); + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВернутьБлок"); - + Проверка_НоушнОбъект(Результат, "block"); - + Результат = OPI_Notion.СоздатьБлок(Токен, Родитель, Результат); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьБлок"); - + Проверка_НоушнОбъект(Результат, "list"); - + Блок = Результат["results"][0]["id"]; - Результат = OPI_Notion.ВернутьДочерниеБлоки(Токен, Блок); - + Результат = OPI_Notion.ВернутьДочерниеБлоки(Токен, Блок); + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВернутьДочерниеБлоки"); - + Проверка_НоушнОбъект(Результат, "list"); - + Результат = OPI_Notion.УдалитьБлок(Токен, Блок); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьБлок"); - + Проверка_НоушнОбъект(Результат, "block"); - + КонецПроцедуры Процедура Ноушн_ПолучитьПользователей() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Token"); Результат = OPI_Notion.СписокПользователей(Токен); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СписокПользователей"); - + Проверка_НоушнОбъект(Результат, "list"); - + КонецПроцедуры Процедура Ноушн_ПолучитьДанныеПользователя() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_Token"); - Пользователь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_User"); + Пользователь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Notion_User"); Результат = OPI_Notion.ПолучитьДанныеПользователя(Токен, Пользователь); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьДанныеПользователя"); - + Проверка_НоушнОбъект(Результат, "user"); - + КонецПроцедуры #КонецОбласти @@ -2009,160 +2009,160 @@ #Область Slack Процедура Слак_ПолучитьИнформациюОБоте() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); Результат = OPI_Slack.ПолучитьИнформациюОБоте(Токен); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИнформациюОБоте"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["bot_id"]).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["user_id"]).Заполнено(); - + КонецПроцедуры Процедура Слак_ПолучитьСписокПользователей() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); Результат = OPI_Slack.ПолучитьСписокПользователей(Токен); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокПользователей"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["members"]).ИмеетТип("Массив"); - + КонецПроцедуры Процедура Слак_ПолучитьСписокОбластей() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); Результат = OPI_Slack.ПолучитьСписокРабочихОбластей(Токен); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокРабочихОбластей"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["teams"]).ИмеетТип("Массив"); - + КонецПроцедуры Процедура Слак_ОтправитьУдалитьСообщение() Экспорт - Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); Канал = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Channel"); Текст = "Тестовое сообщение 1"; Текст2 = "Тестовое сообщение 2"; Отметки = Новый Массив; Картинка = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/Media/logo.png?v1"; - + Результат = OPI_Slack.ОтправитьСообщение(Токен, Канал, Текст); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьСообщение"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["channel"]).Равно(Канал); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ts"]).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message"]["text"]).Равно(Текст); - + Отметка = Результат["ts"]; - + Результат = OPI_Slack.ИзменитьСообщение(Токен, Канал, Отметка, Текст2); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьСообщение"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["channel"]).Равно(Канал); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ts"]).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message"]["text"]).Равно(Текст2); - + Результат = OPI_Slack.ПолучитьСписокОтветовНаСообщение(Токен, Канал, Отметка); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокОтветовНаСообщение"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["messages"]).ИмеетТип("Массив"); - + Результат = OPI_Slack.ПолучитьСсылкуНаСообщение(Токен, Канал, Отметка); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСсылкуНаСообщение"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["channel"]).Равно(Канал); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["permalink"]).Заполнено(); - + Проверка_СлакОк(Результат); - + Отметки.Добавить(Отметка); - + МассивБлоков = Новый Массив; Блок = OPI_Slack.СформироватьБлокКартинку(Картинка, "Yo"); МассивБлоков.Добавить(Блок); - + Результат = OPI_Slack.ОтправитьСообщение(Токен, Канал, Текст, , МассивБлоков); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьСообщение (картинка)"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["channel"]).Равно(Канал); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ts"]).Заполнено(); - + Отметки.Добавить(Результат["ts"]); - - Блок = OPI_Slack.СформироватьБлокКартинку(Картинка, "Yo"); + + Блок = OPI_Slack.СформироватьБлокКартинку(Картинка, "Yo"); БлокJSON = OPI_Инструменты.JSONСтрокой(Блок); - + ИВФ = ПолучитьИмяВременногоФайла("json"); - + ТекстовыйДокумент = Новый ТекстовыйДокумент(); ТекстовыйДокумент.УстановитьТекст(БлокJSON); ТекстовыйДокумент.Записать(ИВФ); - + Результат = OPI_Slack.ОтправитьСообщение(Токен, Канал, Текст, , ИВФ); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьСообщение (json)"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["channel"]).Равно(Канал); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ts"]).Заполнено(); - + Отметки.Добавить(Результат["ts"]); - - Блоки = "['" + ИВФ + "','" + ИВФ + "']"; + + Блоки = "['" + ИВФ + "','" + ИВФ + "']"; Результат = OPI_Slack.ОтправитьСообщение(Токен, Канал, Текст, , Блоки); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьСообщение (json массив)"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["channel"]).Равно(Канал); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ts"]).Заполнено(); - + Отметки.Добавить(Результат["ts"]); УдалитьФайлы(ИВФ); - + Для Каждого Отметка Из Отметки Цикл - + Результат = OPI_Slack.УдалитьСообщение(Токен, Канал, Отметка); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьСообщение"); Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["channel"]).Равно(Канал); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ts"]).Заполнено(); - + КонецЦикла; - + Час = 3600; Сутки = 24; Отправка = OPI_Инструменты.ПолучитьТекущуюДату() + (Сутки * Час); Результат = OPI_Slack.ОтправитьСообщение(Токен, Канал, Текст, Отправка); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьСообщение (отложенное)"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["channel"]).Равно(Канал); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["scheduled_message_id"]).Заполнено(); - + Отметка = Результат["scheduled_message_id"]; Результат = OPI_Slack.УдалитьСообщение(Токен, Канал, Отметка, Истина); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьСообщение"); Проверка_СлакОк(Результат); @@ -2170,50 +2170,50 @@ КонецПроцедуры Процедура Слак_ОтправитьУдалитьЭфемерное() Экспорт - - Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); + + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); Канал = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Channel"); Пользователь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_User"); Картинка = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/Media/logo.png?v1"; Текст = "Тестовое сообщение 1"; - + Блок = OPI_Slack.СформироватьБлокКартинку(Картинка, "Yo"); Результат = OPI_Slack.ОтправитьЭфемерноеСообщение(Токен, Канал, Текст, Пользователь, Блок); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьСообщение"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["message_ts"]).Заполнено(); - + КонецПроцедуры Процедура Слак_ПолучитьОтложенныеСообщения() Экспорт - - Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); + + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); Канал = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Channel"); - + Результат = OPI_Slack.ПолучитьСписокОтложенныхСообщений(Токен, Канал); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокОтложенныхСообщений"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["scheduled_messages"]).ИмеетТип("Массив"); - + КонецПроцедуры Процедура Слак_СоздатьАрхивироватьКанал() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); Пользователь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_User"); Имя = "testconv" + Строка(Новый УникальныйИдентификатор); Тема = "Тестовая тема"; Цель = "Тестовая цель"; - + #Область СоздатьКанал Результат = OPI_Slack.СоздатьКанал(Токен, Имя); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьКанал"); - + Данные = Результат["channel"]; Канал = Данные["id"]; @@ -2223,9 +2223,9 @@ #Область УстановитьТемуКанала Результат = OPI_Slack.УстановитьТемуКанала(Токен, Канал, Тема); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УстановитьТемуКанала"); - + Данные = Результат["channel"]; Канал = Данные["id"]; @@ -2233,144 +2233,144 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Данные["name"]).Равно(Имя); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Данные["topic"]["value"]).Равно(Тема); #КонецОбласти - + #Область УстановитьЦельКанала Результат = OPI_Slack.УстановитьЦельКанала(Токен, Канал, Цель); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УстановитьЦельКанала"); - + Проверка_СлакОк(Результат); #КонецОбласти - + #Область ПолучитьКанал Результат = OPI_Slack.ПолучитьКанал(Токен, Канал); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьКанал"); - + Данные = Результат["channel"]; Канал = Данные["id"]; Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Данные["name"]).Равно(Имя); #КонецОбласти - + #Область ПригласитьПользователейВКанал Результат = OPI_Slack.ПригласитьПользователейВКанал(Токен, Канал, Пользователь); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПригласитьПользователейВКанал"); - + Данные = Результат["channel"]; Канал = Данные["id"]; Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Данные["name"]).Равно(Имя); #КонецОбласти - + #Область ВыгнатьПользователяИзКанала Результат = OPI_Slack.ВыгнатьПользователяИзКанала(Токен, Канал, Пользователь); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВыгнатьПользователяИзКанала"); - + Проверка_СлакОк(Результат); #КонецОбласти - + #Область ПолучитьИсториюКанала Результат = OPI_Slack.ПолучитьИсториюКанала(Токен, Канал); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИсториюКанала"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["messages"]).ИмеетТип("Массив"); #КонецОбласти - + #Область ПолучитьСписокПользователейКанала Результат = OPI_Slack.ПолучитьСписокПользователейКанала(Токен, Канал); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокПользователейКанала"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["members"]).ИмеетТип("Массив"); #КонецОбласти #Область ПокинутьКанал Результат = OPI_Slack.ПокинутьКанал(Токен, Канал); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПокинутьКанал"); - + Проверка_СлакОк(Результат); #КонецОбласти - + #Область ВступитьВКанал Результат = OPI_Slack.ВступитьВКанал(Токен, Канал); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВступитьВКанал"); - + Данные = Результат["channel"]; Канал = Данные["id"]; Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Данные["name"]).Равно(Имя); #КонецОбласти - + #Область ПереименоватьКанал НовоеИмя = "testconv" + Строка(Новый УникальныйИдентификатор); Результат = OPI_Slack.ПереименоватьКанал(Токен, Канал, НовоеИмя); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереименоватьКанал"); - + Данные = Результат["channel"]; Канал = Данные["id"]; Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Данные["name"]).Равно(НовоеИмя); #КонецОбласти - + #Область АрхивироватьКанал Результат = OPI_Slack.АрхивироватьКанал(Токен, Канал); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "АрхивироватьКанал"); - + Проверка_СлакОк(Результат); #КонецОбласти - + КонецПроцедуры Процедура Слак_ПолучитьСписокКаналов() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); - + Результат = OPI_Slack.ПолучитьСписокКаналов(Токен); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокКаналов"); Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["channels"]).ИмеетТип("Массив"); - + КонецПроцедуры Процедура Слак_ОткрытьЗакрытьДиалог() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); Пользователь = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_User"); Текст = "Yo, dude"; - + Результат = OPI_Slack.ОткрытьДиалог(Токен, Пользователь); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОткрытьДиалог"); Диалог = Результат["channel"]["id"]; Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["channel"]).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Диалог).Заполнено(); - + Результат = OPI_Slack.ОтправитьСообщение(Токен, Диалог, Текст); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьСообщение"); - + Проверка_СлакОк(Результат); Результат = OPI_Slack.ЗакрытьДиалог(Токен, Диалог); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗакрытьДиалог"); Проверка_СлакОк(Результат); @@ -2378,12 +2378,12 @@ КонецПроцедуры Процедура Слак_ПолучитьСписокФайлов() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); Канал = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Channel"); - + Результат = OPI_Slack.ПолучитьСписокФайлов(Токен, Канал); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокФайлов"); Проверка_СлакОк(Результат); @@ -2392,113 +2392,113 @@ КонецПроцедуры Процедура Слак_ЗагрузитьУдалитьФайл() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); Файл = OPI_ПолучениеДанныхТестов.ПолучитьДвоичные("Document"); Канал = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Channel"); МассивФайлов = Новый Массив; ИмяФайла = "megadoc.docx"; Заголовок = "Новый файл"; - + Результат = OPI_Slack.ЗагрузитьФайл(Токен, Файл, ИмяФайла, Заголовок); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗагрузитьФайл"); ЗагруженныйФайл = Результат["files"][0]; МассивФайлов.Добавить(ЗагруженныйФайл["id"]); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(ЗагруженныйФайл["name"]).Равно(ИмяФайла); - + Результат = OPI_Slack.ЗагрузитьФайл(Токен, Файл, ИмяФайла, Заголовок, Канал); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗагрузитьФайл (в канал)"); ЗагруженныйФайл = Результат["files"][0]; МассивФайлов.Добавить(ЗагруженныйФайл["id"]); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(ЗагруженныйФайл["name"]).Равно(ИмяФайла); - + Результат = OPI_Slack.ПолучитьДанныеФайла(Токен, ЗагруженныйФайл["id"]); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьФайл"); - + ЗагруженныйФайл = Результат["file"]; - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(ЗагруженныйФайл["name"]).Равно(ИмяФайла); - + Для Каждого ЗагруженныйФайл Из МассивФайлов Цикл - + Результат = OPI_Slack.УдалитьФайл(Токен, ЗагруженныйФайл); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьФайл"); - + Проверка_СлакОк(Результат); - + КонецЦикла; КонецПроцедуры Процедура Слак_ПолучитьСписокВФ() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); Канал = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Channel"); - + Результат = OPI_Slack.ПолучитьСписокВнешнихФайлов(Токен); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокВнешнихФайлов"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["files"]).ИмеетТип("Массив"); - + Результат = OPI_Slack.ПолучитьСписокВнешнихФайлов(Токен, Канал); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокВнешнихФайлов"); - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["files"]).ИмеетТип("Массив"); - + КонецПроцедуры Процедура Слак_ЗагрузитьУдалитьВФ() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Token"); Файл = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Document"); Канал = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Slack_Channel"); Заголовок = "Новый файл"; - + Результат = OPI_Slack.ДобавитьВнешнийФайл(Токен, Файл, Заголовок); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьВнешнийФайл"); - + ЗагруженныйФайл = Результат["file"]; - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(ЗагруженныйФайл["title"]).Равно(Заголовок); - + Результат = OPI_Slack.ПолучитьВнешнийФайл(Токен, ЗагруженныйФайл["id"]); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьВнешнийФайл"); - + ЗагруженныйФайл = Результат["file"]; - + Проверка_СлакОк(Результат); OPI_ПолучениеДанныхТестов.ОжидаетЧто(ЗагруженныйФайл["title"]).Равно(Заголовок); - + Результат = OPI_Slack.ОтправитьВнешнийФайл(Токен, ЗагруженныйФайл["id"], Канал); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьВнешнийФайл"); - + Проверка_СлакОк(Результат); - + Результат = OPI_Slack.УдалитьВнешнийФайл(Токен, ЗагруженныйФайл["id"]); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьВнешнийФайл"); - + Проверка_СлакОк(Результат); - + КонецПроцедуры #КонецОбласти @@ -2506,127 +2506,127 @@ #Область Airtable Процедура АТ_СоздатьБазу() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Airtable_Token"); Область = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Airtable_Workspace"); Наименование = "Тестовая база"; - + МассивПолей = Новый Массив; МассивПолей.Добавить(OPI_Airtable.ПолучитьПолеНомера("Номер")); МассивПолей.Добавить(OPI_Airtable.ПолучитьПолеСтроковое("Строковое")); - + ИмяТаблицы = "Тестовая таблица"; - + СоответствиеТаблиц = Новый Соответствие; СоответствиеТаблиц.Вставить(ИмяТаблицы, МассивПолей); - + Результат = OPI_Airtable.СоздатьБазу(Токен, Область, Наименование, СоответствиеТаблиц); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьБазу"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["id"]).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["tables"][0]["name"]).Равно(ИмяТаблицы); - + База = Результат["id"]; OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Airtable_Base", База); - + Результат = OPI_Airtable.ПолучитьТаблицыБазы(Токен, База); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьТаблицыБазы"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["tables"]).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["tables"]).ИмеетТип("Массив"); Результат = OPI_Airtable.ПолучитьСписокБаз(Токен); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокБаз"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["bases"]).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["bases"]).ИмеетТип("Массив"); - + КонецПроцедуры Процедура АТ_СоздатьТаблицу() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Airtable_Token"); База = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Airtable_Base"); - + МассивПолей = Новый Массив; - МассивПолей.Добавить(OPI_Airtable.ПолучитьПолеНомера("Номер")); + МассивПолей.Добавить(OPI_Airtable.ПолучитьПолеНомера("Номер")); // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(МассивПолей[0], "ПолучитьПолеНомера"); - + МассивПолей.Добавить(OPI_Airtable.ПолучитьПолеСтроковое("Строковое")); // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(МассивПолей[1], "ПолучитьПолеСтроковое"); - + МассивПолей.Добавить(OPI_Airtable.ПолучитьПолеВложения("Вложение")); // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(МассивПолей[2], "ПолучитьПолеВложения"); - + МассивПолей.Добавить(OPI_Airtable.ПолучитьПолеФлажка("Флажок")); // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(МассивПолей[3], "ПолучитьПолеФлажка"); - + МассивПолей.Добавить(OPI_Airtable.ПолучитьПолеДаты("Дата")); // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(МассивПолей[4], "ПолучитьПолеДаты"); - + МассивПолей.Добавить(OPI_Airtable.ПолучитьПолеТелефона("Телефон")); // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(МассивПолей[5], "ПолучитьПолеТелефона"); - + МассивПолей.Добавить(OPI_Airtable.ПолучитьПолеПочты("Почта")); - // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(МассивПолей[6], "ПолучитьПолеПочты"); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(МассивПолей[6], "ПолучитьПолеПочты"); + МассивПолей.Добавить(OPI_Airtable.ПолучитьПолеСсылки("Ссылка")); - // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(МассивПолей[7], "ПолучитьПолеСсылки"); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(МассивПолей[7], "ПолучитьПолеСсылки"); + ИмяТаблицы = "Тестовая таблица 2"; Описание = "Новая таблица"; - + Результат = OPI_Airtable.СоздатьТаблицу(Токен, База, ИмяТаблицы, МассивПолей, Описание); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьТаблицу"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["name"]).Равно(ИмяТаблицы); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["description"]).Равно(Описание); - + Таблица = Результат["id"]; ИмяТаблицы = "Тестовая таблица 2 (изм.)"; Описание = "Новая таблица (изм.)"; - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Airtable_Table", Таблица); - + Результат = OPI_Airtable.ИзменитьТаблицу(Токен, База, Таблица, ИмяТаблицы, Описание); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьТаблицу"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["name"]).Равно(ИмяТаблицы); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["description"]).Равно(Описание); КонецПроцедуры Процедура АТ_СоздатьПоле() Экспорт - + Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Airtable_Token"); База = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Airtable_Base"); Таблица = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Airtable_Table"); Имя = Строка(Новый УникальныйИдентификатор); - + Поле = OPI_Airtable.ПолучитьПолеНомера(Имя); - + Результат = OPI_Airtable.СоздатьПоле(Токен, База, Таблица, Поле); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьПоле"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["name"]).Равно(Имя); - - Поле = Результат["id"]; + + Поле = Результат["id"]; Имя = Имя + "(изм.)"; Описание = "Новое описание"; - + Результат = OPI_Airtable.ИзменитьПоле(Токен, База, Таблица, Поле, Имя, Описание); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьПоле"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["name"]).Равно(Имя); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["description"]).Равно(Описание); - + КонецПроцедуры Процедура АТ_СоздатьУдалитьЗаписи() Экспорт @@ -2634,94 +2634,94 @@ Токен = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Airtable_Token"); База = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Airtable_Base"); Таблица = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Airtable_Table"); - + Числовой = 10; Строчный = "Привет"; - + ОписаниеСтроки1 = Новый Структура("Номер,Строковое", Числовой, Строчный); ОписаниеСтроки2 = Новый Структура("Номер,Строковое", Числовой, Строчный); - + МассивУдаляемых = Новый Массив; МассивОписаний = Новый Массив; МассивОписаний.Добавить(ОписаниеСтроки1); МассивОписаний.Добавить(ОписаниеСтроки2); - + Результат = OPI_Airtable.СоздатьЗаписи(Токен, База, Таблица, МассивОписаний); // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьЗаписи"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["records"]).ИмеетТип("Массив"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["records"].Количество()).Равно(2); - + Для Каждого Запись Из Результат["records"] Цикл МассивУдаляемых.Добавить(Запись["id"]); КонецЦикла; - + Результат = OPI_Airtable.СоздатьЗаписи(Токен, База, Таблица, ОписаниеСтроки1); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьЗаписи (одна)"); - + ОдиночнаяЗапись = Результат["id"]; OPI_ПолучениеДанныхТестов.ОжидаетЧто(ОдиночнаяЗапись).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["createdTime"]).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["fields"]["Номер"]).Равно(Числовой); OPI_ПолучениеДанныхТестов.ОжидаетЧто(СокрЛП(Результат["fields"]["Строковое"])).Равно(Строчный); - + Результат = OPI_Airtable.ПолучитьЗапись(Токен, База, Таблица, ОдиночнаяЗапись); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьЗапись"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["id"]).Равно(ОдиночнаяЗапись); - + Текст = "Тестовый комментарий"; Результат = OPI_Airtable.СоздатьКомментарий(Токен, База, Таблица, ОдиночнаяЗапись, Текст); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьКомментарий"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["text"]).Равно(Текст); - + Коммент = Результат["id"]; Текст = "Тестовый комментарий (изм.)"; Результат = OPI_Airtable.ИзменитьКомментарий(Токен, База, Таблица, ОдиночнаяЗапись, Коммент, Текст); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьКомментарий"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["text"]).Равно(Текст); - + Результат = OPI_Airtable.ПолучитьКомментарии(Токен, База, Таблица, ОдиночнаяЗапись); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьКомментарии"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["comments"]).ИмеетТип("Массив"); - + Результат = OPI_Airtable.УдалитьКомментарий(Токен, База, Таблица, ОдиночнаяЗапись, Коммент); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьКомментарий"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["deleted"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["id"]).Равно(Коммент); - + Результат = OPI_Airtable.ПолучитьСписокЗаписей(Токен, База, Таблица); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокЗаписей"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["records"]).ИмеетТип("Массив"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["records"]).Заполнено(); - + Результат = OPI_Airtable.УдалитьЗаписи(Токен, База, Таблица, МассивУдаляемых); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьЗаписи"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["records"]).ИмеетТип("Массив"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["records"]).Заполнено(); - + Результат = OPI_Airtable.УдалитьЗаписи(Токен, База, Таблица, ОдиночнаяЗапись); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьЗаписи (одна)"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["records"]).ИмеетТип("Массив"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["records"]).Заполнено(); - + КонецПроцедуры #КонецОбласти @@ -2729,29 +2729,29 @@ #Область Dropbox Процедура ДропБокс_ПолучитьОбновитьТокен() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Dropbox_Appkey" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Dropbox_Appsecret", ПараметрыТеста); - - Dropbox_ПолучитьСсылкуАвторизации(ПараметрыТеста); - + + Dropbox_ПолучитьСсылкуАвторизации(ПараметрыТеста); + OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Dropbox_Code", ПараметрыТеста); Dropbox_ПолучитьТокен(ПараметрыТеста); - + OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Dropbox_Refresh", ПараметрыТеста); - + Dropbox_ОбновитьТокен(ПараметрыТеста); - + КонецПроцедуры Процедура ДропБокс_ЗагрузитьФайл() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Dropbox_Token", ПараметрыТеста); - OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture", ПараметрыТеста); - + OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture" , ПараметрыТеста); + Dropbox_ЗагрузитьФайл(ПараметрыТеста); Dropbox_ПолучитьИнформациюОбОбъекте(ПараметрыТеста); Dropbox_ПолучитьСписокВерсийОбъекта(ПараметрыТеста); @@ -2761,73 +2761,73 @@ Dropbox_ПереместитьОбъект(ПараметрыТеста); Dropbox_КопироватьОбъект(ПараметрыТеста); Dropbox_УдалитьОбъект(ПараметрыТеста); - + КонецПроцедуры Процедура ДропБокс_СоздатьКаталог() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Dropbox_Token", ПараметрыТеста); - + Dropbox_СоздатьПапку(ПараметрыТеста); Dropbox_СкачатьПапку(ПараметрыТеста); - + КонецПроцедуры Процедура ДропБокс_ПолучитьСписокФайловПапки() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Dropbox_Token", ПараметрыТеста); - + Dropbox_ПолучитьСписокФайловПапки(ПараметрыТеста); - + КонецПроцедуры Процедура ДропБокс_ЗагрузитьФайлПоURL() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Dropbox_Token", ПараметрыТеста); - OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Document", ПараметрыТеста); - + OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Document" , ПараметрыТеста); + Dropbox_ЗагрузитьФайлПоURL(ПараметрыТеста); Dropbox_ПолучитьСтатусЗагрузкиПоURL(ПараметрыТеста); - + КонецПроцедуры Процедура ДропБокс_СоздатьУдалитьТег() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Dropbox_Token", ПараметрыТеста); - + Dropbox_ДобавитьТег(ПараметрыТеста); Dropbox_ПолучитьСписокТегов(ПараметрыТеста); Dropbox_УдалитьТег(ПараметрыТеста); - + КонецПроцедуры Процедура ДропБокс_ПолучитьАккаунт() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Dropbox_Token", ПараметрыТеста); - + Dropbox_ПолучитьИнформациюОбАккаунте(ПараметрыТеста); Dropbox_ПолучитьДанныеИспользованияПространства(ПараметрыТеста); - + КонецПроцедуры Процедура ДропБокс_РаботаСДоступами() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Dropbox_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Dropbox_OtherUser", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Dropbox_FileID" , ПараметрыТеста); - + Dropbox_ДобавитьПользователейКФайлу(ПараметрыТеста); Dropbox_ОпубликоватьПапку(ПараметрыТеста); Dropbox_ДобавитьПользователейКПапке(ПараметрыТеста); Dropbox_ОтменитьПубликациюПапки(ПараметрыТеста); Dropbox_ОтменитьПубликациюФайла(ПараметрыТеста); - + КонецПроцедуры #КонецОбласти @@ -2835,37 +2835,37 @@ #Область Bitrix24 Процедура Б24_РаботаСТокеном() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Domain" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_ClientID" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_ClientSecret", ПараметрыТеста); - + Bitrix24_ПолучитьСсылкуАвторизацииПриложения(ПараметрыТеста); - + OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Code", ПараметрыТеста); - + Bitrix24_ПолучитьТокен(ПараметрыТеста); - + OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Refresh", ПараметрыТеста); - + Bitrix24_ОбновитьТокен(ПараметрыТеста); - + КонецПроцедуры Процедура Б24_СерверноеВремя() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_URL" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Domain", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Token" , ПараметрыТеста); - - Bitrix24_СерверноеВремя(ПараметрыТеста); + + Bitrix24_СерверноеВремя(ПараметрыТеста); КонецПроцедуры Процедура Б24_РаботаСНовостями() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_URL" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Domain", ПараметрыТеста); @@ -2880,18 +2880,18 @@ Bitrix24_ДобавитьКомментарийНовости(ПараметрыТеста); Bitrix24_ДобавитьПолучателейКНовости(ПараметрыТеста); Bitrix24_УдалитьНовость(ПараметрыТеста); - + КонецПроцедуры Процедура Б24_РаботаСЗадачами() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_URL" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Domain", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Token" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_UserID", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture" , ПараметрыТеста); - + Bitrix24_ПолучитьСтруктуруЗадачи(ПараметрыТеста); Bitrix24_СоздатьЗадачу(ПараметрыТеста); Bitrix24_СоздатьЗависимостьЗадач(ПараметрыТеста); @@ -2910,7 +2910,7 @@ Bitrix24_НачатьВыполнениеЗадачи(ПараметрыТеста); Bitrix24_НачатьНаблюдатьЗаЗадачей(ПараметрыТеста); Bitrix24_ПрекратитьНаблюдатьЗаЗадачей(ПараметрыТеста); - Bitrix24_ПриостановитьЗадачу(ПараметрыТеста); + Bitrix24_ПриостановитьЗадачу(ПараметрыТеста); Bitrix24_ПолучитьИсториюЗадачи(ПараметрыТеста); Bitrix24_ПолучитьСписокЗадач(ПараметрыТеста); Bitrix24_ПроверитьДоступКЗадаче(ПараметрыТеста); @@ -2922,29 +2922,29 @@ Bitrix24_ВозобновитьЭлементЧеклистаЗадачи(ПараметрыТеста); Bitrix24_УдалитьЭлементЧеклистаЗадачи(ПараметрыТеста); Bitrix24_ПолучитьПланЗадачНаДень(ПараметрыТеста); - + Наименование = "Картинка задачи.jpg"; - Картинка = ПараметрыТеста["Picture"]; + Картинка = ПараметрыТеста["Picture"]; IDПриемника = 3; - + URL = ПараметрыТеста["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ЗагрузитьФайлВХранилище(URL, Наименование, Картинка, IDПриемника); - IDФайла = Результат["result"]["ID"]; - - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_TaskFileID", IDФайла); + IDФайла = Результат["result"]["ID"]; + + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_TaskFileID", IDФайла); ПараметрыТеста.Вставить("Bitrix24_TaskFileID", IDФайла); - - Bitrix24_ДобавитьФайлВЗадачу(ПараметрыТеста); - + + Bitrix24_ДобавитьФайлВЗадачу(ПараметрыТеста); + OPI_Bitrix24.УдалитьФайл(URL, IDФайла); - + Bitrix24_УдалитьЗадачу(ПараметрыТеста); - + КонецПроцедуры Процедура Б24_РаботаСДиском() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_URL" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Domain", ПараметрыТеста); @@ -2979,7 +2979,7 @@ Bitrix24_ПоместитьКаталогВКорзину(ПараметрыТеста); Bitrix24_ВосстановитьКаталог(ПараметрыТеста); Bitrix24_УдалитьКаталог(ПараметрыТеста); - + КонецПроцедуры Процедура Б24_РаботаСКомментариями() Экспорт @@ -2988,25 +2988,25 @@ OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_URL" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Domain", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Token" , ПараметрыТеста); - + ТекущаяДата = OPI_Инструменты.ПолучитьТекущуюДату(); Час = 3600; Сутки = 24; Исполнитель = 1; - + СтруктураЗадачи = Новый Структура; СтруктураЗадачи.Вставить("TITLE" , "Новая задача"); СтруктураЗадачи.Вставить("DESCRIPTION" , "Новое описание задачи"); СтруктураЗадачи.Вставить("PRIORITY" , "2"); СтруктураЗадачи.Вставить("DEADLINE" , ТекущаяДата + Час * Сутки); СтруктураЗадачи.Вставить("RESPONSIBLE_ID", Исполнитель); - + URL = ПараметрыТеста["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.СоздатьЗадачу(URL, СтруктураЗадачи); - IDЗадачи = Результат["result"]["task"]["id"]; - - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_CommentsTaskID", IDЗадачи); + IDЗадачи = Результат["result"]["task"]["id"]; + + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_CommentsTaskID", IDЗадачи); ПараметрыТеста.Вставить("Bitrix24_CommentsTaskID", IDЗадачи); Bitrix24_ДобавитьКомментарийЗадачи(ПараметрыТеста); @@ -3017,9 +3017,9 @@ Bitrix24_ПолучитьСписокКомментариевЗадачи(ПараметрыТеста); Bitrix24_ПолучитьКомменатрийЗадачи(ПараметрыТеста); Bitrix24_УдалитьКомментарийЗадачи(ПараметрыТеста); - - OPI_Bitrix24.УдалитьЗадачу(URL, IDЗадачи); - + + OPI_Bitrix24.УдалитьЗадачу(URL, IDЗадачи); + КонецПроцедуры Процедура Б24_УчетРабочегоВремени() Экспорт @@ -3028,25 +3028,25 @@ OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_URL" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Domain", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Token" , ПараметрыТеста); - + ТекущаяДата = OPI_Инструменты.ПолучитьТекущуюДату(); Час = 3600; Сутки = 24; Исполнитель = 1; - + СтруктураЗадачи = Новый Структура; СтруктураЗадачи.Вставить("TITLE" , "Новая задача"); СтруктураЗадачи.Вставить("DESCRIPTION" , "Новое описание задачи"); СтруктураЗадачи.Вставить("PRIORITY" , "2"); СтруктураЗадачи.Вставить("DEADLINE" , ТекущаяДата + Час * Сутки); СтруктураЗадачи.Вставить("RESPONSIBLE_ID", Исполнитель); - + URL = ПараметрыТеста["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.СоздатьЗадачу(URL, СтруктураЗадачи); - IDЗадачи = Результат["result"]["task"]["id"]; - - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_ElapsedTaskID", IDЗадачи); + IDЗадачи = Результат["result"]["task"]["id"]; + + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_ElapsedTaskID", IDЗадачи); ПараметрыТеста.Вставить("Bitrix24_ElapsedTaskID", IDЗадачи); Bitrix24_ДобавитьТрудозатратыЗадачи(ПараметрыТеста); @@ -3054,51 +3054,51 @@ Bitrix24_ПолучитьСписокТрудозатратЗадачи(ПараметрыТеста); Bitrix24_ИзменитьТрудозатратыЗадачи(ПараметрыТеста); Bitrix24_УдалитьТрудозатратыЗадачи(ПараметрыТеста); - - OPI_Bitrix24.УдалитьЗадачу(URL, IDЗадачи); - + + OPI_Bitrix24.УдалитьЗадачу(URL, IDЗадачи); + КонецПроцедуры Процедура Б24_Канбан() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_URL" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Domain", ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Token" , ПараметрыТеста); - + ТекущаяДата = OPI_Инструменты.ПолучитьТекущуюДату(); Час = 3600; Сутки = 24; Исполнитель = 1; - + СтруктураЗадачи = Новый Структура; СтруктураЗадачи.Вставить("TITLE" , "Новая задача"); СтруктураЗадачи.Вставить("DESCRIPTION" , "Новое описание задачи"); СтруктураЗадачи.Вставить("PRIORITY" , "2"); СтруктураЗадачи.Вставить("DEADLINE" , ТекущаяДата + Час * Сутки); СтруктураЗадачи.Вставить("RESPONSIBLE_ID", Исполнитель); - + URL = ПараметрыТеста["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.СоздатьЗадачу(URL, СтруктураЗадачи); - IDЗадачи = Результат["result"]["task"]["id"]; - - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_KanbanTaskID", IDЗадачи); + IDЗадачи = Результат["result"]["task"]["id"]; + + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_KanbanTaskID", IDЗадачи); ПараметрыТеста.Вставить("Bitrix24_KanbanTaskID", IDЗадачи); - + Bitrix24_ДобавитьСтадиюКанбана(ПараметрыТеста); Bitrix24_ПолучитьСтадииКанбана(ПараметрыТеста); Bitrix24_ПеренестиЗадачуВСтадиюКанбана(ПараметрыТеста); Bitrix24_ИзменитьСтадиюКанбана(ПараметрыТеста); - - OPI_Bitrix24.УдалитьЗадачу(URL, IDЗадачи); - + + OPI_Bitrix24.УдалитьЗадачу(URL, IDЗадачи); + Bitrix24_УдалитьСтадиюКанбана(ПараметрыТеста); - + КонецПроцедуры Процедура Б24_РаботаСЧатами() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_URL" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Domain", ПараметрыТеста); @@ -3106,7 +3106,7 @@ OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture2" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Document" , ПараметрыТеста); - + Bitrix24_ПолучитьСтатусПользователя(ПараметрыТеста); Bitrix24_УстановитьСтатусПользователя(ПараметрыТеста); Bitrix24_ПолучитьПользователей(ПараметрыТеста); @@ -3134,11 +3134,11 @@ Bitrix24_ПрочитатьВсе(ПараметрыТеста); Bitrix24_СменитьВладельцаЧата(ПараметрыТеста); Bitrix24_ПокинутьЧат(ПараметрыТеста); - + КонецПроцедуры Процедура Б24_РаботаСУведомлениями() Экспорт - + ПараметрыТеста = Новый Структура; OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_URL" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Bitrix24_Domain", ПараметрыТеста); @@ -3146,11 +3146,11 @@ OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Picture2" , ПараметрыТеста); OPI_ПолучениеДанныхТестов.ПараметрВКоллекцию("Document" , ПараметрыТеста); - + Bitrix24_СоздатьПерсональноеУведомление(ПараметрыТеста); Bitrix24_СоздатьСистемноеУведомление(ПараметрыТеста); Bitrix24_УдалитьУведомление(ПараметрыТеста); - + КонецПроцедуры #КонецОбласти @@ -3161,24 +3161,24 @@ #Область СлужебныеПроцедурыИФункции -Функция ПолучитьПараметрыВК() - +Функция ПолучитьПараметрыВК() + Параметры = Новый Структура; НомерГруппы = OPI_ПолучениеДанныхТестов.ПолучитьПараметр("VK_GroupID"); - + Параметры.Вставить("access_token" , OPI_ПолучениеДанныхТестов.ПолучитьПараметр("VK_Token")); Параметры.Вставить("owner_id" , "-" + НомерГруппы); Параметры.Вставить("app_id" , OPI_ПолучениеДанныхТестов.ПолучитьПараметр("VK_AppID")); Параметры.Вставить("group_id" , НомерГруппы); - + Возврат Параметры; - + КонецФункции -Функция ПолучитьПараметрыТвиттер() - +Функция ПолучитьПараметрыТвиттер() + Параметры = Новый Соответствие; - + Параметры.Вставить("redirect_uri" , OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Twitter_Redirect")); Параметры.Вставить("client_id" , OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Twitter_ClinetID")); Параметры.Вставить("client_secret" , OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Twitter_ClientSecret")); @@ -3186,102 +3186,102 @@ Параметры.Вставить("refresh_token" , OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Twitter_Refresh")); Параметры.Вставить("oauth_token" , OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Twitter_OAuthToken")); Параметры.Вставить("oauth_token_secret" , OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Twitter_OAuthSecret")); - - Параметры.Вставить("oauth_consumer_key" + + Параметры.Вставить("oauth_consumer_key" , OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Twitter_OAuthConsumerKey")); - Параметры.Вставить("oauth_consumer_secret" + Параметры.Вставить("oauth_consumer_secret" , OPI_ПолучениеДанныхТестов.ПолучитьПараметр("Twitter_OAuthConsumerSecret")); Возврат Параметры; - + КонецФункции #Область Проверки -Процедура Проверка_Пусто(Знач Результат) +Процедура Проверка_Пусто(Знач Результат) OPI_ПолучениеДанныхТестов.ОжидаетЧто(ЗначениеЗаполнено(Результат)).Равно(Ложь); КонецПроцедуры -Процедура Проверка_Строка(Знач Результат) - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Строка"); +Процедура Проверка_Строка(Знач Результат) + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Строка"); КонецПроцедуры Процедура Проверка_ДвоичныеДанные(Знач Результат, Знач Размер = Неопределено) - + МинимальныйРазмер = 500000; - - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("ДвоичныеДанные"); - + + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("ДвоичныеДанные"); + Если Не Размер = Неопределено Тогда - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат.Размер() >= Размер).Равно(Истина); + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат.Размер() >= Размер).Равно(Истина); Иначе OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат.Размер() > МинимальныйРазмер).Равно(Истина); КонецЕсли; - + КонецПроцедуры Процедура Проверка_Массив(Знач Результат, Знач Количество = Неопределено) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Массив"); - + Если Не Количество = Неопределено Тогда - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетДлину(Количество); - КонецЕсли; - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетДлину(Количество); + КонецЕсли; + КонецПроцедуры Процедура Проверка_Соответствие(Знач Результат) - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); + КонецПроцедуры Процедура Проверка_Структура(Знач Результат) OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Структура").Заполнено(); - + КонецПроцедуры Процедура Проверка_ТелеграмИстина(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).Равно(Истина); - + КонецПроцедуры Процедура Проверка_ТелеграмИнформацияБота(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["username"]).Заполнено(); - + КонецПроцедуры Процедура Проверка_ТелеграмМассив(Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие") .Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Массив"); - + КонецПроцедуры Процедура Проверка_ТелеграмУстановкаВебхук(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["description"]).Равно("Webhook was set"); - + КонецПроцедуры Процедура Проверка_ТелеграмУдалениеВебхук(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["description"]).Заполнено(); - + КонецПроцедуры Процедура Проверка_ТелеграмСообщение(Знач Результат, Знач Текст) @@ -3289,16 +3289,16 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["text"]).Равно(Текст); - + КонецПроцедуры Процедура Проверка_ТелеграмКартинка(Знач Результат, Знач Текст) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие") .Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["caption"]).Равно(Текст); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["photo"]).ИмеетТип("Массив"); - + КонецПроцедуры Процедура Проверка_ТелеграмВидео(Знач Результат, Знач Текст) @@ -3307,7 +3307,7 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["caption"]).Равно(Текст); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["video"]["mime_type"]).Равно("video/mp4"); - + КонецПроцедуры Процедура Проверка_ТелеграмАудио(Знач Результат, Знач Текст) @@ -3316,7 +3316,7 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["caption"]).Равно(Текст); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["audio"]["mime_type"]).Равно("audio/mpeg"); - + КонецПроцедуры Процедура Проверка_ТелеграмДокумент(Знач Результат, Знач Текст) @@ -3324,20 +3324,20 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["caption"]).Равно(Текст); - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["document"]).ИмеетТип("Соответствие").Заполнено(); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["document"]).ИмеетТип("Соответствие").Заполнено(); + КонецПроцедуры Процедура Проверка_ТелеграмГифка(Знач Результат, Знач Текст) Result_ = "result"; - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Result_]["caption"]).Равно(Текст); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Result_]["document"]).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Result_]["animation"]["mime_type"]).Равно("video/mp4"); - + КонецПроцедуры Процедура Проверка_ТелеграмМедиагруппа(Знач Результат) @@ -3345,15 +3345,15 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Массив"); - + КонецПроцедуры Процедура Проверка_ТелеграмМестоположение(Знач Результат) OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["location"]).ИмеетТип("Соответствие").Заполнено(); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["location"]).ИмеетТип("Соответствие").Заполнено(); + КонецПроцедуры Процедура Проверка_ТелеграмКонтакт(Знач Результат, Знач Имя) @@ -3362,7 +3362,7 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["contact"]).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["contact"]["first_name"]).Равно(Имя); - + КонецПроцедуры Процедура Проверка_ТелеграмОпрос(Знач Результат, Знач Вопрос) @@ -3371,22 +3371,22 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["poll"]).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["poll"]["question"]).Равно(Вопрос); - + КонецПроцедуры Процедура Проверка_ТелеграмПереслать(Знач Результат, Знач IDСообщения) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["forward_origin"]["message_id"]).Равно(Число(IDСообщения)); - + КонецПроцедуры Процедура Проверка_ТелеграмБан(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["description"]).Равно("Bad Request: can't remove chat owner"); - + КонецПроцедуры Процедура Проверка_ТелеграмПриглашение(Знач Результат, Знач Заголовок, Знач UnixИстечение) @@ -3397,7 +3397,7 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Result_]["member_limit"]).Равно(200); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Result_]["name"]).Равно(Заголовок); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Result_]["expire_date"]).Равно(Число(UnixИстечение)); - + КонецПроцедуры Процедура Проверка_ТелеграмЧисло(Знач Результат) @@ -3405,7 +3405,7 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Число"); - + КонецПроцедуры Процедура Проверка_ТелеграмСозданиеТемы(Знач Результат, Знач Имя, Иконка) @@ -3414,60 +3414,60 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["name"]).Равно(Имя); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["icon_custom_emoji_id"]).Равно(Иконка); - + КонецПроцедуры Процедура Проверка_ВКПост(Знач Результат) OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["post_id"]).ИмеетТип("Число").Заполнено(); - + КонецПроцедуры Процедура Проверка_ВКИстина(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]).ИмеетТип("Число").Равно(1); - + КонецПроцедуры Процедура Проверка_ВКАльбом(Знач Результат, Знач Описание) OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["description"]).Равно(Описание); - + КонецПроцедуры Процедура Проверка_ВККартинкаАльбома(Знач Результат, Знач ОписаниеКартинки, Знач ИДАльбома) Response = "response"; - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Response][0]["text"]).Равно(ОписаниеКартинки); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат[Response][0]["album_id"]).Равно(ИДАльбома); - + КонецПроцедуры Процедура Проверка_ВКИстория(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["count"]).ИмеетТип("Число").Равно(1); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["items"]).ИмеетТип("Массив").Заполнено(); - + КонецПроцедуры Процедура Проверка_ВКОбсуждение(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]).ИмеетТип("Число").Заполнено(); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]).ИмеетТип("Число").Заполнено(); + КонецПроцедуры Процедура Проверка_ВКЛайк(Знач Результат) OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["likes"]).ИмеетТип("Число").Заполнено(); - + КонецПроцедуры Процедура Проверка_ВКРепост(Знач Результат) @@ -3475,37 +3475,37 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["success"]).ИмеетТип("Число").Равно(1); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["wall_repost_count"]).ИмеетТип("Число").Равно(1); - + КонецПроцедуры Процедура Проверка_ВККомментарий(Знач Результат) OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["comment_id"]).ИмеетТип("Число").Заполнено(); - + КонецПроцедуры Процедура Проверка_ВКСтатистика(Знач Результат) - + ТипСоответствие = "Соответствие"; - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип(ТипСоответствие).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"][0]["visitors"]).ИмеетТип(ТипСоответствие).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"][0]["reach"]).ИмеетТип(ТипСоответствие).Заполнено(); - + КонецПроцедуры Процедура Проверка_ВКСтатистикаПостов(Знач Результат) OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Массив").ИмеетДлину(2); - + КонецПроцедуры Процедура Проверка_ВКЧисло(Знач Результат) - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие"); + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]).ИмеетТип("Число").Заполнено(); - + КонецПроцедуры Процедура Проверка_ВКПодборка(Знач Результат) @@ -3513,59 +3513,59 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["albums_count"]).ИмеетТип("Число").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["market_album_id"]).ИмеетТип("Число").Заполнено(); - + КонецПроцедуры Процедура Проверка_ВКТовар(Знач Результат) OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["market_item_id"]).ИмеетТип("Число").Заполнено(); - + КонецПроцедуры Процедура Проверка_ВКСвойство(Знач Результат) OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["property_id"]).ИмеетТип("Число").Заполнено(); - + КонецПроцедуры Процедура Проверка_ВКВариантСвойства(Знач Результат) OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["variant_id"]).ИмеетТип("Число").Заполнено(); - + КонецПроцедуры Процедура Проверка_ВКИНформацияОТоварах(Знач Результат) OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["items"]).ИмеетТип("Массив").ИмеетДлину(2); - + КонецПроцедуры Процедура Проверка_ВКГруппаТоваров(Знач Результат) OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["response"]["item_group_id"]).ИмеетТип("Число").Заполнено(); - + КонецПроцедуры Процедура Проверка_ВКВидео(Знач Результат) OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["video_id"]).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["video_hash"]).Заполнено(); - + КонецПроцедуры Процедура Проверка_ЯДискДиск(Знач Результат) Соответствие_ = "Соответствие"; - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип(Соответствие_).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["system_folders"]).ИмеетТип(Соответствие_); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["user"]).ИмеетТип(Соответствие_); - + КонецПроцедуры Процедура Проверка_ЯДискКаталог(Знач Результат, Знач Путь) @@ -3573,69 +3573,69 @@ OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["type"]).Равно("dir"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["path"]).Равно("disk:" + Путь); - + КонецПроцедуры Процедура Проверка_ГКОбъект(Знач Результат, Знач Наименование, Знач Описание) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["summary"]).Равно(Наименование); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["description"]).Равно(Описание); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["id"]).ИмеетТип("Строка").Заполнено(); - + КонецПроцедуры Процедура Проверка_ТвиттерТекст(Знач Результат, Знач Текст) - + ТекстОтвета = Результат["data"]["text"]; ТекстОтвета = Лев(ТекстОтвета, СтрДлина(Текст)); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(ТекстОтвета).Равно(Текст); КонецПроцедуры Процедура Проверка_ВайберОк(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["status_message"]).Равно("ok"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["status"]).Равно(0); КонецПроцедуры Процедура Проверка_НоушнОбъект(Знач Результат, Знач Вид = "page") - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["object"]).Равно(Вид); - + КонецПроцедуры Процедура Проверка_СлакОк(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["ok"]).Равно(Истина); КонецПроцедуры Процедура Проверка_ДропБоксФайл(Знач Результат, Знач Путь) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["path_display"]).Равно(Путь); - + КонецПроцедуры Процедура Проверка_ДропБоксМетаданные(Знач Результат, Знач Путь) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["metadata"]["path_display"]).Равно(Путь); - + КонецПроцедуры Процедура Проверка_ДропБоксМассив(Знач Результат, Знач Количество = Неопределено) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["entries"]).ИмеетТип("Массив"); - + Если Не Количество = Неопределено Тогда OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["entries"].Количество()).Равно(Количество); КонецЕсли; - + КонецПроцедуры Процедура Проверка_ДропБоксРабота(Знач Результат) @@ -3647,10 +3647,10 @@ КонецПроцедуры Процедура Проверка_ДропБоксТеги(Знач Результат, Знач Количество) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["paths_to_tags"]).ИмеетТип("Массив"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["paths_to_tags"].Количество()).Равно(Количество); - + КонецПроцедуры Процедура Проверка_ДропбоксАккаунт(Знач Результат) @@ -3673,38 +3673,38 @@ КонецПроцедуры Процедура Проверка_БитриксВремя(Знач Результат) - + Время = Результат["result"]; - + Если Не ТипЗнч(Время) = Тип("Дата") Тогда Время = XMLЗначение(Тип("Дата"), Время); КонецЕсли; - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Время).ИмеетТип("Дата").Заполнено(); - + КонецПроцедуры Процедура Проверка_БитриксАвторизация(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["access_token"]).Заполнено(); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["refresh_token"]).Заполнено(); КонецПроцедуры Процедура Проверка_БитриксЧисло(Знач Результат) - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Число").Заполнено(); + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Число").Заполнено(); КонецПроцедуры Процедура Проверка_БитриксИстина(Знач Результат) - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Булево").Равно(Истина); -КонецПроцедуры + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Булево").Равно(Истина); +КонецПроцедуры Процедура Проверка_БитриксБулево(Знач Результат) - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Булево"); + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Булево"); КонецПроцедуры Процедура Проверка_БитриксСтрока(Знач Результат) - OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Строка").Заполнено(); + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Строка").Заполнено(); КонецПроцедуры Процедура Проверка_БитриксМассив(Знач Результат) @@ -3720,22 +3720,22 @@ КонецПроцедуры Процедура Проверка_БитриксМассивОбъектов(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Массив"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"][0]["ID"]).Заполнено(); - + КонецПроцедуры Процедура Проверка_БитриксПоля(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["fields"]).Заполнено(); - + КонецПроцедуры Процедура Проверка_БитриксЗадача(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["task"]).Заполнено(); - + КонецПроцедуры Процедура Проверка_БитриксСписокЗадач(Знач Результат) @@ -3758,75 +3758,75 @@ КонецПроцедуры Процедура Проверка_БитриксДоступныеДействия(Знач Результат, Знач Количество) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Соответствие"); - + Действия = Результат["result"]["allowedActions"]; OPI_ПолучениеДанныхТестов.ОжидаетЧто(Действия).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Действия.Количество()).Равно(Количество); - + КонецПроцедуры Процедура Проверка_БитриксКомментарий(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["POST_MESSAGE"]).Заполнено(); - + КонецПроцедуры Процедура Проверка_БитриксРезультат(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["text"]).Заполнено(); КонецПроцедуры Процедура Проверка_БитриксНеопределено(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Неопределено"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["time"]).Заполнено(); КонецПроцедуры Процедура Проверка_БитриксСписокКомментариев(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Массив"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"][0]["POST_MESSAGE"]).Заполнено(); - + КонецПроцедуры Процедура Проверка_БитриксСписокРезультатов(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Массив"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"][0]["text"]).Заполнено(); - + КонецПроцедуры Процедура Проверка_БитриксСообщения(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["messages"]).ИмеетТип("Массив"); - + КонецПроцедуры Процедура Проверка_БитриксДиалог(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["dialogId"]).Заполнено(); - + КонецПроцедуры Процедура Проверка_БитриксСообщение(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["id"]).Заполнено(); - + КонецПроцедуры Процедура Проверка_БитриксФайлСообщение(Знач Результат) - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]).ИмеетТип("Соответствие"); OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат["result"]["MESSAGE_ID"]).Заполнено(); - + КонецПроцедуры #КонецОбласти @@ -3839,90 +3839,90 @@ Токен = ПараметрыФункции["Telegram_Token"]; Результат = OPI_Telegram.ПолучитьИнформациюБота(Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИнформациюБота", "Telegram"); - + Проверка_ТелеграмИнформацияБота(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ПолучитьОбновления(ПараметрыФункции) - - Токен = ПараметрыФункции["Telegram_Token"]; + + Токен = ПараметрыФункции["Telegram_Token"]; Результат = OPI_Telegram.ПолучитьОбновления(Токен); // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьОбновления", "Telegram"); - + Проверка_ТелеграмМассив(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_УстановитьWebhook(ПараметрыФункции) - + Токен = ПараметрыФункции["Telegram_Token"]; URL = ПараметрыФункции["Telegram_URL"]; - + Результат = OPI_Telegram.УстановитьWebhook(Токен, URL); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УстановитьWebhook", "Telegram"); - + Проверка_ТелеграмУстановкаВебхук(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_УдалитьWebhook(ПараметрыФункции) - + Токен = ПараметрыФункции["Telegram_Token"]; Результат = OPI_Telegram.УдалитьWebhook(Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьWebhook", "Telegram"); - + Проверка_ТелеграмУдалениеВебхук(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ОтправитьТекстовоеСообщение(ПараметрыФункции) - + Токен = ПараметрыФункции["Telegram_Token"]; IDЧата = ПараметрыФункции["Telegram_ChatID"]; - IDКанала = ПараметрыФункции["Telegram_ChannelID"]; + IDКанала = ПараметрыФункции["Telegram_ChannelID"]; Текст = ПараметрыФункции["String"]; - + Результат = OPI_Telegram.ОтправитьТекстовоеСообщение(Токен, IDЧата, Текст); - - // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьТекстовоеСообщение", "Telegram"); - + + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьТекстовоеСообщение", "Telegram"); + Проверка_ТелеграмСообщение(Результат, Текст); // SKIP - + Результат = OPI_Telegram.ОтправитьТекстовоеСообщение(Токен, IDКанала, Текст); - + // END - - // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьТекстовоеСообщение (канал)"); - + + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьТекстовоеСообщение (канал)"); + Проверка_ТелеграмСообщение(Результат, Текст); - + IDСообщения = OPI_Инструменты.ЧислоВСтроку(Результат["result"]["message_id"]); OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Telegram_ChannelMessageID", IDСообщения); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ОтправитьКартинку(ПараметрыФункции) @@ -3931,42 +3931,42 @@ IDЧата = ПараметрыФункции["Telegram_ChatID"]; IDКанала = ПараметрыФункции["Telegram_ChannelID"]; Текст = ПараметрыФункции["String"]; - Картинка = ПараметрыФункции["Picture"]; - + Картинка = ПараметрыФункции["Picture"]; + КартинкаПуть = ПолучитьИмяВременногоФайла("png"); КопироватьФайл(Картинка, КартинкаПуть); - + КартинкаДД = Новый ДвоичныеДанные(КартинкаПуть); - + Результат = OPI_Telegram.ОтправитьКартинку(Токен, IDЧата, Текст, Картинка); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьКартинку", "Telegram"); - + Проверка_ТелеграмКартинка(Результат, Текст); // SKIP - + Результат = OPI_Telegram.ОтправитьКартинку(Токен, IDКанала, Текст, КартинкаПуть); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьКартинку (Путь)"); - + Проверка_ТелеграмКартинка(Результат, Текст); // SKIP - + Результат = OPI_Telegram.ОтправитьКартинку(Токен, IDКанала, Текст, КартинкаДД); - - // END - + + // END + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьКартинку (ДД)"); - + Проверка_ТелеграмКартинка(Результат, Текст); - + УдалитьФайлы(КартинкаПуть); - + IDФайла = Результат["result"]["photo"][0]["file_id"]; OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Telegram_FileID", IDФайла); - + ПараметрыФункции.Вставить("Telegram_FileID", IDФайла); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ОтправитьВидео(ПараметрыФункции) @@ -3976,41 +3976,41 @@ IDКанала = ПараметрыФункции["Telegram_ChannelID"]; Текст = ПараметрыФункции["String"]; Видео = ПараметрыФункции["Video"]; - + ВидеоПуть = ПолучитьИмяВременногоФайла("mp4"); КопироватьФайл(Видео, ВидеоПуть); - + ВидеоДД = Новый ДвоичныеДанные(ВидеоПуть); - + Результат = OPI_Telegram.ОтправитьВидео(Токен, IDЧата, Текст, Видео); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьВидео", "Telegram"); - + Проверка_ТелеграмВидео(Результат, Текст); // SKIP - + Результат = OPI_Telegram.ОтправитьВидео(Токен, IDКанала, Текст, ВидеоПуть); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьВидео (Путь)"); - + Проверка_ТелеграмВидео(Результат, Текст); // SKIP - + Результат = OPI_Telegram.ОтправитьВидео(Токен, IDКанала, Текст, ВидеоДД); - - // END - + + // END + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьВидео (ДД)"); - + Проверка_ТелеграмВидео(Результат, Текст); - + УдалитьФайлы(ВидеоПуть); - + IDФайла = Результат["result"]["video"]["file_id"]; OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Telegram_FileID", IDФайла); - + ПараметрыФункции.Вставить("Telegram_FileID", IDФайла); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ОтправитьАудио(ПараметрыФункции) @@ -4020,41 +4020,41 @@ IDКанала = ПараметрыФункции["Telegram_ChannelID"]; Текст = ПараметрыФункции["String"]; Аудио = ПараметрыФункции["Audio"]; - + АудиоПуть = ПолучитьИмяВременногоФайла("mp3"); КопироватьФайл(Аудио, АудиоПуть); - + АудиоДД = Новый ДвоичныеДанные(АудиоПуть); - + Результат = OPI_Telegram.ОтправитьАудио(Токен, IDЧата, Текст, Аудио); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьАудио", "Telegram"); - + Проверка_ТелеграмАудио(Результат, Текст); // SKIP - + Результат = OPI_Telegram.ОтправитьАудио(Токен, IDКанала, Текст, АудиоПуть); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьАудио (Путь)"); - + Проверка_ТелеграмАудио(Результат, Текст); // SKIP - + Результат = OPI_Telegram.ОтправитьАудио(Токен, IDКанала, Текст, АудиоДД); - - // END - + + // END + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьАудио (ДД)"); - + Проверка_ТелеграмАудио(Результат, Текст); - + УдалитьФайлы(АудиоПуть); - + IDФайла = Результат["result"]["audio"]["file_id"]; OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Telegram_FileID", IDФайла); - + ПараметрыФункции.Вставить("Telegram_FileID", IDФайла); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ОтправитьДокумент(ПараметрыФункции) @@ -4064,42 +4064,42 @@ IDКанала = ПараметрыФункции["Telegram_ChannelID"]; Текст = ПараметрыФункции["String"]; Документ = ПараметрыФункции["Document"]; - + ДокументПуть = ПолучитьИмяВременногоФайла("docx"); КопироватьФайл(Документ, ДокументПуть); - + ДокументДД = Новый ДвоичныеДанные(ДокументПуть); - + Результат = OPI_Telegram.ОтправитьДокумент(Токен, IDЧата, Текст, Документ); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьДокумент", "Telegram"); - + Проверка_ТелеграмДокумент(Результат, Текст); // SKIP - + Результат = OPI_Telegram.ОтправитьДокумент(Токен, IDЧата, Текст, Документ, , , "customname.docx"); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьДокумент (с именем)", "Telegram"); - + Проверка_ТелеграмДокумент(Результат, Текст); // SKIP - + Результат = OPI_Telegram.ОтправитьДокумент(Токен, IDКанала, Текст, ДокументПуть); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьДокумент (Путь)"); - + Проверка_ТелеграмДокумент(Результат, Текст); // SKIP - + Результат = OPI_Telegram.ОтправитьДокумент(Токен, IDКанала, Текст, ДокументДД, , , "customname.docx"); - - // END - + + // END + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьДокумент (ДД)"); - + Проверка_ТелеграмДокумент(Результат, Текст); - + УдалитьФайлы(ДокументПуть); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ОтправитьГифку(ПараметрыФункции) @@ -4109,36 +4109,36 @@ IDКанала = ПараметрыФункции["Telegram_ChannelID"]; Текст = ПараметрыФункции["String"]; Гифка = ПараметрыФункции["GIF"]; - + ГифкаПуть = ПолучитьИмяВременногоФайла("gif"); КопироватьФайл(Гифка, ГифкаПуть); - + ГифкаДД = Новый ДвоичныеДанные(ГифкаПуть); - + Результат = OPI_Telegram.ОтправитьГифку(Токен, IDЧата, Текст, Гифка); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьГифку", "Telegram"); - + Проверка_ТелеграмГифка(Результат, Текст); // SKIP - + Результат = OPI_Telegram.ОтправитьГифку(Токен, IDКанала, Текст, ГифкаПуть); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьГифку (Путь)"); - + Проверка_ТелеграмГифка(Результат, Текст); // SKIP - + Результат = OPI_Telegram.ОтправитьГифку(Токен, IDКанала, Текст, ГифкаДД); - - // END - + + // END + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьГифку (ДД)"); - + Проверка_ТелеграмГифка(Результат, Текст); - + УдалитьФайлы(ГифкаПуть); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ОтправитьМеидагруппу(ПараметрыФункции) @@ -4148,157 +4148,157 @@ Текст = ПараметрыФункции["String"]; Картинка = ПараметрыФункции["Picture"]; Видео = ПараметрыФункции["Video"]; - + КартинкаПуть = ПолучитьИмяВременногоФайла("png"); КопироватьФайл(Картинка, КартинкаПуть); - + ВидеоПуть = ПолучитьИмяВременногоФайла("mp4"); КопироватьФайл(Видео, ВидеоПуть); - + ВидеоДД = Новый ДвоичныеДанные(ВидеоПуть); - + Медиагруппа = Новый Соответствие; Медиагруппа.Вставить(КартинкаПуть, "photo"); Медиагруппа.Вставить(ВидеоДД , "video"); - + Результат = OPI_Telegram.ОтправитьМедиагруппу(Токен, IDЧата, Текст, Медиагруппа); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьМедиагруппу", "Telegram"); - + Проверка_ТелеграмМедиагруппа(Результат); - - ДокументURL = ПараметрыФункции["Document"]; + + ДокументURL = ПараметрыФункции["Document"]; ДокументПуть = ПолучитьИмяВременногоФайла("docx"); IDКанала = ПараметрыФункции["Telegram_ChannelID"]; - + КопироватьФайл(ДокументURL, ДокументПуть); - + МедиаГруппа = Новый Соответствие; Медиагруппа.Вставить(ДокументURL , "document"); - Медиагруппа.Вставить(ДокументПуть, "document"); - + Медиагруппа.Вставить(ДокументПуть, "document"); + Результат = OPI_Telegram.ОтправитьМедиагруппу(Токен, IDКанала, Текст, Медиагруппа); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьМедиагруппу (доки)", "Telegram"); - + Проверка_ТелеграмМедиагруппа(Результат); - + УдалитьФайлы(ВидеоПуть); УдалитьФайлы(КартинкаПуть); УдалитьФайлы(ДокументПуть); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ОтправитьМестоположение(ПараметрыФункции) - + Токен = ПараметрыФункции["Telegram_Token"]; IDЧата = ПараметрыФункции["Telegram_ChatID"]; - IDКанала = ПараметрыФункции["Telegram_ChannelID"]; + IDКанала = ПараметрыФункции["Telegram_ChannelID"]; Ширина = ПараметрыФункции["Lat"]; Долгота = ПараметрыФункции["Long"]; - + Результат = OPI_Telegram.ОтправитьМестоположение(Токен, IDЧата, Ширина, Долгота); - - // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьМестоположение", "Telegram"); - + + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьМестоположение", "Telegram"); + Проверка_ТелеграмМестоположение(Результат); // SKIP - + Результат = OPI_Telegram.ОтправитьМестоположение(Токен, IDКанала, Ширина, Долгота); - + // END - - // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьМестоположение (канал)"); - + + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьМестоположение (канал)"); + Проверка_ТелеграмМестоположение(Результат); OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ОтправитьКонтакт(ПараметрыФункции) Токен = ПараметрыФункции["Telegram_Token"]; IDЧата = ПараметрыФункции["Telegram_ChatID"]; - IDКанала = ПараметрыФункции["Telegram_ChannelID"]; + IDКанала = ПараметрыФункции["Telegram_ChannelID"]; Имя = ПараметрыФункции["Name"]; Фамилия = ПараметрыФункции["Surname"]; Телефон = ПараметрыФункции["Phone"]; - + Результат = OPI_Telegram.ОтправитьКонтакт(Токен, IDЧата , Имя, Фамилия, Телефон); - - // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьКонтакт", "Telegram"); - + + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьКонтакт", "Telegram"); + Проверка_ТелеграмКонтакт(Результат, Имя); // SKIP OPI_Инструменты.Пауза(20); // SKIP - + Результат = OPI_Telegram.ОтправитьКонтакт(Токен, IDКанала, Имя, Фамилия, Телефон); - + // END - - // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьКонтакт (канал)"); - + + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьКонтакт (канал)"); + Проверка_ТелеграмКонтакт(Результат, Имя); OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ОтправитьОпрос(ПараметрыФункции) Токен = ПараметрыФункции["Telegram_Token"]; IDЧата = ПараметрыФункции["Telegram_ChatID"]; - IDКанала = ПараметрыФункции["Telegram_ChannelID"]; + IDКанала = ПараметрыФункции["Telegram_ChannelID"]; Вопрос = "Какой ваш любимый цвет?"; - + МассивОтветов = Новый Массив; МассивОтветов.Добавить("Красный"); МассивОтветов.Добавить("Желтый"); МассивОтветов.Добавить("Зеленый"); МассивОтветов.Добавить("Синий"); - + Результат = OPI_Telegram.ОтправитьОпрос(Токен, IDЧата , Вопрос, МассивОтветов, Ложь); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьОпрос", "Telegram"); - + Проверка_ТелеграмОпрос(Результат, Вопрос); // SKIP - + Результат = OPI_Telegram.ОтправитьОпрос(Токен, IDКанала, Вопрос, МассивОтветов, Истина); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьОпрос (канал)"); - + Проверка_ТелеграмОпрос(Результат, Вопрос); // SKIP - + // END - + СтрочныйМассив = "['Красный', 'Желтый','Зеленый' ,'Синий']"; - + Результат = OPI_Telegram.ОтправитьОпрос(Токен, IDКанала, Вопрос, СтрочныйМассив, Истина); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьОпрос (строчный массив)"); - + Проверка_ТелеграмОпрос(Результат, Вопрос); OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_СкачатьФайл(ПараметрыФункции) - + IDФайла = ПараметрыФункции["Telegram_FileID"]; Токен = ПараметрыФункции["Telegram_Token"]; Результат = OPI_Telegram.СкачатьФайл(Токен, IDФайла); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СкачатьФайл", "Telegram"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("ДвоичныеДанные"); - + КонецПроцедуры Процедура Telegram_ПереслатьСообщение(ПараметрыФункции) @@ -4307,74 +4307,74 @@ IDЧата = ПараметрыФункции["Telegram_ChatID"]; IDКанала = ПараметрыФункции["Telegram_ChannelID"]; IDСообщения = ПараметрыФункции["Telegram_ChannelMessageID"]; - + Результат = OPI_Telegram.ПереслатьСообщение(Токен, IDСообщения, IDКанала, IDЧата); - + // END // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереслатьСообщение", "Telegram"); - + Проверка_ТелеграмПереслать(Результат, IDСообщения); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_Бан(ПараметрыФункции) - - Токен = ПараметрыФункции["Telegram_Token"]; + + Токен = ПараметрыФункции["Telegram_Token"]; IDПользователя = ПараметрыФункции["Telegram_ChatID"]; IDКанала = ПараметрыФункции["Telegram_ChannelID"]; - + Результат = OPI_Telegram.Бан(Токен, IDКанала, IDПользователя); // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "Бан", "Telegram"); - + Проверка_ТелеграмБан(Результат); OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_Разбан(ПараметрыФункции) - + Токен = ПараметрыФункции["Telegram_Token"]; IDПользователя = ПараметрыФункции["Telegram_ChatID"]; IDКанала = ПараметрыФункции["Telegram_ChannelID"]; - + Результат = OPI_Telegram.Разбан(Токен, IDКанала, IDПользователя); // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "Разбан", "Telegram"); - + Проверка_ТелеграмБан(Результат); OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_СоздатьСсылкуПриглашение(ПараметрыФункции) Токен = ПараметрыФункции["Telegram_Token"]; - IDКанала = ПараметрыФункции["Telegram_ChannelID"]; - Сутки = 86400; + IDКанала = ПараметрыФункции["Telegram_ChannelID"]; + Сутки = 86400; ТекущаяДата = OPI_Инструменты.ПолучитьТекущуюДату(); - Заголовок = "Ссылка " + Строка(ТекущаяДата); + Заголовок = "Ссылка " + Строка(ТекущаяДата); Истечение = ТекущаяДата + Сутки; UnixИстечение = OPI_Инструменты.UNIXTime(Истечение); - + Результат = OPI_Telegram.СоздатьСсылкуПриглашение(Токен, IDКанала, Заголовок, Истечение, 200); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьСсылкуПриглашение", "Telegram"); Проверка_ТелеграмПриглашение(Результат, Заголовок, UnixИстечение); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ЗакрепитьСообщение(ПараметрыФункции) @@ -4382,17 +4382,17 @@ Токен = ПараметрыФункции["Telegram_Token"]; IDКанала = ПараметрыФункции["Telegram_ChannelID"]; IDСообщения = ПараметрыФункции["Telegram_ChannelMessageID"]; - + Результат = OPI_Telegram.ЗакрепитьСообщение(Токен, IDКанала, IDСообщения); // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗакрепитьСообщение", "Telegram"); - + Проверка_ТелеграмИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ОткрепитьСообщение(ПараметрыФункции) @@ -4400,262 +4400,262 @@ Токен = ПараметрыФункции["Telegram_Token"]; IDКанала = ПараметрыФункции["Telegram_ChannelID"]; IDСообщения = ПараметрыФункции["Telegram_ChannelMessageID"]; - + Результат = OPI_Telegram.ОткрепитьСообщение(Токен, IDКанала, IDСообщения); // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОткрепитьСообщение", "Telegram"); - + Проверка_ТелеграмИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ПолучитьЧислоУчастников(ПараметрыФункции) - + Токен = ПараметрыФункции["Telegram_Token"]; IDКанала = ПараметрыФункции["Telegram_ChannelID"]; - + Результат = OPI_Telegram.ПолучитьЧислоУчастников(Токен, IDКанала); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьЧислоУчастников", "Telegram"); - + Проверка_ТелеграмЧисло(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ПолучитьСписокАватаровФорума(ПараметрыФункции) - + Токен = ПараметрыФункции["Telegram_Token"]; Результат = OPI_Telegram.ПолучитьСписокИконокАватаров(Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокИконокАватаров", "Telegram"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Соответствие").Заполнено(); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_СоздатьТемуФорума(ПараметрыФункции) - - Токен = ПараметрыФункции["Telegram_Token"]; + + Токен = ПараметрыФункции["Telegram_Token"]; Чат = ПараметрыФункции["Telegram_ForumID"]; Иконка = "5357419403325481346"; Имя = "Тестовая тема " + Строка(Новый УникальныйИдентификатор); - + Результат = OPI_Telegram.СоздатьТемуФорума(Токен, Чат, Имя, Иконка); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьТемуФорума", "Telegram"); - + Тема = Результат["result"]["message_thread_id"]; - + ПараметрыФункции.Вставить("Telegram_TopicID", Тема); OPI_Инструменты.ДобавитьПоле("Telegram_TopicID", Тема, "Строка", ПараметрыФункции); OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Telegram_TopicID", ПараметрыФункции["Telegram_TopicID"]); - + Проверка_ТелеграмСозданиеТемы(Результат, Имя, Иконка); - - ЧатТема = Чат + "*" + Тема; - Текст = ПараметрыФункции["String"]; + + ЧатТема = Чат + "*" + Тема; + Текст = ПараметрыФункции["String"]; Результат = OPI_Telegram.ОтправитьТекстовоеСообщение(Токен, ЧатТема, Текст); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьТекстовоеСообщение (форум)"); - + Проверка_ТелеграмСообщение(Результат, Текст); - + КонецПроцедуры Процедура Telegram_ИзменитьТемуФорума(ПараметрыФункции) - Токен = ПараметрыФункции["Telegram_Token"]; + Токен = ПараметрыФункции["Telegram_Token"]; Чат = ПараметрыФункции["Telegram_ForumID"]; Тема = ПараметрыФункции["Telegram_TopicID"]; НовоеИмя = "Новый тестовый заголовок"; НовяИконка = "5310132165583840589"; Результат = OPI_Telegram.ИзменитьТемуФорума(Токен, Чат, Тема, НовоеИмя, НовяИконка); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьТемуФорума", "Telegram"); - + Проверка_ТелеграмИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ЗакрытьТемуФорума(ПараметрыФункции) - Токен = ПараметрыФункции["Telegram_Token"]; + Токен = ПараметрыФункции["Telegram_Token"]; Чат = ПараметрыФункции["Telegram_ForumID"]; Тема = ПараметрыФункции["Telegram_TopicID"]; OPI_Telegram.ОткрытьТемуФорума(Токен, Чат); // SKIP - + Результат = OPI_Telegram.ЗакрытьТемуФорума(Токен, Чат); // Закрывает главную тему - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗакрытьТемуФорума (главная)"); - + Проверка_ТелеграмИстина(Результат); // SKIP - + Результат = OPI_Telegram.ЗакрытьТемуФорума(Токен, Чат, Тема); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗакрытьТемуФорума", "Telegram"); - + Проверка_ТелеграмИстина(Результат); - + OPI_Инструменты.Пауза(25); - + КонецПроцедуры Процедура Telegram_ОткрытьТемуФорума(ПараметрыФункции) - Токен = ПараметрыФункции["Telegram_Token"]; + Токен = ПараметрыФункции["Telegram_Token"]; Чат = ПараметрыФункции["Telegram_ForumID"]; Тема = ПараметрыФункции["Telegram_TopicID"]; Результат = OPI_Telegram.ОткрытьТемуФорума(Токен, Чат); // Открывает главную тему - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОткрытьТемуФорума (главная)"); - + Проверка_ТелеграмИстина(Результат); // SKIP - + Результат = OPI_Telegram.ОткрытьТемуФорума(Токен, Чат, Тема); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОткрытьТемуФорума", "Telegram"); - + Проверка_ТелеграмИстина(Результат); - + OPI_Инструменты.Пауза(25); - + КонецПроцедуры Процедура Telegram_УдалитьТемуФорума(ПараметрыФункции) - Токен = ПараметрыФункции["Telegram_Token"]; + Токен = ПараметрыФункции["Telegram_Token"]; Чат = ПараметрыФункции["Telegram_ForumID"]; Тема = ПараметрыФункции["Telegram_TopicID"]; - - Результат = OPI_Telegram.УдалитьТемуФорума(Токен, Чат, Тема); - + + Результат = OPI_Telegram.УдалитьТемуФорума(Токен, Чат, Тема); + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьТемуФорума", "Telegram"); - + Проверка_ТелеграмИстина(Результат); - + OPI_Инструменты.Пауза(25); - + КонецПроцедуры Процедура Telegram_ОчиститьСписокЗакрепленныхСообщенийТемы(ПараметрыФункции) - Токен = ПараметрыФункции["Telegram_Token"]; + Токен = ПараметрыФункции["Telegram_Token"]; Чат = ПараметрыФункции["Telegram_ForumID"]; Тема = ПараметрыФункции["Telegram_TopicID"]; - + Результат = OPI_Telegram.ОчиститьСписокЗакрепленныхСообщенийТемы(Токен, Чат); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОчиститьСписокЗакрепленныхСообщенийТемы (главная)"); - + Проверка_ТелеграмИстина(Результат); // SKIP - + Результат = OPI_Telegram.ОчиститьСписокЗакрепленныхСообщенийТемы(Токен, Чат, Тема); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОчиститьСписокЗакрепленныхСообщенийТемы", "Telegram"); - + Проверка_ТелеграмИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_СкрытьГлавнуюТемуФорума(ПараметрыФункции) - Токен = ПараметрыФункции["Telegram_Token"]; + Токен = ПараметрыФункции["Telegram_Token"]; Чат = ПараметрыФункции["Telegram_ForumID"]; - + Результат = OPI_Telegram.СкрытьГлавнуюТемуФорума(Токен, Чат); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СкрытьГлавнуюТемуФорума", "Telegram"); - + Проверка_ТелеграмИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ПоказатьГлавнуюТемуФорума(ПараметрыФункции) - Токен = ПараметрыФункции["Telegram_Token"]; + Токен = ПараметрыФункции["Telegram_Token"]; Чат = ПараметрыФункции["Telegram_ForumID"]; - + Результат = OPI_Telegram.ПоказатьГлавнуюТемуФорума(Токен, Чат); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПоказатьГлавнуюТемуФорума", "Telegram"); - + Проверка_ТелеграмИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_ИзменитьИмяГлавнойТемыФорума(ПараметрыФункции) - Заголовок = "Новое имя главной темы " + Строка(Новый УникальныйИдентификатор); - Токен = ПараметрыФункции["Telegram_Token"]; - Чат = ПараметрыФункции["Telegram_ForumID"]; - + Заголовок = "Новое имя главной темы " + Строка(Новый УникальныйИдентификатор); + Токен = ПараметрыФункции["Telegram_Token"]; + Чат = ПараметрыФункции["Telegram_ForumID"]; + Результат = OPI_Telegram.ИзменитьИмяГлавнойТемыФорума(Токен, Чат, Заголовок); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьИмяГлавнойТемыФорума", "Telegram"); - + Проверка_ТелеграмИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Telegram_УдалитьСообщение(ПараметрыФункции) - - Токен = ПараметрыФункции["Telegram_Token"]; - IDЧата = ПараметрыФункции["Telegram_ChannelID"]; + + Токен = ПараметрыФункции["Telegram_Token"]; + IDЧата = ПараметрыФункции["Telegram_ChannelID"]; IDСообщения = ПараметрыФункции["Telegram_ChannelMessageID"]; - + Результат = OPI_Telegram.УдалитьСообщение(Токен, IDЧата, IDСообщения); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьСообщение", "Telegram"); - + Проверка_ТелеграмИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры #КонецОбласти @@ -4666,82 +4666,82 @@ Приложение = ПараметрыФункции["VK_AppID"]; Результат = OPI_VK.СоздатьСсылкуПолученияТокена(Приложение); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьСсылкуПолученияТокена", "VK"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Строка").Заполнено(); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_СоздатьПост(ПараметрыФункции) - + Параметры = ПолучитьПараметрыВК(); Текст = "Пост из автотеста"; URL = "https://github.com/Bayselonarrend/OpenIntegrations"; - + Картинка = ПараметрыФункции["Picture"]; // URL, Путь или Двоичные данные Картинка2 = ПараметрыФункции["Picture2"]; // URL, Путь или Двоичные данные - - ИВФ = ПолучитьИмяВременногоФайла("png"); + + ИВФ = ПолучитьИмяВременногоФайла("png"); КопироватьФайл(Картинка2, ИВФ); - + МассивКартинок = Новый Массив; МассивКартинок.Добавить(Картинка); МассивКартинок.Добавить(ИВФ); - + Результат = OPI_VK.СоздатьПост(Текст, МассивКартинок, Истина, URL, Параметры); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьПост", "VK"); Проверка_ВКПост(Результат); // SKIP ИДПоста = Результат["response"]["post_id"]; // SKIP Результат = OPI_VK.УдалитьПост(ИДПоста, Параметры); // SKIP - + Результат = OPI_VK.СоздатьПост(Текст, Картинка, Ложь , , Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьПост (одна картинка)"); - Проверка_ВКПост(Результат); - - ИДПоста = Результат["response"]["post_id"]; - Результат = OPI_VK.УдалитьПост(ИДПоста, Параметры); - - OPI_Инструменты.Пауза(5); - + Проверка_ВКПост(Результат); + + ИДПоста = Результат["response"]["post_id"]; + Результат = OPI_VK.УдалитьПост(ИДПоста, Параметры); + + OPI_Инструменты.Пауза(5); + Результат = OPI_VK.СоздатьПост(Текст, ИВФ , Истина, URL, Параметры); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьПост (один путь)"); - Проверка_ВКПост(Результат); - + Проверка_ВКПост(Результат); + ИДПоста = Результат["response"]["post_id"]; OPI_Инструменты.ДобавитьПоле("VK_PostID", ИДПоста, "Строка", ПараметрыФункции); OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_PostID", ПараметрыФункции["VK_PostID"]); - + УдалитьФайлы(ИВФ); OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_УдалитьПост(ПараметрыФункции) - + Параметры = ПолучитьПараметрыВК(); ИДПоста = ПараметрыФункции["VK_PostID"]; - + Результат = OPI_VK.УдалитьПост(ИДПоста, Параметры); // END // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьПост", "VK"); - + Проверка_ВКИстина(Результат); - + КонецПроцедуры Процедура VK_СоздатьСоставнойПост(ПараметрыФункции) @@ -4749,154 +4749,154 @@ Параметры = ПолучитьПараметрыВК(); Текст = "Пост из автотеста"; URL = "https://github.com/Bayselonarrend/OpenIntegrations"; - + Картинка = ПараметрыФункции["Picture"]; // URL, Путь или Двоичные данные Видео = ПараметрыФункции["Video"]; // URL, Путь или Двоичные данные - - ИВФ = ПолучитьИмяВременногоФайла("png"); + + ИВФ = ПолучитьИмяВременногоФайла("png"); КопироватьФайл(Картинка, ИВФ); - + ЗагрузкаКартинки = OPI_VK.ЗагрузитьФотоНаСервер(ИВФ, Параметры)["response"][0]; ЗагрузкаВидео = OPI_VK.ЗагрузитьВидеоНаСервер(Видео, "Новое видео", , , Параметры); - + ВладелецКартинки = OPI_Инструменты.ЧислоВСтроку(ЗагрузкаКартинки["owner_id"]); ВладелецВидео = OPI_Инструменты.ЧислоВСтроку(ЗагрузкаВидео["owner_id"]); - + IDКартинки = OPI_Инструменты.ЧислоВСтроку(ЗагрузкаКартинки["id"]); IDВидео = OPI_Инструменты.ЧислоВСтроку(ЗагрузкаВидео["video_id"]); - + МассивВложений = Новый Массив; МассивВложений.Добавить("photo" + ВладелецКартинки + "_" + IDКартинки); МассивВложений.Добавить("video" + ВладелецВидео + "_" + IDВидео); - + Результат = OPI_VK.СоздатьСоставнойПост(Текст, МассивВложений, Ложь, URL, Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьСоставнойПост", "VK"); - + Проверка_ВКПост(Результат); - УдалитьФайлы(ИВФ); - + УдалитьФайлы(ИВФ); + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_СоздатьОпрос() Параметры = ПолучитьПараметрыВК(); Вопрос = "Какой ваш любимый цвет?"; - + МассивВариантов = Новый Массив; МассивВариантов.Добавить("Красный"); МассивВариантов.Добавить("Желтый"); МассивВариантов.Добавить("Зеленый"); - + Результат = OPI_VK.СоздатьОпрос(Вопрос, МассивВариантов, , Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьОпрос", "VK"); - + Проверка_ВКПост(Результат); - + ИДПоста = Результат["response"]["post_id"]; OPI_VK.УдалитьПост(ИДПоста, Параметры); - + OPI_Инструменты.Пауза(10); - + КонецПроцедуры Процедура VK_СоздатьАльбом(ПараметрыФункции) - + Параметры = ПолучитьПараметрыВК(); Имя = "Альбом из автотеста"; Описание = "Новый альбом из автотеста"; - + Результат = OPI_VK.СоздатьАльбом(Имя, Описание, Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьАльбом", "VK"); - + Проверка_ВКАльбом(Результат, Описание); - + ИДАльбома = Результат["response"]["id"]; ПараметрыФункции.Вставить("VK_AlbumID", ИДАльбома); OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_AlbumID", ИДАльбома); - + КонецПроцедуры Процедура VK_СохранитьКартинкуВАльбом(ПараметрыФункции) - + Параметры = ПолучитьПараметрыВК(); ОписаниеКартинки = "Картинка автотест"; ИДАльбома = ПараметрыФункции["VK_AlbumID"]; - + Картинка = ПараметрыФункции["Picture"]; // URL, Путь к файлу или Двоичные данные ИВФ = ПолучитьИмяВременногоФайла("png"); КопироватьФайл(Картинка, ИВФ); - + Картинка = Новый ДвоичныеДанные(ИВФ); - + Результат = OPI_VK.СохранитьКартинкуВАльбом(ИДАльбома, Картинка, ОписаниеКартинки, Параметры); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СохранитьКартинкуВАльбом", "VK"); - + Проверка_ВККартинкаАльбома(Результат, ОписаниеКартинки, ИДАльбома); // SKIP - - ИДКартинки = Результат["response"][0]["id"]; // SKIP + + ИДКартинки = Результат["response"][0]["id"]; // SKIP Результат = OPI_VK.УдалитьКартинку(ИДКартинки, Параметры); // SKIP - + Результат = OPI_VK.СохранитьКартинкуВАльбом(ИДАльбома, ИВФ, ОписаниеКартинки, Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СохранитьКартинкуВАльбом (путь)"); - + Проверка_ВККартинкаАльбома(Результат, ОписаниеКартинки, ИДАльбома); // SKIP - + ИДКартинки = Результат["response"][0]["id"]; ПараметрыФункции.Вставить("VK_PictureID", ИДКартинки); OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_PictureID", ИДКартинки); - + УдалитьФайлы(ИВФ); OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_УдалитьКартинку(ПараметрыФункции) - + Параметры = ПолучитьПараметрыВК(); ИДКартинки = ПараметрыФункции["VK_PictureID"]; - + Результат = OPI_VK.УдалитьКартинку(ИДКартинки, Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьКартинку", "VK"); - + Проверка_ВКИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_УдалитьАльбом(ПараметрыФункции) - + Параметры = ПолучитьПараметрыВК(); ИДАльбома = ПараметрыФункции["VK_AlbumID"]; - + Результат = OPI_VK.УдалитьАльбом(ИДАльбома, Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьАльбом", "VK"); - + Проверка_ВКИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_СоздатьИсторию(ПараметрыФункции) @@ -4908,25 +4908,25 @@ ИВФ = ПолучитьИмяВременногоФайла("png"); КопироватьФайл(Картинка, ИВФ); Картинка = Новый ДвоичныеДанные(ИВФ); - + Результат = OPI_VK.СоздатьИсторию(Картинка , URL, Параметры); // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьИсторию", "VK"); - + Проверка_ВКИстория(Результат); // SKIP - + Результат = OPI_VK.СоздатьИсторию(ИВФ, , Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьИсторию (путь)"); - + Проверка_ВКИстория(Результат); - + УдалитьФайлы(ИВФ); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_СоздатьОбсуждение(ПараметрыФункции) @@ -4934,104 +4934,104 @@ Параметры = ПолучитьПараметрыВК(); Название = "Обсуждаем: какой цвет лучше?"; Сообщение = "Красный, желтый, синий или какой-то другой?"; - + Результат = OPI_VK.СоздатьОбсуждение(Название, Сообщение, Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьОбсуждение", "VK"); - + Проверка_ВКОбсуждение(Результат); - + ИДОбсуждения = Результат["response"]; ПараметрыФункции.Вставить("VK_ConvID", ИДОбсуждения); - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_ConvID", ИДОбсуждения); - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_ConvID", ИДОбсуждения); + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_ЗакрытьОбсуждение(ПараметрыФункции) - + Параметры = ПолучитьПараметрыВК(); ИДОбсуждения = ПараметрыФункции["VK_ConvID"]; Результат = OPI_VK.ЗакрытьОбсуждение(ИДОбсуждения, Ложь, Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗакрытьОбсуждение", "VK"); - + Проверка_ВКИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_ОткрытьОбсуждение(ПараметрыФункции) - + Параметры = ПолучитьПараметрыВК(); ИДОбсуждения = ПараметрыФункции["VK_ConvID"]; Результат = OPI_VK.ОткрытьОбсуждение(ИДОбсуждения, Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОткрытьОбсуждение", "VK"); - + Проверка_ВКИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_НаписатьВОбсуждение(ПараметрыФункции) - + Параметры = ПолучитьПараметрыВК(); ИДОбсуждения = ПараметрыФункции["VK_ConvID"]; Сообщение = "Мне больше нравится желтый"; - + Результат = OPI_VK.НаписатьВОбсуждение(ИДОбсуждения, Сообщение, Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "НаписатьВОбсуждение", "VK"); - + Проверка_ВКОбсуждение(Результат); - + КонецПроцедуры Процедура VK_ПоставитьЛайк(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); IDПоста = ПараметрыФункции["VK_PostID"]; - + Результат = OPI_VK.ПоставитьЛайк(IDПоста, , Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПоставитьЛайк", "VK"); - + Проверка_ВКЛайк(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_СделатьРепост(ПараметрыФункции) - + Параметры = ПолучитьПараметрыВК(); IDПоста = 2571; IDСтены = -218704372; - + Результат = OPI_VK.СделатьРепост(IDПоста, IDСтены, , , Параметры); // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СделатьРепост", "VK"); - + Проверка_ВКРепост(Результат); - + ПараметрыФункции.Вставить("Repost", Результат["response"]["post_id"]); - + OPI_Инструменты.Пауза(5); КонецПроцедуры @@ -5042,78 +5042,78 @@ Текст = "Новый комментарий"; IDПоста = ПараметрыФункции["VK_PostID"]; IDСтены = Параметры["owner_id"]; - + Результат = OPI_VK.НаписатьКомментарий(IDПоста, IDСтены, Текст, Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "НаписатьКомментарий", "VK"); - + Проверка_ВККомментарий(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_ПолучитьСтатистику(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + ТекущаяДата = OPI_Инструменты.ПолучитьТекущуюДату(); ДатаНачала = НачалоДня(ТекущаяДата); ДатаОкончания = КонецДня(ДатаНачала); - + Результат = OPI_VK.ПолучитьСтатистику(ДатаНачала, ДатаОкончания, Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСтатистику", "VK"); - + Проверка_ВКСтатистика(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_ПолучитьСтатистикуПостов(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + МассивПостов = Новый Массив; МассивПостов.Добавить(214); МассивПостов.Добавить(215); - + Результат = OPI_VK.ПолучитьСтатистикуПостов(МассивПостов, Параметры); // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСтатистикуПостов", "VK"); - + Проверка_ВКСтатистикаПостов(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_СоздатьРекламнуюКампанию(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + IDКабинета = ПараметрыФункции["VK_AdsCabinetID"]; Наименование = "Новая кампания"; - + Результат = OPI_VK.СоздатьРекламнуюКампанию(IDКабинета, Наименование, Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьРекламнуюКампанию", "VK"); - + Проверка_Соответствие(Результат); - + ИДКампании = Результат["response"][0]["id"]; OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_AdsCampaignID", ИДКампании); ПараметрыФункции.Вставить("VK_AdsCampaignID", ИДКампании); - + КонецПроцедуры Процедура VK_СоздатьРекламноеОбъявление(ПараметрыФункции) @@ -5125,256 +5125,256 @@ НомерКатегории = 126; IDПоста = ПараметрыФункции["VK_PostID"]; IDКабинета = ПараметрыФункции["VK_AdsCabinetID"]; - + Результат = OPI_VK.СоздатьРекламноеОбъявление(НомерКампании , ДневнойЛимит , НомерКатегории , IDПоста , IDКабинета , Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьРекламноеОбъявление", "VK"); - + Проверка_Соответствие(Результат); - + ИДОбъявления = Результат["response"][0]["id"]; OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_AdsPostID", ИДОбъявления); ПараметрыФункции.Вставить("VK_AdsPostID", ИДОбъявления); - + КонецПроцедуры Процедура VK_ПриостановитьРекламноеОбъявление(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + IDКабинета = ПараметрыФункции["VK_AdsCabinetID"]; IDОбъявления = ПараметрыФункции["VK_AdsPostID"]; - + Результат = OPI_VK.ПриостановитьРекламноеОбъявление(IDКабинета, IDОбъявления, Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПриостановитьРекламноеОбъявление", "VK"); - + Проверка_Соответствие(Результат); - + КонецПроцедуры Процедура VK_СформироватьКлавиатуру(ПараметрыФункции) МассивКнопок = Новый Массив; МассивКнопок.Добавить("Button 1"); - МассивКнопок.Добавить("Button 2"); - + МассивКнопок.Добавить("Button 2"); + Клавиатура = OPI_VK.СформироватьКлавиатуру(МассивКнопок); - + // END - + Проверка_Строка(Клавиатура); - + КонецПроцедуры Процедура VK_НаписатьСообщение(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + Текст = "Сообщение из автотеста"; IDПользователя = ПараметрыФункции["VK_UserID"]; Communitytoken = ПараметрыФункции["VK_CommunityToken"]; - + МассивКнопок = Новый Массив; МассивКнопок.Добавить("Button 1"); - МассивКнопок.Добавить("Button 2"); - + МассивКнопок.Добавить("Button 2"); + Клавиатура = OPI_VK.СформироватьКлавиатуру(МассивКнопок); Результат = OPI_VK.НаписатьСообщение(Текст, IDПользователя, Communitytoken, Клавиатура, Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "НаписатьСообщение", "VK"); - - Проверка_ВКЧисло(Результат); - + + Проверка_ВКЧисло(Результат); + КонецПроцедуры Процедура VK_ПолучитьСписокКатегорийТоваров(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + Результат = OPI_VK.ПолучитьСписокКатегорийТоваров(Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокКатегорийТоваров", "VK"); - + Проверка_Соответствие(Результат); - + КонецПроцедуры Процедура VK_СоздатьПодборкуТоваров(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + Название = "Тестовая подборка"; Картинка = ПараметрыФункции["Picture"]; Основная = Истина; Скрытая = Ложь; - + Результат = OPI_VK.СоздатьПодборкуТоваров(Название , Картинка , Основная , Скрытая - , Параметры); - + , Параметры); + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьПодборкуТоваров", "VK"); - + Проверка_ВКПодборка(Результат); - + OPI_Инструменты.Пауза(5); - + ИДПодборки = Результат["response"]["market_album_id"]; OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_MarketAlbumID", ИДПодборки); ПараметрыФункции.Вставить("VK_MarketAlbumID", ИДПодборки); - + КонецПроцедуры Процедура VK_ИзменитьПодборкуТоваров(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + Название = "Измененная подборка"; - Подборка = ПараметрыФункции["VK_MarketAlbumID"]; - + Подборка = ПараметрыФункции["VK_MarketAlbumID"]; + Результат = OPI_VK.ИзменитьПодборкуТоваров(Название, Подборка, , , , Параметры); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьПодборкуТоваров", "VK"); - + Проверка_ВКИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_ДобавитьТовар(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + Картинка1 = ПараметрыФункции["Picture"]; // URL, Путь к файлу или двоичные данные Картинка2 = ПараметрыФункции["Picture2"]; // URL, Путь к файлу или двоичные данные - Подборка = ПараметрыФункции["VK_MarketAlbumID"]; - + Подборка = ПараметрыФункции["VK_MarketAlbumID"]; + МассивКартинок = Новый Массив; МассивКартинок.Добавить(Картинка1); МассивКартинок.Добавить(Картинка2); - + ОписаниеТовара = Новый Соответствие(); - ОписаниеТовара.Вставить("Имя" , "Тестовый товар"); + ОписаниеТовара.Вставить("Имя" , "Тестовый товар"); ОписаниеТовара.Вставить("Описание" , "Описание товара"); - ОписаниеТовара.Вставить("Категория" , "20173"); - ОписаниеТовара.Вставить("Цена" , 1); - ОписаниеТовара.Вставить("СтараяЦена" , 15); - ОписаниеТовара.Вставить("ОсновноеФото" , Картинка1); - ОписаниеТовара.Вставить("URL" , "https://github.com/Bayselonarrend/OpenIntegrations"); - ОписаниеТовара.Вставить("ДополнительныеФото" , МассивКартинок); - ОписаниеТовара.Вставить("ГлавныйВГруппе" , Истина); - ОписаниеТовара.Вставить("Ширина" , 20); - ОписаниеТовара.Вставить("Высота" , 30); - ОписаниеТовара.Вставить("Глубина" , 40); + ОписаниеТовара.Вставить("Категория" , "20173"); + ОписаниеТовара.Вставить("Цена" , 1); + ОписаниеТовара.Вставить("СтараяЦена" , 15); + ОписаниеТовара.Вставить("ОсновноеФото" , Картинка1); + ОписаниеТовара.Вставить("URL" , "https://github.com/Bayselonarrend/OpenIntegrations"); + ОписаниеТовара.Вставить("ДополнительныеФото" , МассивКартинок); + ОписаниеТовара.Вставить("ГлавныйВГруппе" , Истина); + ОписаниеТовара.Вставить("Ширина" , 20); + ОписаниеТовара.Вставить("Высота" , 30); + ОписаниеТовара.Вставить("Глубина" , 40); ОписаниеТовара.Вставить("Вес" , 100); ОписаниеТовара.Вставить("SKU" , "12345"); ОписаниеТовара.Вставить("ДоступныйОстаток" , "10"); - - Результат = OPI_VK.ДобавитьТовар(ОписаниеТовара, Подборка, Параметры); - - // END - + + Результат = OPI_VK.ДобавитьТовар(ОписаниеТовара, Подборка, Параметры); + + // END + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьТовар", "VK"); - + Проверка_ВКТовар(Результат); - + ИДТовара = Результат["response"]["market_item_id"]; OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_MarketItemID", ИДТовара); ПараметрыФункции.Вставить("VK_MarketItemID", ИДТовара); - + КонецПроцедуры Процедура VK_ИзменитьТовар(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - - Товар = ПараметрыФункции["VK_MarketItemID"]; - + + Товар = ПараметрыФункции["VK_MarketItemID"]; + ОписаниеТовара = Новый Соответствие; ОписаниеТовара.Вставить("Имя", "Тестовый товар измененный"); - + Результат = OPI_VK.ИзменитьТовар(Товар, ОписаниеТовара, , Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьТовар", "VK"); - + Проверка_ВКИстина(Результат); - + КонецПроцедуры Процедура VK_ДобавитьТоварВПодборку(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + Товар = ПараметрыФункции["VK_MarketItemID"]; Подборка = ПараметрыФункции["VK_MarketAlbumID"]; - + Результат = OPI_VK.ДобавитьТоварВПодборку(Товар, Подборка, Параметры); - - // END - + + // END + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьТоварВПодборку", "VK"); - + Проверка_ВКЧисло(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_УдалитьТоварИзПодборки(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + Товар = ПараметрыФункции["VK_MarketItemID"]; Подборка = ПараметрыФункции["VK_MarketAlbumID"]; - - Результат = OPI_VK.УдалитьТоварИзПодборки(Товар, Подборка, Параметры); - + + Результат = OPI_VK.УдалитьТоварИзПодборки(Товар, Подборка, Параметры); + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьТоварИзПодборки", "VK"); - + Проверка_ВКИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_УдалитьТовар(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + Товар = ПараметрыФункции["VK_MarketItemID"]; - + Результат = OPI_VK.УдалитьТовар(Товар, Параметры); - - // END - + + // END + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьТовар", "VK"); - + Проверка_ВКИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_УдалитьПодборку(ПараметрыФункции) @@ -5382,235 +5382,235 @@ Параметры = ПолучитьПараметрыВК(); Подборка = ПараметрыФункции["VK_MarketAlbumID"]; - - Результат = OPI_VK.УдалитьПодборку(Подборка, Параметры); - + + Результат = OPI_VK.УдалитьПодборку(Подборка, Параметры); + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьПодборку", "VK"); - + Проверка_ВКИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_СоздатьСвойствоТовара(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + Название = "Цвет"; - + Результат = OPI_VK.СоздатьСвойствоТовара(Название, Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьСвойствоТовара", "VK"); - + Проверка_ВКСвойство(Результат); - + OPI_Инструменты.Пауза(5); - + Свойство = Результат["response"]["property_id"]; Свойство = OPI_Инструменты.ЧислоВСтроку(Свойство); - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_PropID", Свойство); ПараметрыФункции.Вставить("VK_PropID", Свойство); - + КонецПроцедуры Процедура VK_ИзменитьСвойствоТовара(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + Название = "Цвет (изм.)"; Свойство = ПараметрыФункции["VK_PropID"]; - + Результат = OPI_VK.ИзменитьСвойствоТовара(Название, Свойство, Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьСвойствоТовара", "VK"); - + OPI_Инструменты.Пауза(5); - + Проверка_ВКИстина(Результат); - + КонецПроцедуры Процедура VK_ДобавитьВариантСвойстваТовара(ПараметрыФункции) Счетчик = 1; // SKIP Параметры = ПолучитьПараметрыВК(); - + Свойство = ПараметрыФункции["VK_PropID"]; МассивВариантов = Новый Массив; МассивВариантов.Добавить("Желтый"); МассивВариантов.Добавить("Синий"); МассивВариантов.Добавить("Красный"); - + Для Каждого Значение Из МассивВариантов Цикл - + Результат = OPI_VK.ДобавитьВариантСвойстваТовара(Значение, Свойство, Параметры); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьВариантСвойстваТовара", "VK"); - - Проверка_ВКВариантСвойства(Результат); // SKIP + + Проверка_ВКВариантСвойства(Результат); // SKIP OPI_Инструменты.Пауза(5); // SKIP - + ИДВарианта = Результат["response"]["variant_id"]; // SKIP ИмяПараметра = "VK_PropVarID" + Строка(Счетчик); // SKIP - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр(ИмяПараметра, ИДВарианта); // SKIP ПараметрыФункции.Вставить(ИмяПараметра, ИДВарианта); Счетчик = Счетчик + 1; // SKIP - - КонецЦикла; - + + КонецЦикла; + // END - + КонецПроцедуры Процедура VK_ИзменитьВариантСвойстваТовара(ПараметрыФункции) - + Параметры = ПолучитьПараметрыВК(); - + Свойство = ПараметрыФункции["VK_PropID"]; Вариант = ПараметрыФункции["VK_PropVarID1"]; Значение = "Новое имя варианта"; - + Результат = OPI_VK.ИзменитьВариантСвойстваТовара(Значение , Свойство , Вариант , Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьВариантСвойстваТовара", "VK"); - + Проверка_ВКИстина(Результат); - + КонецПроцедуры Процедура VK_СоздатьТоварСоСвойством(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + Картинка1 = ПараметрыФункции["Picture"]; Картинка2 = ПараметрыФункции["Picture2"]; ВариантСвойства1 = ПараметрыФункции["VK_PropVarID1"]; ВариантСвойства2 = ПараметрыФункции["VK_PropVarID2"]; - + МассивКартинок = Новый Массив; МассивКартинок.Добавить(Картинка1); МассивКартинок.Добавить(Картинка2); - + Товар = Новый Соответствие(); - Товар.Вставить("Имя" , "Тестовый товар (со свойством)"); + Товар.Вставить("Имя" , "Тестовый товар (со свойством)"); Товар.Вставить("Описание" , "Описание товара"); - Товар.Вставить("Категория" , "20173"); - Товар.Вставить("Цена" , 1); - Товар.Вставить("СтараяЦена" , 15); - Товар.Вставить("ОсновноеФото" , Картинка1); - Товар.Вставить("URL" , "https://github.com/Bayselonarrend/OpenIntegrations"); - Товар.Вставить("ДополнительныеФото" , МассивКартинок); - Товар.Вставить("ГлавныйВГруппе" , Истина); - Товар.Вставить("НомерГруппы" , Неопределено); - Товар.Вставить("Ширина" , 20); - Товар.Вставить("Высота" , 30); - Товар.Вставить("Глубина" , 40); + Товар.Вставить("Категория" , "20173"); + Товар.Вставить("Цена" , 1); + Товар.Вставить("СтараяЦена" , 15); + Товар.Вставить("ОсновноеФото" , Картинка1); + Товар.Вставить("URL" , "https://github.com/Bayselonarrend/OpenIntegrations"); + Товар.Вставить("ДополнительныеФото" , МассивКартинок); + Товар.Вставить("ГлавныйВГруппе" , Истина); + Товар.Вставить("НомерГруппы" , Неопределено); + Товар.Вставить("Ширина" , 20); + Товар.Вставить("Высота" , 30); + Товар.Вставить("Глубина" , 40); Товар.Вставить("Вес" , 100); Товар.Вставить("SKU" , 12345); Товар.Вставить("ДоступныйОстаток" , "10"); Товар.Вставить("ЗначенияСвойств" , ВариантСвойства1); - - Результат = OPI_VK.ДобавитьТовар(Товар, , Параметры); - + + Результат = OPI_VK.ДобавитьТовар(Товар, , Параметры); + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ТоварСоСвойством1"); - + Проверка_ВКТовар(Результат); - + ИДТовара = Результат["response"]["market_item_id"]; OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_MarketItemID2", ИДТовара); ПараметрыФункции.Вставить("VK_MarketItemID2", ИДТовара); - + Товар.Вставить("Имя" , "Тестовый товар (другой)"); Товар.Вставить("ЗначенияСвойств", ВариантСвойства2); - Результат = OPI_VK.ДобавитьТовар(Товар, , Параметры); - + Результат = OPI_VK.ДобавитьТовар(Товар, , Параметры); + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ТоварСоСвойством2"); - + Проверка_ВКТовар(Результат); - + ИДТовара = Результат["response"]["market_item_id"]; OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("VK_MarketItemID3", ИДТовара); ПараметрыФункции.Вставить("VK_MarketItemID3", ИДТовара); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_ПолучитьТоварыПоИД(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); - + Товар1 = ПараметрыФункции["VK_MarketItemID2"]; Товар2 = ПараметрыФункции["VK_MarketItemID3"]; - + МассивТоваров = Новый Массив; МассивТоваров.Добавить(Товар1); МассивТоваров.Добавить(Товар2); - + Результат = OPI_VK.ПолучитьТоварыПоИД(МассивТоваров, Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьТоварыПоИД", "VK"); - + Проверка_ВКИнформацияОТоварах(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_СгруппироватьТовары(ПараметрыФункции) - + Параметры = ПолучитьПараметрыВК(); - + Товар1 = ПараметрыФункции["VK_MarketItemID2"]; Товар2 = ПараметрыФункции["VK_MarketItemID3"]; - + МассивТоваров = Новый Массив; МассивТоваров.Добавить(Товар1); МассивТоваров.Добавить(Товар2); - + Результат = OPI_VK.СгруппироватьТовары(МассивТоваров, , Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СгруппироватьТовары", "VK"); - + Проверка_ВКГруппаТоваров(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры - + Процедура VK_УдалитьВариантСвойстваТовара(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); Вариант = ПараметрыФункции["VK_PropVarID1"]; - + Результат = OPI_VK.УдалитьВариантСвойстваТовара(Вариант, Параметры); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьВариантСвойстваТовара", "VK"); - + Проверка_ВКИстина(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_УдалитьСвойствоТовара(ПараметрыФункции) @@ -5618,93 +5618,93 @@ Параметры = ПолучитьПараметрыВК(); Свойство = ПараметрыФункции["VK_PropID"]; - + Результат = OPI_VK.УдалитьСвойствоТовара(Свойство, Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьСвойствоТовара"); - + OPI_Инструменты.Пауза(5); - + Проверка_ВКИстина(Результат); - + КонецПроцедуры Процедура VK_ПолучитьСписокТоваров(ПараметрыФункции) - Параметры = ПолучитьПараметрыВК(); + Параметры = ПолучитьПараметрыВК(); Результат = OPI_VK.ПолучитьСписокТоваров(, Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокТоваров", "VK"); - + Проверка_Массив(Результат); OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_ПолучитьСписокПодборок(ПараметрыФункции) - Параметры = ПолучитьПараметрыВК(); + Параметры = ПолучитьПараметрыВК(); Результат = OPI_VK.ПолучитьСписокПодборок(Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокПодборок", "VK"); - + Проверка_Массив(Результат); OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_ПолучитьСписокСвойств(ПараметрыФункции) - Параметры = ПолучитьПараметрыВК(); + Параметры = ПолучитьПараметрыВК(); Результат = OPI_VK.ПолучитьСписокСвойств(Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокСвойств", "VK"); - + Проверка_Массив(Результат); OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_ПолучитьСписокЗаказов(ПараметрыФункции) Параметры = ПолучитьПараметрыВК(); Результат = OPI_VK.ПолучитьСписокЗаказов(Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокЗаказов", "VK"); - + Проверка_Массив(Результат); OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура VK_ЗагрузитьВидеоНаСервер(ПараметрыФункции) - + Параметры = ПолучитьПараметрыВК(); - + Видео = ПараметрыФункции["Video"]; Наименование = "Новое видео"; Описание = "Описание видео"; - + Результат = OPI_VK.ЗагрузитьВидеоНаСервер(Видео, Наименование, Описание, , Параметры); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗагрузитьВидеоНаСервер", "VK"); - + Проверка_ВКВидео(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры #КонецОбласти @@ -5715,38 +5715,38 @@ КлючПриложения = ПараметрыФункции["Dropbox_Appkey"]; Результат = OPI_Dropbox.ПолучитьСсылкуАвторизации(КлючПриложения); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСсылкуАвторизации", "Dropbox"); - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Результат).ИмеетТип("Строка"); - + КонецПроцедуры Процедура Dropbox_ПолучитьТокен(ПараметрыФункции) - + КлючПриложения = ПараметрыФункции["Dropbox_Appkey"]; СекретПриложения = ПараметрыФункции["Dropbox_Appsecret"]; Код = ПараметрыФункции["Dropbox_Code"]; Результат = OPI_Dropbox.ПолучитьТокен(КлючПриложения, СекретПриложения, Код); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьТокен"); - + Токен = Результат["access_token"]; Рефреш = Результат["refresh_token"]; - + Если ЗначениеЗаполнено(Токен) Тогда OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Dropbox_Token", Токен); КонецЕсли; - + Если ЗначениеЗаполнено(Рефреш) Тогда OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Dropbox_Refresh", Рефреш); КонецЕсли; - + КонецПроцедуры Процедура Dropbox_ОбновитьТокен(ПараметрыФункции) @@ -5754,515 +5754,515 @@ КлючПриложения = ПараметрыФункции["Dropbox_Appkey"]; СекретПриложения = ПараметрыФункции["Dropbox_Appsecret"]; РефрешТокен = ПараметрыФункции["Dropbox_Refresh"]; - + Результат = OPI_Dropbox.ОбновитьТокен(КлючПриложения, СекретПриложения, РефрешТокен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОбновитьТокен"); - + Токен = Результат["access_token"]; - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(Токен).Заполнено(); OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Dropbox_Token", Токен); - + КонецПроцедуры Процедура Dropbox_ПолучитьИнформациюОбОбъекте(ПараметрыФункции) - - Путь = "/New/pic.png"; + + Путь = "/New/pic.png"; Токен = ПараметрыФункции["Dropbox_Token"]; - + Результат = OPI_Dropbox.ПолучитьИнформациюОбОбъекте(Токен, Путь, Истина); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИнформациюОбОбъекте", "Dropbox"); Проверка_ДропБоксФайл(Результат, Путь); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_ПолучитьПревью(ПараметрыФункции) - + Токен = ПараметрыФункции["Dropbox_Token"]; - Путь = "/New/mydoc.docx"; - + Путь = "/New/mydoc.docx"; + Результат = OPI_Dropbox.ПолучитьПревью(Токен, Путь); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьПревью", "Dropbox"); - + Проверка_ДвоичныеДанные(Результат, 120000); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_ЗагрузитьФайл(ПараметрыФункции) - Путь = "/New/pic.png"; + Путь = "/New/pic.png"; Токен = ПараметрыФункции["Dropbox_Token"]; Картинка = ПараметрыФункции["Picture"]; - + КартинкаПуть = ПолучитьИмяВременногоФайла("png"); КопироватьФайл(Картинка, КартинкаПуть); - + Результат = OPI_Dropbox.ЗагрузитьФайл(Токен, КартинкаПуть, Путь, Истина); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗагрузитьФайл", "Dropbox"); - + Проверка_ДропБоксФайл(Результат, Путь); УдалитьФайлы(КартинкаПуть); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_ЗагрузитьФайлПоURL(ПараметрыФункции) - - Путь = "/New/url_doc.docx"; + + Путь = "/New/url_doc.docx"; Токен = ПараметрыФункции["Dropbox_Token"]; URL = ПараметрыФункции["Document"]; - + Результат = OPI_Dropbox.ЗагрузитьФайлПоURL(Токен, URL, Путь); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗагрузитьФайлПоURL", "Dropbox"); - + Проверка_ДропБоксРабота(Результат); - + Работа = Результат["async_job_id"]; - + ПараметрыФункции.Вставить("Dropbox_Job", Работа); OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Dropbox_Job", Работа); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_ПолучитьСтатусЗагрузкиПоURL(ПараметрыФункции) Токен = ПараметрыФункции["Dropbox_Token"]; ИДРаботы = ПараметрыФункции["Dropbox_Job"]; - Статус = "in_progress"; - - Пока Статус = "in_progress" Цикл - + Статус = "in_progress"; + + Пока Статус = "in_progress" Цикл + Результат = OPI_Dropbox.ПолучитьСтатусЗагрузкиПоURL(Токен, ИДРаботы); Статус = Результат[".tag"]; - + OPI_Инструменты.Пауза(5); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСтатусЗагрузкиПоURL", "Dropbox"); - + КонецЦикла; - + // END - + Проверка_ДропБоксСтатус(Результат); - + Путь = "/New/url_doc.docx"; Результат = OPI_Dropbox.УдалитьОбъект(Токен, Путь); - + Проверка_ДропБоксМетаданные(Результат, Путь); - OPI_Инструменты.Пауза(5); - + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_УдалитьОбъект(ПараметрыФункции) - - Путь = "/New/pic.png"; - Токен = ПараметрыФункции["Dropbox_Token"]; - + + Путь = "/New/pic.png"; + Токен = ПараметрыФункции["Dropbox_Token"]; + Результат = OPI_Dropbox.УдалитьОбъект(Токен, Путь); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьОбъект", "Dropbox"); Проверка_ДропБоксМетаданные(Результат, Путь); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_КопироватьОбъект(ПараметрыФункции) - + Оригинал = "/New/pic.png"; - Копия = "/New/pic_copy.png"; + Копия = "/New/pic_copy.png"; Токен = ПараметрыФункции["Dropbox_Token"]; - + Результат = OPI_Dropbox.КопироватьОбъект(Токен, Оригинал, Копия); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "КопироватьОбъект", "Dropbox"); - + Проверка_ДропБоксМетаданные(Результат, Копия); - + Результат = OPI_Dropbox.УдалитьОбъект(Токен, Копия); Проверка_ДропБоксМетаданные(Результат, Копия); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_ПереместитьОбъект(ПараметрыФункции) - + ОригиналныйПуть = "/New/pic.png"; - ЦелевойПуть = "/pic.png"; + ЦелевойПуть = "/pic.png"; Токен = ПараметрыФункции["Dropbox_Token"]; - + Результат = OPI_Dropbox.ПереместитьОбъект(Токен, ОригиналныйПуть, ЦелевойПуть); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереместитьОбъект", "Dropbox"); - + Проверка_ДропБоксМетаданные(Результат, ЦелевойПуть); - + Результат = OPI_Dropbox.ПереместитьОбъект(Токен, ЦелевойПуть, ОригиналныйПуть); Проверка_ДропБоксМетаданные(Результат, ОригиналныйПуть); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_СоздатьПапку(ПараметрыФункции) - + Токен = ПараметрыФункции["Dropbox_Token"]; Путь = "/Новый каталог"; - + Результат = OPI_Dropbox.СоздатьПапку(Токен, Путь); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьПапку", "Dropbox"); - + Проверка_ДропБоксМетаданные(Результат, Путь); - + Результат = OPI_Dropbox.УдалитьОбъект(Токен, Путь); Проверка_ДропБоксМетаданные(Результат, Путь); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_СкачатьФайл(ПараметрыФункции) Токен = ПараметрыФункции["Dropbox_Token"]; - Путь = "/New/pic.png"; - + Путь = "/New/pic.png"; + Результат = OPI_Dropbox.СкачатьФайл(Токен, Путь); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СкачатьФайл", "Dropbox"); - + Проверка_ДвоичныеДанные(Результат, 2000000); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_СкачатьПапку(ПараметрыФункции) - + Токен = ПараметрыФункции["Dropbox_Token"]; Путь = "/New"; - + Результат = OPI_Dropbox.СкачатьПапку(Токен, Путь); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СкачатьПапку", "Dropbox"); - + Проверка_ДвоичныеДанные(Результат); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_ПолучитьСписокФайловПапки(ПараметрыФункции) - - Путь = "/New"; + + Путь = "/New"; Токен = ПараметрыФункции["Dropbox_Token"]; - + Результат = OPI_Dropbox.ПолучитьСписокФайловПапки(Токен, Путь, Истина); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокФайловПапки", "Dropbox"); Проверка_ДропБоксМассив(Результат); - + OPI_Инструменты.Пауза(5); - -КонецПроцедуры + +КонецПроцедуры Процедура Dropbox_ПолучитьСписокВерсийОбъекта(ПараметрыФункции) Токен = ПараметрыФункции["Dropbox_Token"]; - Путь = "/New/pic.png"; - + Путь = "/New/pic.png"; + Результат = OPI_Dropbox.ПолучитьСписокВерсийОбъекта(Токен, Путь, 1); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокВерсийОбъекта", "Dropbox"); - + Проверка_ДропБоксМассив(Результат, 1); - + Ревизия = Результат["entries"][0]["rev"]; - + ПараметрыФункции.Вставить("Dropbox_FileRevision", Ревизия); OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Dropbox_FileRevision", Ревизия); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_ВосстановитьОбъектКВерсии(ПараметрыФункции) - + Версия = ПараметрыФункции["Dropbox_FileRevision"]; Токен = ПараметрыФункции["Dropbox_Token"]; - Путь = "/New/pic.png"; - + Путь = "/New/pic.png"; + Результат = OPI_Dropbox.ВосстановитьОбъектКВерсии(Токен, Путь, Версия); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВосстановитьОбъектКВерсии", "Dropbox"); - + Проверка_ДропБоксФайл(Результат, Путь); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_ПолучитьСписокТегов(ПараметрыФункции) Токен = ПараметрыФункции["Dropbox_Token"]; - + МассивПутей = Новый Массив; МассивПутей.Добавить("/New/Dogs.mp3"); - МассивПутей.Добавить("/New/mydoc.docx"); - + МассивПутей.Добавить("/New/mydoc.docx"); + Результат = OPI_Dropbox.ПолучитьСписокТегов(Токен, МассивПутей); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокТегов", "Dropbox"); - + Проверка_ДропБоксТеги(Результат, МассивПутей.Количество()); - + Результат = OPI_Dropbox.ПолучитьСписокТегов(Токен, "/New/mydoc.docx"); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокТегов (одиночный)"); - + Проверка_ДропБоксТеги(Результат, 1); - + ЕстьТег = Ложь; - + Для Каждого Тег Из Результат["paths_to_tags"][0]["tags"] Цикл Если Тег["tag_text"] = "важное" Тогда - ЕстьТег = Истина; + ЕстьТег = Истина; КонецЕсли; КонецЦикла; - + OPI_ПолучениеДанныхТестов.ОжидаетЧто(ЕстьТег).Равно(Истина); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_ДобавитьТег(ПараметрыФункции) - + Тег = "Важное"; Токен = ПараметрыФункции["Dropbox_Token"]; - Путь = "/New/mydoc.docx"; - + Путь = "/New/mydoc.docx"; + Результат = OPI_Dropbox.ДобавитьТег(Токен, Путь, Тег); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьТег", "Dropbox"); - + Проверка_Пусто(Результат); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_УдалитьТег(ПараметрыФункции) - + Тег = "Важное"; Токен = ПараметрыФункции["Dropbox_Token"]; - Путь = "/New/mydoc.docx"; - + Путь = "/New/mydoc.docx"; + Результат = OPI_Dropbox.УдалитьТег(Токен, Путь, Тег); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьТег", "Dropbox"); - + Проверка_Пусто(Результат); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_ПолучитьИнформациюОбАккаунте(ПараметрыФункции) - + Токен = ПараметрыФункции["Dropbox_Token"]; - + Результат = OPI_Dropbox.ПолучитьИнформациюОбАккаунте(Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИнформациюОбАккаунте", "Dropbox"); - + Проверка_ДропбоксАккаунт(Результат); - + Результат = OPI_Dropbox.ПолучитьИнформациюОбАккаунте(Токен, Результат["account_id"]); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИнформациюОбАккаунте (сторонний)"); - + Проверка_ДропбоксАккаунт(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура Dropbox_ПолучитьДанныеИспользованияПространства(ПараметрыФункции) - + Токен = ПараметрыФункции["Dropbox_Token"]; - + Результат = OPI_Dropbox.ПолучитьДанныеИспользованияПространства(Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьДанныеИспользованияПространства", "Dropbox"); - + Проверка_ДропбоксПространство(Результат); - + КонецПроцедуры Процедура Dropbox_ДобавитьПользователейКФайлу(ПараметрыФункции) - + Токен = ПараметрыФункции["Dropbox_Token"]; Почта = ПараметрыФункции["Dropbox_OtherUser"]; Файл = ПараметрыФункции["Dropbox_FileID"]; - + Результат = OPI_Dropbox.ДобавитьПользователейКФайлу(Токен, Файл, Почта, Ложь); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьПользователейКФайлу", "Dropbox"); - + Проверка_ДропбоксУчастник(Результат, Почта, Ложь); - + Почты = Новый Массив; Почты.Добавить(Почта); - + Результат = OPI_Dropbox.ДобавитьПользователейКФайлу(Токен, Файл, Почты, Истина); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьПользователейКФайлу (доп.) "); - + Проверка_ДропбоксУчастник(Результат, Почта, Истина); - + КонецПроцедуры Процедура Dropbox_ОпубликоватьПапку(ПараметрыФункции) - + Токен = ПараметрыФункции["Dropbox_Token"]; - Путь = "/New"; - + Путь = "/New"; + Результат = OPI_Dropbox.ОпубликоватьПапку(Токен, Путь); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОпубликоватьПапку", "Dropbox"); - + Проверка_ДропБоксПубличнаяПапка(Результат); - + IDПапки = Результат["shared_folder_id"]; - + ПараметрыФункции.Вставить("Dropbox_SharedFolder", IDПапки); OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Dropbox_SharedFolder", IDПапки); - - OPI_Инструменты.Пауза(5); + + OPI_Инструменты.Пауза(5); КонецПроцедуры Процедура Dropbox_ОтменитьПубликациюПапки(ПараметрыФункции) - + Токен = ПараметрыФункции["Dropbox_Token"]; Папка = ПараметрыФункции["Dropbox_SharedFolder"]; - + Результат = OPI_Dropbox.ОтменитьПубликациюПапки(Токен, Папка); ТекущийСтатус = "in_progress"; IDРаботы = Результат["async_job_id"]; - + Пока ТекущийСтатус = "in_progress" Цикл - Результат = OPI_Dropbox.ПолучитьСтатусАсинхронногоИзменения(Токен, IDРаботы); - ТекущийСтатус = Результат[".tag"]; + Результат = OPI_Dropbox.ПолучитьСтатусАсинхронногоИзменения(Токен, IDРаботы); + ТекущийСтатус = Результат[".tag"]; OPI_Инструменты.Пауза(3); КонецЦикла; - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтменитьПубликациюПапки", "Dropbox"); - + Проверка_ДропБоксСтатус(Результат); - - OPI_Инструменты.Пауза(5); - + + OPI_Инструменты.Пауза(5); + КонецПроцедуры Процедура Dropbox_ДобавитьПользователейКПапке(ПараметрыФункции) - + Токен = ПараметрыФункции["Dropbox_Token"]; Почта = ПараметрыФункции["Dropbox_OtherUser"]; Папка = ПараметрыФункции["Dropbox_SharedFolder"]; // shared_folder_id - + Результат = OPI_Dropbox.ДобавитьПользователейКПапке(Токен, Папка, Почта, Ложь); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьПользователейКПапке", "Dropbox"); - + Проверка_Пусто(Результат); - + Почты = Новый Массив; Почты.Добавить(Почта); - + Результат = OPI_Dropbox.ДобавитьПользователейКПапке(Токен, Папка, Почты, Истина); - + Проверка_Пусто(Результат); - + КонецПроцедуры Процедура Dropbox_ОтменитьПубликациюФайла(ПараметрыФункции) - - Токен = ПараметрыФункции["Dropbox_Token"]; + + Токен = ПараметрыФункции["Dropbox_Token"]; Файл = ПараметрыФункции["Dropbox_FileID"]; - + Результат = OPI_Dropbox.ОтменитьПубликациюФайла(Токен, Файл); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтменитьПубликациюФайла", "Dropbox"); - + Проверка_Пусто(Результат); - + КонецПроцедуры #КонецОбласти @@ -6270,2230 +6270,2230 @@ #Область Bitrix24 Процедура Bitrix24_ПолучитьСсылкуАвторизацииПриложения(ПараметрыФункции) - + Домен = ПараметрыФункции["Bitrix24_Domain"]; ClientID = ПараметрыФункции["Bitrix24_ClientID"]; - + Результат = OPI_Bitrix24.ПолучитьСсылкуАвторизацииПриложения(Домен, ClientID); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСсылкуАвторизацииПриложения", "Bitrix24"); - + Проверка_Строка(Результат); - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_AuthURL", Результат); КонецПроцедуры Процедура Bitrix24_ПолучитьТокен(ПараметрыФункции) - + ClientID = ПараметрыФункции["Bitrix24_ClientID"]; ClientSecret = ПараметрыФункции["Bitrix24_ClientSecret"]; Code = ПараметрыФункции["Bitrix24_Code"]; - + Результат = OPI_Bitrix24.ПолучитьТокен(ClientID, ClientSecret, Code); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьТокен", "Bitrix24"); - + Если ЗначениеЗаполнено(Результат["access_token"]) И ЗначениеЗаполнено(Результат["refresh_token"]) Тогда OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_Token" , Результат["access_token"]); OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_Refresh", Результат["refresh_token"]); КонецЕсли; - + КонецПроцедуры Процедура Bitrix24_ОбновитьТокен(ПараметрыФункции) - + ClientID = ПараметрыФункции["Bitrix24_ClientID"]; ClientSecret = ПараметрыФункции["Bitrix24_ClientSecret"]; Refresh = ПараметрыФункции["Bitrix24_Refresh"]; - + Результат = OPI_Bitrix24.ОбновитьТокен(ClientID, ClientSecret, Refresh); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОбновитьТокен", "Bitrix24"); - + Проверка_БитриксАвторизация(Результат); - + Если ЗначениеЗаполнено(Результат["access_token"]) И ЗначениеЗаполнено(Результат["refresh_token"]) Тогда OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_Token" , Результат["access_token"]); OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_Refresh", Результат["refresh_token"]); КонецЕсли; - + КонецПроцедуры Процедура Bitrix24_СерверноеВремя(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.СерверноеВремя(URL); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СерверноеВремя (хук)", "Bitrix24"); - + Проверка_БитриксВремя(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.СерверноеВремя(URL, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СерверноеВремя", "Bitrix24"); - - Проверка_БитриксВремя(Результат); - + + Проверка_БитриксВремя(Результат); + КонецПроцедуры Процедура Bitrix24_СоздатьНовость(ПараметрыФункции) - + Текст = "Текст новости"; Заголовок = "Заголовок новости"; Картинка1 = ПараметрыФункции["Picture"]; // URL, Путь или Двоичные данные Картинка2 = ПараметрыФункции["Picture2"]; // URL, Путь или Двоичные данные - + Файлы = Новый Соответствие; Файлы.Вставить("1.png", Картинка1); Файлы.Вставить("2.png", Картинка2); - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.СоздатьНовость(URL, Текст, , Файлы, Заголовок, Истина); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьНовость (хук)", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); // SKIP - + IDНовости = Результат["result"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookPostID", IDНовости); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookPostID", IDНовости); // SKIP ПараметрыФункции.Вставить("Bitrix24_HookPostID", IDНовости); // SKIP URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.СоздатьНовость(URL, Текст, , Файлы, Заголовок, , Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьНовость", "Bitrix24"); - - Проверка_БитриксЧисло(Результат); - + + Проверка_БитриксЧисло(Результат); + IDНовости = Результат["result"]; - - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_PostID", IDНовости); + + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_PostID", IDНовости); ПараметрыФункции.Вставить("Bitrix24_PostID", IDНовости); - + КонецПроцедуры Процедура Bitrix24_ИзменитьНовость(ПараметрыФункции) - + Текст = "Новый текст новости"; Заголовок = "Новый заголовок новости"; Картинка1 = ПараметрыФункции["Picture"]; // URL, Путь или Двоичные данные IDНовости = ПараметрыФункции["Bitrix24_PostID"]; - + Файлы = Новый Соответствие; Файлы.Вставить("1.png", Картинка1); - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ИзменитьНовость(URL, IDНовости, Текст, , Файлы, Заголовок); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьНовость (хук)", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDНовости = ПараметрыФункции["Bitrix24_HookPostID"]; - + Результат = OPI_Bitrix24.ИзменитьНовость(URL, IDНовости, Текст, , Файлы, Заголовок, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьНовость", "Bitrix24"); - - Проверка_БитриксЧисло(Результат); - + + Проверка_БитриксЧисло(Результат); + КонецПроцедуры Процедура Bitrix24_УдалитьНовость(ПараметрыФункции) - - IDНовости = ПараметрыФункции["Bitrix24_HookPostID"]; + + IDНовости = ПараметрыФункции["Bitrix24_HookPostID"]; URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.УдалитьНовость(URL, IDНовости); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьНовость (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + IDНовости = ПараметрыФункции["Bitrix24_PostID"]; URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.УдалитьНовость(URL, IDНовости, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьНовость", "Bitrix24"); - - Проверка_БитриксИстина(Результат); - + + Проверка_БитриксИстина(Результат); + КонецПроцедуры Процедура Bitrix24_ПолучитьСписокПросмотревшихВажное(ПараметрыФункции) - - IDНовости = ПараметрыФункции["Bitrix24_HookPostID"]; + + IDНовости = ПараметрыФункции["Bitrix24_HookPostID"]; URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ПолучитьСписокПросмотревшихВажное(URL, IDНовости); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокПросмотревшихВажное (хук)", "Bitrix24"); - + Проверка_БитриксМассив(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьСписокПросмотревшихВажное(URL, IDНовости, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокПросмотревшихВажное", "Bitrix24"); - - Проверка_БитриксМассив(Результат); - + + Проверка_БитриксМассив(Результат); + КонецПроцедуры Процедура Bitrix24_ПолучитьНовости(ПараметрыФункции) - - IDНовости = ПараметрыФункции["Bitrix24_PostID"]; + + IDНовости = ПараметрыФункции["Bitrix24_PostID"]; URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ПолучитьНовости(URL, IDНовости); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьНовости (хук)", "Bitrix24"); - + Проверка_БитриксМассивОбъектов(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьНовости(URL, IDНовости, , Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьНовости", "Bitrix24"); - - Проверка_БитриксМассивОбъектов(Результат); - + + Проверка_БитриксМассивОбъектов(Результат); + КонецПроцедуры Процедура Bitrix24_ДобавитьКомментарийНовости(ПараметрыФункции) - + Текст = "Комментарий к новости"; - IDНовости = ПараметрыФункции["Bitrix24_PostID"]; + IDНовости = ПараметрыФункции["Bitrix24_PostID"]; URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ДобавитьКомментарийНовости(URL, IDНовости, Текст); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьКомментарийНовости (хук)", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); // SKIP - + Текст = "Другой комментарий к новости"; URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ДобавитьКомментарийНовости(URL, IDНовости, Текст, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьКомментарийНовости", "Bitrix24"); - - Проверка_БитриксЧисло(Результат); - + + Проверка_БитриксЧисло(Результат); + КонецПроцедуры Процедура Bitrix24_ДобавитьПолучателейКНовости(ПараметрыФункции) - + Видимость = "UA"; - IDНовости = ПараметрыФункции["Bitrix24_PostID"]; + IDНовости = ПараметрыФункции["Bitrix24_PostID"]; URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ДобавитьПолучателейКНовости(URL, IDНовости, Видимость); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьПолучателейКНовости (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ДобавитьПолучателейКНовости(URL, IDНовости, Видимость, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьПолучателейКНовости", "Bitrix24"); - - Проверка_БитриксИстина(Результат); - + + Проверка_БитриксИстина(Результат); + КонецПроцедуры Процедура Bitrix24_ПолучитьСтруктуруЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ПолучитьСтруктуруЗадачи(URL); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСтруктуруЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксПоля(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьСтруктуруЗадачи(URL, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСтруктуруЗадачи", "Bitrix24"); - - Проверка_БитриксПоля(Результат); - + + Проверка_БитриксПоля(Результат); + КонецПроцедуры Процедура Bitrix24_СоздатьЗадачу(ПараметрыФункции) - + // Полную структуру полей можно получить функцией ПолучитьСтруктуруЗадачи() - + ТекущаяДата = OPI_Инструменты.ПолучитьТекущуюДату(); Час = 3600; Сутки = 24; Исполнитель = 1; - + СтруктураЗадачи = Новый Структура; СтруктураЗадачи.Вставить("TITLE" , "Новая задача"); СтруктураЗадачи.Вставить("DESCRIPTION" , "Новое описание задачи"); СтруктураЗадачи.Вставить("PRIORITY" , "2"); СтруктураЗадачи.Вставить("DEADLINE" , ТекущаяДата + Час * Сутки); СтруктураЗадачи.Вставить("RESPONSIBLE_ID", Исполнитель); - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.СоздатьЗадачу(URL, СтруктураЗадачи); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьЗадачу (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + IDЗадачи = Результат["result"]["task"]["id"]; // SKIP - - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookTaskID", IDЗадачи); // SKIP + + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookTaskID", IDЗадачи); // SKIP ПараметрыФункции.Вставить("Bitrix24_HookTaskID", IDЗадачи); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.СоздатьЗадачу(URL, СтруктураЗадачи, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьЗадачу", "Bitrix24"); - - Проверка_БитриксЗадача(Результат); - + + Проверка_БитриксЗадача(Результат); + IDЗадачи = Результат["result"]["task"]["id"]; - - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_TaskID", IDЗадачи); + + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_TaskID", IDЗадачи); ПараметрыФункции.Вставить("Bitrix24_TaskID", IDЗадачи); - + OPI_Инструменты.Пауза(5); КонецПроцедуры Процедура Bitrix24_ИзменитьЗадачу(ПараметрыФункции) - + // Полную структуру полей можно получить функцией ПолучитьСтруктуруЗадачи() - + СтруктураЗадачи = Новый Структура; - СтруктураЗадачи.Вставить("TITLE", "Другой заголовок задачи"); + СтруктураЗадачи.Вставить("TITLE" , "Другой заголовок задачи"); СтруктураЗадачи.Вставить("DESCRIPTION", "Другое описание задачи"); - СтруктураЗадачи.Вставить("PRIORITY", "1"); - + СтруктураЗадачи.Вставить("PRIORITY" , "1"); + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ИзменитьЗадачу(URL, IDЗадачи, СтруктураЗадачи); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьЗадачу (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ИзменитьЗадачу(URL, IDЗадачи, СтруктураЗадачи, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьЗадачу", "Bitrix24"); - - Проверка_БитриксЗадача(Результат); - + + Проверка_БитриксЗадача(Результат); + КонецПроцедуры Процедура Bitrix24_ПолучитьЗадачу(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ПолучитьЗадачу(URL, IDЗадачи); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьЗадачу (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ПолучитьЗадачу(URL, IDЗадачи, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьЗадачу", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); - + КонецПроцедуры Процедура Bitrix24_ПринятьЗадачу(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ПринятьЗадачу(URL, IDЗадачи); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПринятьЗадачу (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ПринятьЗадачу(URL, IDЗадачи, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПринятьЗадачу", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); - + КонецПроцедуры Процедура Bitrix24_ОтклонитьЗадачу(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ОтклонитьЗадачу(URL, IDЗадачи); - + Проверка_Соответствие(Результат); // SKIP - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтклонитьЗадачу (хук)", "Bitrix24"); - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ОтклонитьЗадачу(URL, IDЗадачи, Токен); - + // END - + Проверка_Соответствие(Результат); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтклонитьЗадачу", "Bitrix24"); - + КонецПроцедуры Процедура Bitrix24_ЗавершитьЗадачу(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ЗавершитьЗадачу(URL, IDЗадачи); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗавершитьЗадачу (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ЗавершитьЗадачу(URL, IDЗадачи, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗавершитьЗадачу", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); - + КонецПроцедуры Процедура Bitrix24_ВозобновитьЗадачу(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ВозобновитьЗадачу(URL, IDЗадачи); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВозобновитьЗадачу (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ВозобновитьЗадачу(URL, IDЗадачи, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВозобновитьЗадачу", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); - + КонецПроцедуры Процедура Bitrix24_ОтложитьЗадачу(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ОтложитьЗадачу(URL, IDЗадачи); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтложитьЗадачу (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ОтложитьЗадачу(URL, IDЗадачи, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтложитьЗадачу", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); - + КонецПроцедуры Процедура Bitrix24_НачатьВыполнениеЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.НачатьВыполнениеЗадачи(URL, IDЗадачи); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "НачатьВыполнениеЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.НачатьВыполнениеЗадачи(URL, IDЗадачи, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "НачатьВыполнениеЗадачи", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); - + КонецПроцедуры Процедура Bitrix24_НачатьНаблюдатьЗаЗадачей(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.НачатьНаблюдатьЗаЗадачей(URL, IDЗадачи); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "НачатьНаблюдатьЗаЗадачей (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.НачатьНаблюдатьЗаЗадачей(URL, IDЗадачи, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "НачатьНаблюдатьЗаЗадачей", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); - + КонецПроцедуры Процедура Bitrix24_ПрекратитьНаблюдатьЗаЗадачей(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ПрекратитьНаблюдатьЗаЗадачей(URL, IDЗадачи); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПрекратитьНаблюдатьЗаЗадачей (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ПрекратитьНаблюдатьЗаЗадачей(URL, IDЗадачи, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПрекратитьНаблюдатьЗаЗадачей", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); - + КонецПроцедуры Процедура Bitrix24_ПриостановитьЗадачу(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ПриостановитьЗадачу(URL, IDЗадачи); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПриостановитьЗадачу (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ПриостановитьЗадачу(URL, IDЗадачи, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПриостановитьЗадачу", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); - + КонецПроцедуры Процедура Bitrix24_УдалитьЗадачу(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.УдалитьЗадачу(URL, IDЗадачи); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьЗадачу (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.УдалитьЗадачу(URL, IDЗадачи, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьЗадачу", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); - + КонецПроцедуры Процедура Bitrix24_ДелегироватьЗадачу(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; IDПользователя = ПараметрыФункции["Bitrix24_UserID"]; - + Результат = OPI_Bitrix24.ДелегироватьЗадачу(URL, IDЗадачи, IDПользователя); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДелегироватьЗадачу (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ДелегироватьЗадачу(URL, IDЗадачи, IDПользователя, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДелегироватьЗадачу", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); - + КонецПроцедуры Процедура Bitrix24_ДобавитьЗадачуВИзбранное(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ДобавитьЗадачуВИзбранное(URL, IDЗадачи); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьЗадачуВИзбранное (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ДобавитьЗадачуВИзбранное(URL, IDЗадачи, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьЗадачуВИзбранное", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_УбратьЗадачуИзИзбранного(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.УбратьЗадачуИзИзбранного(URL, IDЗадачи); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УбратьЗадачуИзИзбранного (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.УбратьЗадачуИзИзбранного(URL, IDЗадачи, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УбратьЗадачуИзИзбранного", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьИсториюЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ПолучитьИсториюЗадачи(URL, IDЗадачи); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИсториюЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксСписок(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ПолучитьИсториюЗадачи(URL, IDЗадачи, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИсториюЗадачи", "Bitrix24"); - + Проверка_БитриксСписок(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьСписокЗадач(ПараметрыФункции) - + // Полную структуру фильтра можно найти в функции ПолучитьСтруктуруФильтраЗадач Фильтр = Новый Структура; Фильтр.Вставить("CREATED_BY" , 1); Фильтр.Вставить("RESPONSIBLE_ID", 10); - + Отступ = 1; URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ПолучитьСписокЗадач(URL, Фильтр); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокЗадач (хук)", "Bitrix24"); - + Проверка_БитриксСписокЗадач(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьСписокЗадач(URL, , Отступ, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокЗадач", "Bitrix24"); - + Проверка_БитриксСписокЗадач(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьСписокХранилищ(ПараметрыФункции) - - URL = ПараметрыФункции["Bitrix24_URL"]; + + URL = ПараметрыФункции["Bitrix24_URL"]; Результат = OPI_Bitrix24.ПолучитьСписокХранилищ(URL); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокХранилищ (хук)", "Bitrix24"); - + Проверка_БитриксХранилища(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьСписокХранилищ(URL, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокХранилищ", "Bitrix24"); - + Проверка_БитриксХранилища(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьХранилищеПриложения(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьХранилищеПриложения(URL, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьХранилищеПриложения", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); - + IDХранилища = Результат["result"]["ID"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_StorageID", IDХранилища); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_StorageID", IDХранилища); // SKIP ПараметрыФункции.Вставить("Bitrix24_StorageID", IDХранилища); // SKIP - + КонецПроцедуры Процедура Bitrix24_ЗагрузитьФайлВХранилище(ПараметрыФункции) - - Наименование2 = "Картинка2.jpg"; + + Наименование2 = "Картинка2.jpg"; Наименование = "Картинка1.jpg"; - + Картинка2 = ПараметрыФункции["Picture"]; // Локальный путь, URL или Двоичные данные Картинка = ПараметрыФункции["Picture2"]; // Локальный путь, URL или Двоичные данные - + IDПриемника = 3; - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ЗагрузитьФайлВХранилище(URL, Наименование2, Картинка2, IDПриемника); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗагрузитьФайлВХранилище (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + IDФайла = Результат["result"]["ID"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookFileID", IDФайла); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookFileID", IDФайла); // SKIP ПараметрыФункции.Вставить("Bitrix24_HookFileID", IDФайла); // SKIP URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ЗагрузитьФайлВХранилище(URL, Наименование, Картинка, IDПриемника, , Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗагрузитьФайлВХранилище", "Bitrix24"); - - Проверка_БитриксОбъект(Результат); - - IDФайла = Результат["result"]["ID"]; - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_FileID", IDФайла); - ПараметрыФункции.Вставить("Bitrix24_FileID", IDФайла); - + + Проверка_БитриксОбъект(Результат); + + IDФайла = Результат["result"]["ID"]; + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_FileID", IDФайла); + ПараметрыФункции.Вставить("Bitrix24_FileID", IDФайла); + КонецПроцедуры Процедура Bitrix24_УдалитьФайл(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDФайла = ПараметрыФункции["Bitrix24_HookFileID"]; - + Результат = OPI_Bitrix24.УдалитьФайл(URL, IDФайла); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьФайл (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDФайла = ПараметрыФункции["Bitrix24_FileID"]; - + Результат = OPI_Bitrix24.УдалитьФайл(URL, IDФайла, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьФайл", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_СоздатьКаталогВХранилище(ПараметрыФункции) - + IDХранилища = 3; Наименование = "Новый каталог"; Наименование2 = "Новый каталог 2"; - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.СоздатьКаталогВХранилище(URL, IDХранилища, Наименование2); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьКаталогВХранилище (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + IDКаталога = Результат["result"]["ID"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookFolderID", IDКаталога); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookFolderID", IDКаталога); // SKIP ПараметрыФункции.Вставить("Bitrix24_HookFolderID", IDКаталога); // SKIP URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.СоздатьКаталогВХранилище(URL, IDХранилища, Наименование, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьКаталогВХранилище", "Bitrix24"); - - Проверка_БитриксОбъект(Результат); - + + Проверка_БитриксОбъект(Результат); + IDКаталога = Результат["result"]["ID"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_FolderID", IDКаталога); // SKIP - ПараметрыФункции.Вставить("Bitrix24_FolderID", IDКаталога); // SKIP - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_FolderID", IDКаталога); // SKIP + ПараметрыФункции.Вставить("Bitrix24_FolderID", IDКаталога); // SKIP + КонецПроцедуры Процедура Bitrix24_УдалитьКаталог(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDКаталога = ПараметрыФункции["Bitrix24_HookFolderID"]; - + Результат = OPI_Bitrix24.УдалитьКаталог(URL, IDКаталога); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьКаталог (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDКаталога = ПараметрыФункции["Bitrix24_FolderID"]; - + Результат = OPI_Bitrix24.УдалитьКаталог(URL, IDКаталога, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьКаталог", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьХранилище(ПараметрыФункции) - - URL = ПараметрыФункции["Bitrix24_URL"]; + + URL = ПараметрыФункции["Bitrix24_URL"]; IDХранилища = 3; - + Результат = OPI_Bitrix24.ПолучитьХранилище(URL, IDХранилища); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьХранилище (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьХранилище(URL, IDХранилища, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьХранилище", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьСодержимоеХранилища(ПараметрыФункции) - - URL = ПараметрыФункции["Bitrix24_URL"]; - IDХранилища = 3; - + + URL = ПараметрыФункции["Bitrix24_URL"]; + IDХранилища = 3; + Результат = OPI_Bitrix24.ПолучитьСодержимоеХранилища(URL, IDХранилища); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСодержимоеХранилища (хук)", "Bitrix24"); - + Проверка_БитриксМассив(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьСодержимоеХранилища(URL, IDХранилища, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСодержимоеХранилища", "Bitrix24"); - + Проверка_БитриксМассив(Результат); - + КонецПроцедуры Процедура Bitrix24_ПереименоватьХранилище(ПараметрыФункции) - - Наименование = "Новое имя хранилища"; + + Наименование = "Новое имя хранилища"; URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDХранилища = ПараметрыФункции["Bitrix24_StorageID"]; - + Результат = OPI_Bitrix24.ПереименоватьХранилище(URL, IDХранилища, Наименование, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереименоватьХранилище", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьИнформациюОКаталоге(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDКаталога = ПараметрыФункции["Bitrix24_FolderID"]; - + Результат = OPI_Bitrix24.ПолучитьИнформациюОКаталоге(URL, IDКаталога); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИнформациюОКаталоге (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьИнформациюОКаталоге(URL, IDКаталога, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИнформациюОКаталоге", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); - + КонецПроцедуры Процедура Bitrix24_СоздатьПодкаталог(ПараметрыФункции) - + IDКаталога = ПараметрыФункции["Bitrix24_FolderID"]; Наименование = "Новый подкаталог"; Наименование2 = "Новый подкаталог 2"; - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.СоздатьПодкаталог(URL, IDКаталога, Наименование2); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьПодкаталог (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + IDПодкаталога = Результат["result"]["ID"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookSubfolderID", IDПодкаталога); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookSubfolderID", IDПодкаталога); // SKIP ПараметрыФункции.Вставить("Bitrix24_HookSubfolderID", IDПодкаталога); // SKIP URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.СоздатьПодкаталог(URL, IDКаталога, Наименование, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьПодкаталог", "Bitrix24"); - - Проверка_БитриксОбъект(Результат); - + + Проверка_БитриксОбъект(Результат); + IDПодкаталога = Результат["result"]["ID"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_SubfolderID", IDПодкаталога); // SKIP - ПараметрыФункции.Вставить("Bitrix24_SubfolderID", IDПодкаталога); // SKIP - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_SubfolderID", IDПодкаталога); // SKIP + ПараметрыФункции.Вставить("Bitrix24_SubfolderID", IDПодкаталога); // SKIP + КонецПроцедуры Процедура Bitrix24_СкопироватьКаталог(ПараметрыФункции) - + IDПриемника = ПараметрыФункции["Bitrix24_HookSubfolderID"]; IDКаталога = ПараметрыФункции["Bitrix24_SubfolderID"]; - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.СкопироватьКаталог(URL, IDКаталога, IDПриемника); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СкопироватьКаталог (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + IDПриемника = ПараметрыФункции["Bitrix24_SubfolderID"]; IDКаталога = ПараметрыФункции["Bitrix24_HookSubfolderID"]; URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.СкопироватьКаталог(URL, IDКаталога, IDПриемника, Токен); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СкопироватьКаталог", "Bitrix24"); - - Проверка_БитриксОбъект(Результат); - + + Проверка_БитриксОбъект(Результат); + КонецПроцедуры Процедура Bitrix24_ПолучитьВнешнююСсылкуКаталога(ПараметрыФункции) - - URL = ПараметрыФункции["Bitrix24_URL"]; + + URL = ПараметрыФункции["Bitrix24_URL"]; IDКаталога = ПараметрыФункции["Bitrix24_FolderID"]; - + Результат = OPI_Bitrix24.ПолучитьВнешнююСсылкуКаталога(URL, IDКаталога); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьВнешнююСсылкуКаталога (хук)", "Bitrix24"); - + Проверка_БитриксСтрока(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьВнешнююСсылкуКаталога(URL, IDКаталога, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьВнешнююСсылкуКаталога", "Bitrix24"); - + Проверка_БитриксСтрока(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьСтруктуруФильтраКаталога(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ПолучитьСтруктуруФильтраКаталога(URL); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСтруктуруФильтраКаталога (хук)", "Bitrix24"); - + Проверка_Структура(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьСтруктуруФильтраКаталога(URL, Истина, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСтруктуруФильтраКаталога", "Bitrix24"); - + Проверка_Структура(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьДочерниеЭлементыКаталога(ПараметрыФункции) - - URL = ПараметрыФункции["Bitrix24_URL"]; + + URL = ПараметрыФункции["Bitrix24_URL"]; IDКаталога = ПараметрыФункции["Bitrix24_FolderID"]; - + Результат = OPI_Bitrix24.ПолучитьДочерниеЭлементыКаталога(URL, IDКаталога); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьДочерниеЭлементыКаталога (хук)", "Bitrix24"); - + Проверка_БитриксМассив(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьДочерниеЭлементыКаталога(URL, IDКаталога, , Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьДочерниеЭлементыКаталога", "Bitrix24"); - + Проверка_БитриксМассив(Результат); - + КонецПроцедуры Процедура Bitrix24_ПоместитьКаталогВКорзину(ПараметрыФункции) - - URL = ПараметрыФункции["Bitrix24_URL"]; + + URL = ПараметрыФункции["Bitrix24_URL"]; IDКаталога = ПараметрыФункции["Bitrix24_FolderID"]; - + Результат = OPI_Bitrix24.ПоместитьКаталогВКорзину(URL, IDКаталога); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПоместитьКаталогВКорзину (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПоместитьКаталогВКорзину(URL, IDКаталога, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПоместитьКаталогВКорзину", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); - + КонецПроцедуры Процедура Bitrix24_ВосстановитьКаталог(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDКаталога = ПараметрыФункции["Bitrix24_FolderID"]; - + Результат = OPI_Bitrix24.ВосстановитьКаталог(URL, IDКаталога); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВосстановитьКаталог (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ВосстановитьКаталог(URL, IDКаталога, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВосстановитьКаталог", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); - + КонецПроцедуры Процедура Bitrix24_ПереместитьКаталог(ПараметрыФункции) - + IDПриемника = ПараметрыФункции["Bitrix24_HookfolderID"]; IDКаталога = ПараметрыФункции["Bitrix24_SubfolderID"]; - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ПереместитьКаталог(URL, IDКаталога, IDПриемника); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереместитьКаталог (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + IDКаталога = ПараметрыФункции["Bitrix24_HookSubfolderID"]; URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПереместитьКаталог(URL, IDКаталога, IDПриемника, Токен); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереместитьКаталог", "Bitrix24"); - - Проверка_БитриксОбъект(Результат); - + + Проверка_БитриксОбъект(Результат); + КонецПроцедуры Процедура Bitrix24_ПереименоватьКаталог(ПараметрыФункции) - + Наименование = "Новый каталог"; Наименование2 = "Новый каталог 2"; - + IDКаталога2 = ПараметрыФункции["Bitrix24_HookFolderID"]; URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ПереименоватьКаталог(URL, IDКаталога2, Наименование2); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереименоватьКаталог (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP IDКаталога = ПараметрыФункции["Bitrix24_FolderID"]; URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПереименоватьКаталог(URL, IDКаталога, Наименование, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереименоватьКаталог", "Bitrix24"); - - Проверка_БитриксОбъект(Результат); - + + Проверка_БитриксОбъект(Результат); + КонецПроцедуры Процедура Bitrix24_ЗагрузитьФайлВКаталог(ПараметрыФункции) - - Наименование2 = "Картинка2.jpg"; + + Наименование2 = "Картинка2.jpg"; Наименование = "Картинка1.jpg"; - + Картинка2 = ПараметрыФункции["Picture"]; // Локальный путь, URL или Двоичные данные Картинка = ПараметрыФункции["Picture2"]; // Локальный путь, URL или Двоичные данные - + IDПриемника = ПараметрыФункции["Bitrix24_FolderID"]; - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ЗагрузитьФайлВКаталог(URL, Наименование2, Картинка2, IDПриемника); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗагрузитьФайлВКаталог (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + IDФайла = Результат["result"]["ID"]; // SKIP OPI_Bitrix24.УдалитьФайл(URL, IDФайла); // SKIP URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ЗагрузитьФайлВКаталог(URL, Наименование, Картинка, IDПриемника, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ЗагрузитьФайлВКаталог", "Bitrix24"); - - Проверка_БитриксОбъект(Результат); - + + Проверка_БитриксОбъект(Результат); + IDФайла = Результат["result"]["ID"]; - Результат = OPI_Bitrix24.УдалитьФайл(URL, IDФайла, Токен); - + Результат = OPI_Bitrix24.УдалитьФайл(URL, IDФайла, Токен); + КонецПроцедуры Процедура Bitrix24_СкопироватьФайл(ПараметрыФункции) - + IDКаталога = ПараметрыФункции["Bitrix24_HookFolderID"]; IDФайла = ПараметрыФункции["Bitrix24_FileID"]; - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.СкопироватьФайл(URL, IDФайла, IDКаталога); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СкопироватьФайл (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + IDКаталога = ПараметрыФункции["Bitrix24_FolderID"]; URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.СкопироватьФайл(URL, IDФайла, IDКаталога, Токен); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СкопироватьФайл", "Bitrix24"); - - Проверка_БитриксОбъект(Результат); - + + Проверка_БитриксОбъект(Результат); + КонецПроцедуры Процедура Bitrix24_ПолучитьИнформациюОФайле(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDФайла = ПараметрыФункции["Bitrix24_FileID"]; - + Результат = OPI_Bitrix24.ПолучитьИнформациюОФайле(URL, IDФайла); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИнформациюОФайле (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьИнформациюОФайле(URL, IDФайла, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИнформациюОФайле", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьВнешнююСсылкуФайла(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDФайла = ПараметрыФункции["Bitrix24_FileID"]; - + Результат = OPI_Bitrix24.ПолучитьВнешнююСсылкуФайла(URL, IDФайла); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьВнешнююСсылкуФайла (хук)", "Bitrix24"); - + Проверка_БитриксСтрока(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьВнешнююСсылкуФайла(URL, IDФайла, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьВнешнююСсылкуФайла", "Bitrix24"); - + Проверка_БитриксСтрока(Результат); - + КонецПроцедуры Процедура Bitrix24_ПоместитьФайлВКорзину(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDФайла = ПараметрыФункции["Bitrix24_FileID"]; - + Результат = OPI_Bitrix24.ПоместитьФайлВКорзину(URL, IDФайла); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПоместитьФайлВКорзину (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПоместитьФайлВКорзину(URL, IDФайла, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПоместитьФайлВКорзину", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); - + КонецПроцедуры Процедура Bitrix24_ВосстановитьФайл(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDФайла = ПараметрыФункции["Bitrix24_FileID"]; - + Результат = OPI_Bitrix24.ВосстановитьФайл(URL, IDФайла); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВосстановитьФайл (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ВосстановитьФайл(URL, IDФайла, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВосстановитьФайл", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); - + КонецПроцедуры Процедура Bitrix24_ПереименоватьФайл(ПараметрыФункции) - + Наименование = "Новое имя файла.jpg"; Наименование2 = "Новое имя файла 2.jpg"; - + IDФайла2 = ПараметрыФункции["Bitrix24_HookFileID"]; URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ПереименоватьФайл(URL, IDФайла2, Наименование2); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереименоватьФайл (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP IDФайла = ПараметрыФункции["Bitrix24_FileID"]; URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПереименоватьФайл(URL, IDФайла, Наименование, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереименоватьФайл", "Bitrix24"); - - Проверка_БитриксОбъект(Результат); - + + Проверка_БитриксОбъект(Результат); + КонецПроцедуры Процедура Bitrix24_ПереместитьФайлВКаталог(ПараметрыФункции) - + IDКаталога = ПараметрыФункции["Bitrix24_HookSubFolderID"]; IDФайла = ПараметрыФункции["Bitrix24_FileID"]; - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ПереместитьФайлВКаталог(URL, IDФайла, IDКаталога); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереместитьФайлВКаталог (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + IDКаталога = ПараметрыФункции["Bitrix24_SubFolderID"]; URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПереместитьФайлВКаталог(URL, IDФайла, IDКаталога, Токен); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПереместитьФайлВКаталог", "Bitrix24"); - - Проверка_БитриксОбъект(Результат); - + + Проверка_БитриксОбъект(Результат); + КонецПроцедуры Процедура Bitrix24_ДобавитьФайлВЗадачу(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; IDФайла = ПараметрыФункции["Bitrix24_TaskFileID"]; - + Результат = OPI_Bitrix24.ДобавитьФайлВЗадачу(URL, IDЗадачи, IDФайла); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьФайлВЗадачу (хук)", "Bitrix24"); - + Проверка_БитриксВложение(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ДобавитьФайлВЗадачу(URL, IDЗадачи, IDФайла, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьФайлВЗадачу", "Bitrix24"); - + Проверка_БитриксВложение(Результат); - + КонецПроцедуры Процедура Bitrix24_ПроверитьДоступКЗадаче(ПараметрыФункции) - + МассивПользователей = Новый Массив; МассивПользователей.Добавить("1"); МассивПользователей.Добавить("10"); - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ПроверитьДоступКЗадаче(URL, IDЗадачи, МассивПользователей); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПроверитьДоступКЗадаче (хук)", "Bitrix24"); - + Проверка_БитриксДоступныеДействия(Результат, МассивПользователей.Количество()); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ПроверитьДоступКЗадаче(URL, IDЗадачи, МассивПользователей, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПроверитьДоступКЗадаче", "Bitrix24"); - + Проверка_БитриксДоступныеДействия(Результат, МассивПользователей.Количество()); - + КонецПроцедуры Процедура Bitrix24_ОтключитьЗвукЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ОтключитьЗвукЗадачи(URL, IDЗадачи); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтключитьЗвукЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ОтключитьЗвукЗадачи(URL, IDЗадачи, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтключитьЗвукЗадачи", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); - + КонецПроцедуры Процедура Bitrix24_ВключитьЗвукЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ВключитьЗвукЗадачи(URL, IDЗадачи); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВключитьЗвукЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ВключитьЗвукЗадачи(URL, IDЗадачи, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВключитьЗвукЗадачи", "Bitrix24"); - + Проверка_БитриксЗадача(Результат); - + КонецПроцедуры Процедура Bitrix24_ДобавитьКомментарийЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_CommentsTaskID"]; - + Текст = "Задача невыполнима, расходимся"; - + Результат = OPI_Bitrix24.ДобавитьКомментарийЗадачи(URL, IDЗадачи, Текст); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьКомментарийЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); // SKIP - + IDКомментария = Результат["result"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookCommentID", IDКомментария); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookCommentID", IDКомментария); // SKIP ПараметрыФункции.Вставить("Bitrix24_HookCommentID", IDКомментария); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Текст = "Задача выполнима, не расходимся"; - + Результат = OPI_Bitrix24.ДобавитьКомментарийЗадачи(URL, IDЗадачи, Текст, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьКомментарийЗадачи", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); - + IDКомментария = Результат["result"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_CommentID", IDКомментария); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_CommentID", IDКомментария); // SKIP ПараметрыФункции.Вставить("Bitrix24_CommentID", IDКомментария); // SKIP - + КонецПроцедуры Процедура Bitrix24_УдалитьКомментарийЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_CommentsTaskID"]; IDКомментария = ПараметрыФункции["Bitrix24_HookCommentID"]; - + Результат = OPI_Bitrix24.УдалитьКомментарийЗадачи(URL, IDЗадачи, IDКомментария); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьКомментарийЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDКомментария = ПараметрыФункции["Bitrix24_CommentID"]; - + Результат = OPI_Bitrix24.УдалитьКомментарийЗадачи(URL, IDЗадачи, IDКомментария, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьКомментарийЗадачи", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_СоздатьРезультатИзКомментария(ПараметрыФункции) URL = ПараметрыФункции["Bitrix24_URL"]; IDКомментария = ПараметрыФункции["Bitrix24_HookCommentID"]; - + Результат = OPI_Bitrix24.СоздатьРезультатИзКомментария(URL, IDКомментария); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьРезультатИзКомментария (хук)", "Bitrix24"); - + Проверка_БитриксРезультат(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDКомментария = ПараметрыФункции["Bitrix24_CommentID"]; - + Результат = OPI_Bitrix24.СоздатьРезультатИзКомментария(URL, IDКомментария, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьРезультатИзКомментария", "Bitrix24"); - + Проверка_БитриксРезультат(Результат); - + КонецПроцедуры Процедура Bitrix24_УдалитьРезультатИзКомментария(ПараметрыФункции) Экспорт URL = ПараметрыФункции["Bitrix24_URL"]; IDКомментария = ПараметрыФункции["Bitrix24_HookCommentID"]; - + Результат = OPI_Bitrix24.УдалитьРезультатИзКомментария(URL, IDКомментария); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьРезультатИзКомментария (хук)", "Bitrix24"); - + Проверка_БитриксНеопределено(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDКомментария = ПараметрыФункции["Bitrix24_CommentID"]; - + Результат = OPI_Bitrix24.УдалитьРезультатИзКомментария(URL, IDКомментария, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьРезультатИзКомментария", "Bitrix24"); - + Проверка_БитриксНеопределено(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьСписокРезультатов(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_CommentsTaskID"]; - + Результат = OPI_Bitrix24.ПолучитьСписокРезультатов(URL, IDЗадачи); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокРезультатов (хук)", "Bitrix24"); - + Проверка_БитриксСписокРезультатов(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьСписокРезультатов(URL, IDЗадачи, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокРезультатов", "Bitrix24"); - + Проверка_БитриксСписокРезультатов(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьСписокКомментариевЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_CommentsTaskID"]; - + Результат = OPI_Bitrix24.ПолучитьСписокКомментариевЗадачи(URL, IDЗадачи); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокКомментариевЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксСписокКомментариев(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьСписокКомментариевЗадачи(URL, IDЗадачи, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокКомментариевЗадачи", "Bitrix24"); - + Проверка_БитриксСписокКомментариев(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьКомменатрийЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDКомментария = ПараметрыФункции["Bitrix24_HookCommentID"]; IDЗадачи = ПараметрыФункции["Bitrix24_CommentsTaskID"]; - + Результат = OPI_Bitrix24.ПолучитьКомменатрийЗадачи(URL, IDЗадачи, IDКомментария); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьКомменатрийЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксКомментарий(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDКомментария = ПараметрыФункции["Bitrix24_CommentID"]; - + Результат = OPI_Bitrix24.ПолучитьКомменатрийЗадачи(URL, IDЗадачи, IDКомментария, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьКомменатрийЗадачи", "Bitrix24"); - + Проверка_БитриксКомментарий(Результат); - + КонецПроцедуры Процедура Bitrix24_ИзменитьКомментарийЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_CommentsTaskID"]; IDКомментария = ПараметрыФункции["Bitrix24_HookCommentID"]; - + Текст = "Задача изменена, не расходимся"; - + Результат = OPI_Bitrix24.ИзменитьКомментарийЗадачи(URL, IDЗадачи, IDКомментария, Текст); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьКомментарийЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDКомментария = ПараметрыФункции["Bitrix24_CommentID"]; - + Текст = "Задача изменена, расходимся"; - + Результат = OPI_Bitrix24.ИзменитьКомментарийЗадачи(URL, IDЗадачи, IDКомментария, Текст, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьКомментарийЗадачи", "Bitrix24"); - + Проверка_БитриксИстина(Результат); КонецПроцедуры Процедура Bitrix24_СоздатьЗависимостьЗадач(ПараметрыФункции) - + IDИсточника = ПараметрыФункции["Bitrix24_HookTaskID"]; IDПриемника = ПараметрыФункции["Bitrix24_TaskID"]; ТипСвязи = 0; - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.СоздатьЗависимостьЗадач(URL, IDИсточника, IDПриемника, ТипСвязи); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьЗависимостьЗадач (хук)", "Bitrix24"); - + Проверка_БитриксМассив(Результат); // SKIP - + Результат = OPI_Bitrix24.УдалитьЗависимостьЗадач(URL, IDИсточника, IDПриемника, ТипСвязи); // SKIP - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьЗависимостьЗадач (хук)", "Bitrix24"); - + IDИсточника = ПараметрыФункции["Bitrix24_TaskID"]; IDПриемника = ПараметрыФункции["Bitrix24_HookTaskID"]; ТипСвязи = 2; - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.СоздатьЗависимостьЗадач(URL, IDИсточника, IDПриемника, ТипСвязи, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьЗависимостьЗадач", "Bitrix24"); - - Проверка_БитриксМассив(Результат); - + + Проверка_БитриксМассив(Результат); + Результат = OPI_Bitrix24.УдалитьЗависимостьЗадач(URL, IDИсточника, IDПриемника, ТипСвязи, Токен); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьЗависимостьЗадач", "Bitrix24"); - + КонецПроцедуры Процедура Bitrix24_ДобавитьСтадиюКанбана(ПараметрыФункции) - + Наименование = "Новая стадия"; Цвет = "0026FF"; - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ДобавитьСтадиюКанбана(URL, Наименование, Цвет, 6); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьСтадиюКанбана (хук)", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); // SKIP - + IDПредыдущей = Результат["result"]; - - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookStageID", IDПредыдущей); // SKIP + + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookStageID", IDПредыдущей); // SKIP ПараметрыФункции.Вставить("Bitrix24_HookStageID", IDПредыдущей); // SKIP - + Наименование = "Новая стадия 2"; Цвет = "0026FF"; - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ДобавитьСтадиюКанбана(URL, Наименование, Цвет, IDПредыдущей, , Истина, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьСтадиюКанбана", "Bitrix24"); - - Проверка_БитриксЧисло(Результат); - + + Проверка_БитриксЧисло(Результат); + IDСтадии = Результат["result"]; - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_StageID", IDСтадии); - ПараметрыФункции.Вставить("Bitrix24_StageID", IDСтадии); - + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_StageID", IDСтадии); + ПараметрыФункции.Вставить("Bitrix24_StageID", IDСтадии); + КонецПроцедуры Процедура Bitrix24_УдалитьСтадиюКанбана(ПараметрыФункции) - + IDСтадии = ПараметрыФункции["Bitrix24_HookStageID"]; - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.УдалитьСтадиюКанбана(URL, IDСтадии, Истина); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьСтадиюКанбана (хук)", "Bitrix24"); - - Проверка_БитриксИстина(Результат); // SKIP - + + Проверка_БитриксИстина(Результат); // SKIP + IDСтадии = ПараметрыФункции["Bitrix24_StageID"]; - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.УдалитьСтадиюКанбана(URL, IDСтадии, , Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьСтадиюКанбана", "Bitrix24"); - - Проверка_БитриксИстина(Результат); - + + Проверка_БитриксИстина(Результат); + КонецПроцедуры Процедура Bitrix24_ПолучитьСтадииКанбана(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ПолучитьСтадииКанбана(URL, , Истина); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСтадииКанбана (хук)", "Bitrix24"); - - Проверка_БитриксСоответствие(Результат); // SKIP - + + Проверка_БитриксСоответствие(Результат); // SKIP + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьСтадииКанбана(URL, , , Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСтадииКанбана", "Bitrix24"); - - Проверка_БитриксСоответствие(Результат); - + + Проверка_БитриксСоответствие(Результат); + КонецПроцедуры Процедура Bitrix24_ПеренестиЗадачуВСтадиюКанбана(ПараметрыФункции) - - IDЗадачи = ПараметрыФункции["Bitrix24_KanbanTaskID"]; + + IDЗадачи = ПараметрыФункции["Bitrix24_KanbanTaskID"]; IDСтадии = ПараметрыФункции["Bitrix24_HookStageID"]; - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ПеренестиЗадачуВСтадиюКанбана(URL, IDЗадачи, IDСтадии); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПеренестиЗадачуВСтадиюКанбана (хук)", "Bitrix24"); - - Проверка_БитриксИстина(Результат); // SKIP - + + Проверка_БитриксИстина(Результат); // SKIP + IDСтадии = ПараметрыФункции["Bitrix24_StageID"]; - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПеренестиЗадачуВСтадиюКанбана(URL, IDЗадачи, IDСтадии, , , Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПеренестиЗадачуВСтадиюКанбана", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + OPI_Bitrix24.ПеренестиЗадачуВСтадиюКанбана(URL, IDЗадачи, 2, , , Токен); - + КонецПроцедуры Процедура Bitrix24_ИзменитьСтадиюКанбана(ПараметрыФункции) - + Наименование = "Новое имя стадии стадии"; Цвет = "000000"; IDСтадии = ПараметрыФункции["Bitrix24_HookStageID"]; - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ИзменитьСтадиюКанбана(URL, Наименование, IDСтадии, Цвет); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьСтадиюКанбана (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + Наименование = "Новое имя стадии стадии 2"; Цвет = "000000"; IDСтадии = ПараметрыФункции["Bitrix24_StageID"]; - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ИзменитьСтадиюКанбана(URL, Наименование, IDСтадии, Цвет, 6, Истина, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьСтадиюКанбана", "Bitrix24"); - - Проверка_БитриксИстина(Результат); - + + Проверка_БитриксИстина(Результат); + КонецПроцедуры Процедура Bitrix24_ДобавитьЭлементЧеклистаЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Текст = "Пункт чек-листа"; - + Результат = OPI_Bitrix24.ДобавитьЭлементЧеклистаЗадачи(URL, IDЗадачи, Текст, Истина); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьЭлементЧеклистаЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); // SKIP - + IDЭлемента = Результат["result"]; // SKIP - - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookCheckElementID", IDЭлемента); // SKIP + + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookCheckElementID", IDЭлемента); // SKIP ПараметрыФункции.Вставить("Bitrix24_HookCheckElementID", IDЭлемента); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ДобавитьЭлементЧеклистаЗадачи(URL, IDЗадачи, Текст, , Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьЭлементЧеклистаЗадачи", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); - - IDЭлемента = Результат["result"]; - - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_CheckElementID", IDЭлемента); - ПараметрыФункции.Вставить("Bitrix24_CheckElementID", IDЭлемента); - + + IDЭлемента = Результат["result"]; + + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_CheckElementID", IDЭлемента); + ПараметрыФункции.Вставить("Bitrix24_CheckElementID", IDЭлемента); + КонецПроцедуры Процедура Bitrix24_ИзменитьЭлементЧеклистаЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; IDЭлемента = ПараметрыФункции["Bitrix24_HookCheckElementID"]; - + Текст = "Новый текст пункта чек-листа"; - + Результат = OPI_Bitrix24.ИзменитьЭлементЧеклистаЗадачи(URL, IDЗадачи, IDЭлемента, Текст); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьЭлементЧеклистаЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксНеопределено(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; IDЭлемента = ПараметрыФункции["Bitrix24_CheckElementID"]; - + Результат = OPI_Bitrix24.ИзменитьЭлементЧеклистаЗадачи(URL, IDЗадачи, IDЭлемента, Текст, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьЭлементЧеклистаЗадачи", "Bitrix24"); - + Проверка_БитриксНеопределено(Результат); - + КонецПроцедуры Процедура Bitrix24_УдалитьЭлементЧеклистаЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; IDЭлемента = ПараметрыФункции["Bitrix24_HookCheckElementID"]; - + Результат = OPI_Bitrix24.УдалитьЭлементЧеклистаЗадачи(URL, IDЗадачи, IDЭлемента); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьЭлементЧеклистаЗадачи (хук)", "Bitrix24"); - - Проверка_БитриксИстина(Результат); // SKIP - + + Проверка_БитриксИстина(Результат); // SKIP + IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; IDЭлемента = ПараметрыФункции["Bitrix24_CheckElementID"]; - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.УдалитьЭлементЧеклистаЗадачи(URL, IDЗадачи, IDЭлемента, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьЭлементЧеклистаЗадачи", "Bitrix24"); - - Проверка_БитриксИстина(Результат); - + + Проверка_БитриксИстина(Результат); + КонецПроцедуры Процедура Bitrix24_ПолучитьЧеклистЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; - + Результат = OPI_Bitrix24.ПолучитьЧеклистЗадачи(URL, IDЗадачи); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьЧеклистЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксМассив(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; - + Результат = OPI_Bitrix24.ПолучитьЧеклистЗадачи(URL, IDЗадачи, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьЧеклистЗадачи", "Bitrix24"); - + Проверка_БитриксМассив(Результат); КонецПроцедуры Процедура Bitrix24_ПолучитьЭлементЧеклистаЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; IDЭлемента = ПараметрыФункции["Bitrix24_HookCheckElementID"]; - + Результат = OPI_Bitrix24.ПолучитьЭлементЧеклистаЗадачи(URL, IDЗадачи, IDЭлемента); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьЭлементЧеклистаЗадачи (хук)", "Bitrix24"); - - Проверка_БитриксОбъект(Результат); // SKIP - + + Проверка_БитриксОбъект(Результат); // SKIP + IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; IDЭлемента = ПараметрыФункции["Bitrix24_CheckElementID"]; - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьЭлементЧеклистаЗадачи(URL, IDЗадачи, IDЭлемента, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьЭлементЧеклистаЗадачи", "Bitrix24"); - - Проверка_БитриксОбъект(Результат); - + + Проверка_БитриксОбъект(Результат); + КонецПроцедуры Процедура Bitrix24_ВыполнитьЭлементЧеклистаЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; IDЭлемента = ПараметрыФункции["Bitrix24_HookCheckElementID"]; - + Результат = OPI_Bitrix24.ВыполнитьЭлементЧеклистаЗадачи(URL, IDЗадачи, IDЭлемента); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВыполнитьЭлементЧеклистаЗадачи (хук)", "Bitrix24"); - - Проверка_БитриксИстина(Результат); // SKIP - + + Проверка_БитриксИстина(Результат); // SKIP + IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; IDЭлемента = ПараметрыФункции["Bitrix24_CheckElementID"]; - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ВыполнитьЭлементЧеклистаЗадачи(URL, IDЗадачи, IDЭлемента, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВыполнитьЭлементЧеклистаЗадачи", "Bitrix24"); - - Проверка_БитриксИстина(Результат); - + + Проверка_БитриксИстина(Результат); + КонецПроцедуры Процедура Bitrix24_ВозобновитьЭлементЧеклистаЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_HookTaskID"]; IDЭлемента = ПараметрыФункции["Bitrix24_HookCheckElementID"]; - + Результат = OPI_Bitrix24.ВозобновитьЭлементЧеклистаЗадачи(URL, IDЗадачи, IDЭлемента); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВозобновитьЭлементЧеклистаЗадачи (хук)", "Bitrix24"); - - Проверка_БитриксИстина(Результат); // SKIP - + + Проверка_БитриксИстина(Результат); // SKIP + IDЗадачи = ПараметрыФункции["Bitrix24_TaskID"]; IDЭлемента = ПараметрыФункции["Bitrix24_CheckElementID"]; - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ВозобновитьЭлементЧеклистаЗадачи(URL, IDЗадачи, IDЭлемента, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВозобновитьЭлементЧеклистаЗадачи", "Bitrix24"); - - Проверка_БитриксИстина(Результат); - + + Проверка_БитриксИстина(Результат); + КонецПроцедуры Процедура Bitrix24_ДобавитьТрудозатратыЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_ElapsedTaskID"]; - + Время = 3600; - + Результат = OPI_Bitrix24.ДобавитьТрудозатратыЗадачи(URL, IDЗадачи, Время); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьТрудозатратыЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); // SKIP - + IDЗатрат = Результат["result"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookTimeID", IDЗатрат); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookTimeID", IDЗатрат); // SKIP ПараметрыФункции.Вставить("Bitrix24_HookTimeID", IDЗатрат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Текст = "Трудозатраты по обработке"; IDПользователя = 10; Время = 7200; ДатаУстановки = ДобавитьМесяц(OPI_Инструменты.ПолучитьТекущуюДату(), -1); - + Результат = OPI_Bitrix24.ДобавитьТрудозатратыЗадачи(URL , IDЗадачи , Время @@ -8501,42 +8501,42 @@ , Текст , ДатаУстановки , Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьТрудозатратыЗадачи", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); - - IDЗатрат = Результат["result"]; - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_TimeID", IDЗатрат); - ПараметрыФункции.Вставить("Bitrix24_TimeID", IDЗатрат); - + + IDЗатрат = Результат["result"]; + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_TimeID", IDЗатрат); + ПараметрыФункции.Вставить("Bitrix24_TimeID", IDЗатрат); + КонецПроцедуры Процедура Bitrix24_ИзменитьТрудозатратыЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_ElapsedTaskID"]; IDЗаписи = ПараметрыФункции["Bitrix24_HookTimeID"]; - + Текст = "Забытый в прошлый раз текст"; Время = 4800; - + Результат = OPI_Bitrix24.ИзменитьТрудозатратыЗадачи(URL, IDЗадачи, IDЗаписи, Время, Текст); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьТрудозатратыЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксНеопределено(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗаписи = ПараметрыФункции["Bitrix24_TimeID"]; - + Текст = "Новые трудозатраты по обработке"; Время = 4800; ДатаУстановки = ДобавитьМесяц(OPI_Инструменты.ПолучитьТекущуюДату(), -1); - + Результат = OPI_Bitrix24.ИзменитьТрудозатратыЗадачи(URL , IDЗадачи , IDЗаписи @@ -8544,125 +8544,125 @@ , Текст , ДатаУстановки , Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьТрудозатратыЗадачи", "Bitrix24"); - - Проверка_БитриксНеопределено(Результат); - + + Проверка_БитриксНеопределено(Результат); + КонецПроцедуры Процедура Bitrix24_УдалитьТрудозатратыЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_ElapsedTaskID"]; IDЗаписи = ПараметрыФункции["Bitrix24_HookTimeID"]; - + Результат = OPI_Bitrix24.УдалитьТрудозатратыЗадачи(URL, IDЗадачи, IDЗаписи); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьТрудозатратыЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксНеопределено(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗаписи = ПараметрыФункции["Bitrix24_TimeID"]; - + Результат = OPI_Bitrix24.УдалитьТрудозатратыЗадачи(URL, IDЗадачи, IDЗаписи, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьТрудозатратыЗадачи", "Bitrix24"); - + Проверка_БитриксНеопределено(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьТрудозатратыЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_ElapsedTaskID"]; IDЗаписи = ПараметрыФункции["Bitrix24_HookTimeID"]; - + Результат = OPI_Bitrix24.ПолучитьТрудозатратыЗадачи(URL, IDЗадачи, IDЗаписи); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьТрудозатратыЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЗаписи = ПараметрыФункции["Bitrix24_TimeID"]; - + Результат = OPI_Bitrix24.ПолучитьТрудозатратыЗадачи(URL, IDЗадачи, IDЗаписи, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьТрудозатратыЗадачи", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьСписокТрудозатратЗадачи(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЗадачи = ПараметрыФункции["Bitrix24_ElapsedTaskID"]; - + Результат = OPI_Bitrix24.ПолучитьСписокТрудозатратЗадачи(URL, IDЗадачи); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокТрудозатратЗадачи (хук)", "Bitrix24"); - + Проверка_БитриксМассивОбъектов(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьСписокТрудозатратЗадачи(URL, IDЗадачи, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокТрудозатратЗадачи", "Bitrix24"); - + Проверка_БитриксМассивОбъектов(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьПланЗадачНаДень(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.ПолучитьПланЗадачНаДень(URL); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьПланЗадачНаДень (хук)", "Bitrix24"); - + Проверка_БитриксМассив(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьПланЗадачНаДень(URL, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьПланЗадачНаДень", "Bitrix24"); - + Проверка_БитриксМассив(Результат); - + КонецПроцедуры Процедура Bitrix24_СоздатьЧат(ПараметрыФункции) - + Картинка = ПараметрыФункции["Picture"]; OPI_ПреобразованиеТипов.ПолучитьДвоичныеДанные(Картинка); - + B64Картинка = ПолучитьBase64СтрокуИзДвоичныхДанных(Картинка); - + МассивУчастников = Новый Массив; МассивУчастников.Добавить(10); МассивУчастников.Добавить(1); - + СтруктураЧата = Новый Структура; СтруктураЧата.Вставить("TYPE" , "OPEN"); СтруктураЧата.Вставить("TITLE" , "Новый чат"); @@ -8672,866 +8672,866 @@ СтруктураЧата.Вставить("USERS" , МассивУчастников); СтруктураЧата.Вставить("AVATAR" , B64Картинка); СтруктураЧата.Вставить("OWNER_ID" , 1); - + URL = ПараметрыФункции["Bitrix24_URL"]; - + Результат = OPI_Bitrix24.СоздатьЧат(URL, СтруктураЧата); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьЧат (хук)", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); // SKIP - + IDЧата = Результат["result"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookChatID", IDЧата); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_HookChatID", IDЧата); // SKIP ПараметрыФункции.Вставить("Bitrix24_HookChatID", IDЧата); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + СтруктураЧата = Новый Структура; СтруктураЧата.Вставить("TYPE" , "CHAT"); СтруктураЧата.Вставить("TITLE" , "Закрытый чат"); СтруктураЧата.Вставить("USERS" , МассивУчастников); - + Результат = OPI_Bitrix24.СоздатьЧат(URL, СтруктураЧата, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьЧат", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); - + IDЧата = Результат["result"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_ChatID", IDЧата); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_ChatID", IDЧата); // SKIP ПараметрыФункции.Вставить("Bitrix24_ChatID", IDЧата); // SKIP - + КонецПроцедуры Процедура Bitrix24_ПолучитьСписокПользователейЧата(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; - + Результат = OPI_Bitrix24.ПолучитьСписокПользователейЧата(URL, IDЧата); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокПользователейЧата (хук)", "Bitrix24"); - + Проверка_БитриксМассив(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЧата = ПараметрыФункции["Bitrix24_ChatID"]; - + Результат = OPI_Bitrix24.ПолучитьСписокПользователейЧата(URL, IDЧата, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокПользователейЧата", "Bitrix24"); - + Проверка_БитриксМассив(Результат); - + КонецПроцедуры Процедура Bitrix24_ПокинутьЧат(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; - + Результат = OPI_Bitrix24.ПокинутьЧат(URL, IDЧата); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПокинутьЧат (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЧата = ПараметрыФункции["Bitrix24_ChatID"]; - + Результат = OPI_Bitrix24.ПокинутьЧат(URL, IDЧата, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПокинутьЧат", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ИсключитьПользователяИзЧата(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; - + IDПользователя = 10; - + Результат = OPI_Bitrix24.ИсключитьПользователяИзЧата(URL, IDЧата, IDПользователя); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИсключитьПользователяИзЧата (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЧата = ПараметрыФункции["Bitrix24_ChatID"]; - + Результат = OPI_Bitrix24.ИсключитьПользователяИзЧата(URL, IDЧата, IDПользователя, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИсключитьПользователяИзЧата", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ДобавитьПользователейВЧат(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; - + IDПользователей = Новый Массив; IDПользователей.Добавить(10); IDПользователей.Добавить(12); - + Результат = OPI_Bitrix24.ДобавитьПользователейВЧат(URL, IDЧата, IDПользователей); // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьПользователейВЧат (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЧата = ПараметрыФункции["Bitrix24_ChatID"]; IDПользователя = 10; - + Результат = OPI_Bitrix24.ДобавитьПользователейВЧат(URL, IDЧата, IDПользователя, Истина, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ДобавитьПользователейВЧат", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ИзменитьЗаголовокЧата(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; - + Заголовок = "Новый заголовок чата"; - + Результат = OPI_Bitrix24.ИзменитьЗаголовокЧата(URL, IDЧата, Заголовок); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьЗаголовокЧата (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЧата = ПараметрыФункции["Bitrix24_ChatID"]; - + Заголовок = "Другой заголовок чата"; - + Результат = OPI_Bitrix24.ИзменитьЗаголовокЧата(URL, IDЧата, Заголовок, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьЗаголовокЧата", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ИзменитьЦветЧата(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; - + Цвет = "AZURE"; - + Результат = OPI_Bitrix24.ИзменитьЦветЧата(URL, IDЧата, Цвет); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьЦветЧата (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЧата = ПараметрыФункции["Bitrix24_ChatID"]; - + Цвет = "PURPLE"; - + Результат = OPI_Bitrix24.ИзменитьЦветЧата(URL, IDЧата, Цвет, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьЦветЧата", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ИзменитьКартинкуЧата(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; Картинка = ПараметрыФункции["Picture2"]; - + Результат = OPI_Bitrix24.ИзменитьКартинкуЧата(URL, IDЧата, Картинка); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьКартинкуЧата (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЧата = ПараметрыФункции["Bitrix24_ChatID"]; Результат = OPI_Bitrix24.ИзменитьКартинкуЧата(URL, IDЧата, Картинка, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьКартинкуЧата", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ОтключитьУведомленияЧата(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; - + Результат = OPI_Bitrix24.ОтключитьУведомленияЧата(URL, IDЧата); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтключитьУведомленияЧата (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЧата = ПараметрыФункции["Bitrix24_ChatID"]; - + Результат = OPI_Bitrix24.ОтключитьУведомленияЧата(URL, IDЧата, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтключитьУведомленияЧата", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ВключитьУведомленияЧата(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; - + Результат = OPI_Bitrix24.ВключитьУведомленияЧата(URL, IDЧата); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВключитьУведомленияЧата (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЧата = ПараметрыФункции["Bitrix24_ChatID"]; - + Результат = OPI_Bitrix24.ВключитьУведомленияЧата(URL, IDЧата, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ВключитьУведомленияЧата", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_СменитьВладельцаЧата(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; - + IDПользователя = 10; - + Результат = OPI_Bitrix24.СменитьВладельцаЧата(URL, IDЧата, IDПользователя); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СменитьВладельцаЧата (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЧата = ПараметрыФункции["Bitrix24_ChatID"]; - + Результат = OPI_Bitrix24.СменитьВладельцаЧата(URL, IDЧата, IDПользователя, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СменитьВладельцаЧата", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьСписокСообщенийЧата(ПараметрыФункции) URL = ПараметрыФункции["Bitrix24_URL"]; - IDЧата = "chat4"; - + IDЧата = "chat4"; + Результат = OPI_Bitrix24.ПолучитьСписокСообщенийЧата(URL, IDЧата); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокСообщенийЧата (хук)", "Bitrix24"); - + Проверка_БитриксСообщения(Результат); // SKIP - + IDСообщения = Результат["result"]["messages"][0]["id"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_ChatMessageID", IDСообщения); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_ChatMessageID", IDСообщения); // SKIP ПараметрыФункции.Вставить("Bitrix24_ChatMessageID", IDСообщения); // SKIP URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDПользователя = 10; - + Результат = OPI_Bitrix24.ПолучитьСписокСообщенийЧата(URL, IDПользователя, , 0, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокСообщенийЧата", "Bitrix24"); - + Проверка_БитриксСообщения(Результат); - - IDСообщения = Результат["result"]["messages"][0]["id"]; - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_UserMessageID", IDСообщения); - ПараметрыФункции.Вставить("Bitrix24_UserMessageID", IDСообщения); - + + IDСообщения = Результат["result"]["messages"][0]["id"]; + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_UserMessageID", IDСообщения); + ПараметрыФункции.Вставить("Bitrix24_UserMessageID", IDСообщения); + КонецПроцедуры Процедура Bitrix24_ОтметитьСообщениеКакПрочитанное(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; - IDЧата = "chat" + ПараметрыФункции["Bitrix24_HookChatID"]; + IDЧата = "chat" + ПараметрыФункции["Bitrix24_HookChatID"]; IDСообщения = ПараметрыФункции["Bitrix24_ChatMessageID"]; - + Результат = OPI_Bitrix24.ОтметитьСообщениеКакПрочитанное(URL, IDЧата, IDСообщения); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтметитьСообщениеКакПрочитанное (хук)", "Bitrix24"); - + Проверка_БитриксДиалог(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDПользователя = 10; IDСообщения = ПараметрыФункции["Bitrix24_UserMessageID"]; - + Результат = OPI_Bitrix24.ОтметитьСообщениеКакПрочитанное(URL, IDПользователя, IDСообщения, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтметитьСообщениеКакПрочитанное", "Bitrix24"); - + Проверка_БитриксДиалог(Результат); - + КонецПроцедуры Процедура Bitrix24_ОтметитьСообщениеКакНепрочитанное(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; - IDЧата = "chat" + ПараметрыФункции["Bitrix24_HookChatID"]; + IDЧата = "chat" + ПараметрыФункции["Bitrix24_HookChatID"]; IDСообщения = ПараметрыФункции["Bitrix24_ChatMessageID"]; - + Результат = OPI_Bitrix24.ОтметитьСообщениеКакНепрочитанное(URL, IDЧата, IDСообщения); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтметитьСообщениеКакНепрочитанное (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDПользователя = 10; IDСообщения = ПараметрыФункции["Bitrix24_UserMessageID"]; - + Результат = OPI_Bitrix24.ОтметитьСообщениеКакНепрочитанное(URL, IDПользователя, IDСообщения, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтметитьСообщениеКакНепрочитанное", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьДиалог(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; - IDЧата = "chat" + ПараметрыФункции["Bitrix24_HookChatID"]; + IDЧата = "chat" + ПараметрыФункции["Bitrix24_HookChatID"]; Результат = OPI_Bitrix24.ПолучитьДиалог(URL, IDЧата); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьДиалог (хук)", "Bitrix24"); - + Проверка_БитриксСообщение(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDПользователя = 10; - + Результат = OPI_Bitrix24.ПолучитьДиалог(URL, IDПользователя, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьДиалог", "Bitrix24"); - + Проверка_БитриксСообщение(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьСписокПользователейДиалога(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; - IDЧата = "chat" + ПараметрыФункции["Bitrix24_HookChatID"]; + IDЧата = "chat" + ПараметрыФункции["Bitrix24_HookChatID"]; Результат = OPI_Bitrix24.ПолучитьСписокПользователейДиалога(URL, IDЧата); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокПользователейДиалога (хук)", "Bitrix24"); - + Проверка_БитриксМассив(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDПользователя = 10; - + Результат = OPI_Bitrix24.ПолучитьСписокПользователейДиалога(URL, IDПользователя, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСписокПользователейДиалога", "Bitrix24"); - + Проверка_БитриксМассив(Результат); - + КонецПроцедуры Процедура Bitrix24_ОтправитьУведомлениеОВводе(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; - IDЧата = "chat" + ПараметрыФункции["Bitrix24_HookChatID"]; + IDЧата = "chat" + ПараметрыФункции["Bitrix24_HookChatID"]; Результат = OPI_Bitrix24.ОтправитьУведомлениеОВводе(URL, IDЧата); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьУведомлениеОВводе (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDПользователя = 10; - + Результат = OPI_Bitrix24.ОтправитьУведомлениеОВводе(URL, IDПользователя, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьУведомлениеОВводе", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ПрочитатьВсе(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; Результат = OPI_Bitrix24.ПрочитатьВсе(URL); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПрочитатьВсе (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПрочитатьВсе(URL, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПрочитатьВсе", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ОтправитьСообщение(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; - IDЧата = "chat" + ПараметрыФункции["Bitrix24_HookChatID"]; + IDЧата = "chat" + ПараметрыФункции["Bitrix24_HookChatID"]; Текст = "Текст сообщения"; Картинка = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/service/test_data/picture.jpg"; - Файл = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; - + Файл = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; + Вложения = Новый Массив; Вложения.Добавить(OPI_Bitrix24.ПолучитьБлокКартинки("Картинка1", Картинка)); - Вложения.Добавить(OPI_Bitrix24.ПолучитьБлокФайла("Файл1.docx", Файл)); + Вложения.Добавить(OPI_Bitrix24.ПолучитьБлокФайла("Файл1.docx" , Файл)); Результат = OPI_Bitrix24.ОтправитьСообщение(URL, IDЧата, Текст, Вложения); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьСообщение (хук)", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); // SKIP - + IDСообщения = Результат["result"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_ChatMessageID", IDСообщения); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_ChatMessageID", IDСообщения); // SKIP ПараметрыФункции.Вставить("Bitrix24_ChatMessageID", IDСообщения); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDПользователя = 10; - + Результат = OPI_Bitrix24.ОтправитьСообщение(URL, IDПользователя, Текст, , Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьСообщение", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); - - IDСообщения = Результат["result"]; - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_UserMessageID", IDСообщения); - ПараметрыФункции.Вставить("Bitrix24_UserMessageID", IDСообщения); - + + IDСообщения = Результат["result"]; + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_UserMessageID", IDСообщения); + ПараметрыФункции.Вставить("Bitrix24_UserMessageID", IDСообщения); + КонецПроцедуры Процедура Bitrix24_ИзменитьСообщение(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDСообщения = ПараметрыФункции["Bitrix24_ChatMessageID"]; - + Текст = "Новый текст сообщения"; Результат = OPI_Bitrix24.ИзменитьСообщение(URL, IDСообщения, Текст); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьСообщение (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDСообщения = ПараметрыФункции["Bitrix24_UserMessageID"]; - + Картинка = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/service/test_data/picture.jpg"; - Файл = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; - + Файл = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; + Вложения = Новый Массив; Вложения.Добавить(OPI_Bitrix24.ПолучитьБлокКартинки("Картинка1", Картинка)); - Вложения.Добавить(OPI_Bitrix24.ПолучитьБлокФайла("Файл1.docx", Файл)); - + Вложения.Добавить(OPI_Bitrix24.ПолучитьБлокФайла("Файл1.docx" , Файл)); + Результат = OPI_Bitrix24.ИзменитьСообщение(URL, IDСообщения, Текст, Вложения, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ИзменитьСообщение", "Bitrix24"); - - Проверка_БитриксИстина(Результат); - + + Проверка_БитриксИстина(Результат); + КонецПроцедуры Процедура Bitrix24_УдалитьСообщение(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDСообщения = ПараметрыФункции["Bitrix24_ChatMessageID"]; Результат = OPI_Bitrix24.УдалитьСообщение(URL, IDСообщения); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьСообщение (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDСообщения = ПараметрыФункции["Bitrix24_UserMessageID"]; - + Результат = OPI_Bitrix24.УдалитьСообщение(URL, IDСообщения, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьСообщение", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_УстановитьРеакциюНаСообщение(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDСообщения = ПараметрыФункции["Bitrix24_ChatMessageID"]; Результат = OPI_Bitrix24.УстановитьРеакциюНаСообщение(URL, IDСообщения); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УстановитьРеакциюНаСообщение (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDСообщения = ПараметрыФункции["Bitrix24_UserMessageID"]; - + Результат = OPI_Bitrix24.УстановитьРеакциюНаСообщение(URL, IDСообщения, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УстановитьРеакциюНаСообщение", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьКаталогФайловЧата(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; - IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; + IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; Результат = OPI_Bitrix24.ПолучитьКаталогФайловЧата(URL, IDЧата); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьКаталогФайловЧата (хук)", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЧата = ПараметрыФункции["Bitrix24_ChatID"]; - + Результат = OPI_Bitrix24.ПолучитьКаталогФайловЧата(URL, IDЧата, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьКаталогФайловЧата", "Bitrix24"); - + Проверка_БитриксОбъект(Результат); - + КонецПроцедуры Процедура Bitrix24_ОтправитьФайл(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; - IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; + IDЧата = ПараметрыФункции["Bitrix24_HookChatID"]; Файл = ПараметрыФункции["Document"]; // Двоичные данные, URL или путь к файлу Описание = "Очень важный файл"; - + Каталог = OPI_Bitrix24.ПолучитьКаталогФайловЧата(URL, IDЧата); IDКаталога = Каталог["result"]["ID"]; - + ЗагруженныйФайл = OPI_Bitrix24.ЗагрузитьФайлВКаталог(URL, "Важный документ.docx", Файл, IDКаталога); IDФайла = ЗагруженныйФайл["result"]["ID"]; Результат = OPI_Bitrix24.ОтправитьФайл(URL, IDЧата, IDФайла, Описание); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьФайл (хук)", "Bitrix24"); - + Проверка_БитриксФайлСообщение(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDЧата = ПараметрыФункции["Bitrix24_ChatID"]; - + Каталог = OPI_Bitrix24.ПолучитьКаталогФайловЧата(URL, IDЧата, Токен); IDКаталога = Каталог["result"]["ID"]; - + ЗагруженныйФайл = OPI_Bitrix24.ЗагрузитьФайлВКаталог(URL, "Важный документ.docx", Файл, IDКаталога, Токен); IDФайла = ЗагруженныйФайл["result"]["ID"]; Результат = OPI_Bitrix24.ОтправитьФайл(URL, IDЧата, IDФайла, Описание, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ОтправитьФайл", "Bitrix24"); - + Проверка_БитриксФайлСообщение(Результат); КонецПроцедуры Процедура Bitrix24_ПолучитьПользователей(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; МассивПользователей = Новый Массив; - + МассивПользователей.Добавить(1); МассивПользователей.Добавить(10); Результат = OPI_Bitrix24.ПолучитьПользователей(URL, МассивПользователей); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьПользователей (хук)", "Bitrix24"); - + Проверка_БитриксСоответствие(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDПользователей = 10; - + Результат = OPI_Bitrix24.ПолучитьПользователей(URL, IDПользователей, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьПользователей", "Bitrix24"); - + Проверка_БитриксСоответствие(Результат); - + КонецПроцедуры Процедура Bitrix24_ПолучитьСтатусПользователя(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; Результат = OPI_Bitrix24.ПолучитьСтатусПользователя(URL); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСтатусПользователя (хук)", "Bitrix24"); - + Проверка_БитриксСтрока(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; - + Результат = OPI_Bitrix24.ПолучитьСтатусПользователя(URL, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьСтатусПользователя", "Bitrix24"); - + Проверка_БитриксСтрока(Результат); - + КонецПроцедуры Процедура Bitrix24_УстановитьСтатусПользователя(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; Статус = "dnd"; Результат = OPI_Bitrix24.УстановитьСтатусПользователя(URL, Статус); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УстановитьСтатусПользователя (хук)", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; Статус = "away"; - + Результат = OPI_Bitrix24.УстановитьСтатусПользователя(URL, Статус, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УстановитьСтатусПользователя", "Bitrix24"); - + Проверка_БитриксИстина(Результат); - + КонецПроцедуры Процедура Bitrix24_СоздатьПерсональноеУведомление(ПараметрыФункции) - + IDПользователя = 1; - - URL = ПараметрыФункции["Bitrix24_URL"]; + + URL = ПараметрыФункции["Bitrix24_URL"]; Текст = "Текст сообщения"; Картинка = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/service/test_data/picture.jpg"; - Файл = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; - + Файл = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; + Вложения = Новый Массив; Вложения.Добавить(OPI_Bitrix24.ПолучитьБлокКартинки("Картинка1", Картинка)); - Вложения.Добавить(OPI_Bitrix24.ПолучитьБлокФайла("Файл1.docx", Файл)); + Вложения.Добавить(OPI_Bitrix24.ПолучитьБлокФайла("Файл1.docx" , Файл)); Результат = OPI_Bitrix24.СоздатьПерсональноеУведомление(URL, IDПользователя, Текст, ,Вложения); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьПерсональноеУведомление (хук)", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); // SKIP - + IDСообщения = Результат["result"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_PersoalHookNotifyID", IDСообщения); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_PersoalHookNotifyID", IDСообщения); // SKIP ПараметрыФункции.Вставить("Bitrix24_PersoalHookNotifyID", IDСообщения); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; Тег = "Новый"; IDПользователя = 10; - + Результат = OPI_Bitrix24.СоздатьПерсональноеУведомление(URL, IDПользователя, Текст, Тег, , Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьПерсональноеУведомление", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); - - IDСообщения = Результат["result"]; - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_PersoalNotifyID", IDСообщения); - ПараметрыФункции.Вставить("Bitrix24_PersoalNotifyID", IDСообщения); - + + IDСообщения = Результат["result"]; + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_PersoalNotifyID", IDСообщения); + ПараметрыФункции.Вставить("Bitrix24_PersoalNotifyID", IDСообщения); + КонецПроцедуры Процедура Bitrix24_СоздатьСистемноеУведомление(ПараметрыФункции) - + IDПользователя = 1; - - URL = ПараметрыФункции["Bitrix24_URL"]; + + URL = ПараметрыФункции["Bitrix24_URL"]; Текст = "Текст сообщения"; Картинка = "https://raw.githubusercontent.com/Bayselonarrend/OpenIntegrations/main/service/test_data/picture.jpg"; - Файл = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; - + Файл = "https://github.com/Bayselonarrend/OpenIntegrations/raw/main/service/test_data/document.docx"; + Вложения = Новый Массив; Вложения.Добавить(OPI_Bitrix24.ПолучитьБлокКартинки("Картинка1", Картинка)); - Вложения.Добавить(OPI_Bitrix24.ПолучитьБлокФайла("Файл1.docx", Файл)); + Вложения.Добавить(OPI_Bitrix24.ПолучитьБлокФайла("Файл1.docx" , Файл)); Результат = OPI_Bitrix24.СоздатьСистемноеУведомление(URL, IDПользователя, Текст, ,Вложения); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьСистемноеУведомление (хук)", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); // SKIP - + IDСообщения = Результат["result"]; // SKIP - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_SystemHookNotifyID", IDСообщения); // SKIP + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_SystemHookNotifyID", IDСообщения); // SKIP ПараметрыФункции.Вставить("Bitrix24_SystemHookNotifyID", IDСообщения); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; Тег = "Новый"; IDПользователя = 10; - + Результат = OPI_Bitrix24.СоздатьСистемноеУведомление(URL, IDПользователя, Текст, Тег, , Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьСистемноеУведомление", "Bitrix24"); - + Проверка_БитриксЧисло(Результат); - - IDСообщения = Результат["result"]; - OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_SystemNotifyID", IDСообщения); - ПараметрыФункции.Вставить("Bitrix24_SystemNotifyID", IDСообщения); - + + IDСообщения = Результат["result"]; + OPI_ПолучениеДанныхТестов.ЗаписатьПараметр("Bitrix24_SystemNotifyID", IDСообщения); + ПараметрыФункции.Вставить("Bitrix24_SystemNotifyID", IDСообщения); + КонецПроцедуры Процедура Bitrix24_УдалитьУведомление(ПараметрыФункции) - + URL = ПараметрыФункции["Bitrix24_URL"]; IDУведомления = ПараметрыФункции["Bitrix24_PersoalHookNotifyID"]; - + Результат = OPI_Bitrix24.УдалитьУведомление(URL, IDУведомления); - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьУведомление", "Bitrix24"); - + Проверка_БитриксИстина(Результат); // SKIP - + URL = ПараметрыФункции["Bitrix24_Domain"]; Токен = ПараметрыФункции["Bitrix24_Token"]; IDУведомления = ПараметрыФункции["Bitrix24_PersoalNotifyID"]; - + Результат = OPI_Bitrix24.УдалитьУведомление(URL, IDУведомления, Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "УдалитьУведомление (приложение)", "Bitrix24"); - + Проверка_БитриксБулево(Результат); - + КонецПроцедуры #КонецОбласти @@ -9542,34 +9542,34 @@ Токен = ПараметрыФункции["YandexDisk_Token"]; Результат = OPI_YandexDisk.ПолучитьИнформациюОДиске(Токен); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "ПолучитьИнформациюОДиске", "YandexDisk"); - + Проверка_ЯДискДиск(Результат); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры Процедура YandexDisk_СоздатьПапку(ПараметрыФункции) Токен = ПараметрыФункции["YandexDisk_Token"]; Путь = "/" + Строка(Новый УникальныйИдентификатор); - + Результат = OPI_YandexDisk.СоздатьПапку(Токен, Путь); - + // END - + // !OInt OPI_ПолучениеДанныхТестов.ЗаписатьЛог(Результат, "СоздатьПапку", "YandexDisk"); - + Проверка_ЯДискКаталог(Результат, Путь); - + OPI_YandexDisk.УдалитьОбъект(Токен, Путь, Ложь); - + OPI_Инструменты.Пауза(5); - + КонецПроцедуры #КонецОбласти