From 9aabbc1b7e984d8e404eced18befaed77d37b2e3 Mon Sep 17 00:00:00 2001 From: doadmin Date: Fri, 17 Mar 2017 14:01:42 +0100 Subject: [PATCH] Publish version 0.1 --- README.md | 59 ++++ doc/AddYmGroupMembership.md | 45 +++ doc/AddYmRelationship.md | 34 +++ doc/GetYmGroup.md | 38 +++ doc/GetYmHelp.md | 27 ++ doc/GetYmMessage.md | 106 +++++++ doc/GetYmNetwork.md | 36 +++ doc/GetYmToken.md | 24 ++ doc/GetYmUser.md | 58 ++++ doc/NewYmGroup.md | 38 +++ doc/NewYmMessage.md | 48 +++ doc/NewYmUser.md | 34 +++ doc/README.md | 22 ++ doc/RemoveYmGroupMembership.md | 35 +++ doc/RemoveYmMessage.md | 25 ++ doc/SearchYmItem.md | 37 +++ doc/SendYmInvitation.md | 25 ++ doc/SetYmToken.md | 22 ++ doc/ShowYmRelationships.md | 33 ++ doc/ShowYmToken.md | 12 + scripts/CreateGroupsAndUsers.ps1 | 52 ++++ scripts/CreateUserAndGroup.ps1 | 26 ++ scripts/_StartYammerShell.bat | 1 + src/YammerShell.sln | 22 ++ .../CmdLets/AddYmGroupMembership.cs | 71 +++++ src/YammerShell/CmdLets/AddYmRelationship.cs | 111 +++++++ src/YammerShell/CmdLets/GetYmGroup.cs | 81 +++++ src/YammerShell/CmdLets/GetYmHelp.cs | 40 +++ src/YammerShell/CmdLets/GetYmMessage.cs | 233 ++++++++++++++ src/YammerShell/CmdLets/GetYmNetwork.cs | 72 +++++ src/YammerShell/CmdLets/GetYmToken.cs | 52 ++++ src/YammerShell/CmdLets/GetYmUser.cs | 289 ++++++++++++++++++ src/YammerShell/CmdLets/NewYmGroup.cs | 67 ++++ src/YammerShell/CmdLets/NewYmMessage.cs | 104 +++++++ src/YammerShell/CmdLets/NewYmUser.cs | 116 +++++++ .../CmdLets/RemoveYmGroupMembership.cs | 57 ++++ src/YammerShell/CmdLets/RemoveYmMessage.cs | 41 +++ src/YammerShell/CmdLets/SearchYmItem.cs | 220 +++++++++++++ src/YammerShell/CmdLets/SendYmInvitation.cs | 50 +++ src/YammerShell/CmdLets/SetYmToken.cs | 23 ++ .../CmdLets/ShowYmRelationships.cs | 113 +++++++ src/YammerShell/CmdLets/ShowYmToken.cs | 19 ++ src/YammerShell/Properties/AssemblyInfo.cs | 36 +++ .../Properties/Resources.Designer.cs | 90 ++++++ src/YammerShell/Properties/Resources.resx | 129 ++++++++ src/YammerShell/Request.cs | 80 +++++ src/YammerShell/YammerObjects/YammerFile.cs | 18 ++ src/YammerShell/YammerObjects/YammerGroup.cs | 19 ++ .../YammerObjects/YammerMessage.cs | 19 ++ .../YammerObjects/YammerNetwork.cs | 20 ++ .../YammerObjects/YammerRelationship.cs | 11 + .../YammerObjects/YammerSearchResult.cs | 20 ++ src/YammerShell/YammerObjects/YammerTopic.cs | 10 + src/YammerShell/YammerObjects/YammerUser.cs | 23 ++ src/YammerShell/YammerShell.csproj | 103 +++++++ src/YammerShell/packages.config | 4 + 56 files changed, 3200 insertions(+) create mode 100644 README.md create mode 100644 doc/AddYmGroupMembership.md create mode 100644 doc/AddYmRelationship.md create mode 100644 doc/GetYmGroup.md create mode 100644 doc/GetYmHelp.md create mode 100644 doc/GetYmMessage.md create mode 100644 doc/GetYmNetwork.md create mode 100644 doc/GetYmToken.md create mode 100644 doc/GetYmUser.md create mode 100644 doc/NewYmGroup.md create mode 100644 doc/NewYmMessage.md create mode 100644 doc/NewYmUser.md create mode 100644 doc/README.md create mode 100644 doc/RemoveYmGroupMembership.md create mode 100644 doc/RemoveYmMessage.md create mode 100644 doc/SearchYmItem.md create mode 100644 doc/SendYmInvitation.md create mode 100644 doc/SetYmToken.md create mode 100644 doc/ShowYmRelationships.md create mode 100644 doc/ShowYmToken.md create mode 100644 scripts/CreateGroupsAndUsers.ps1 create mode 100644 scripts/CreateUserAndGroup.ps1 create mode 100644 scripts/_StartYammerShell.bat create mode 100644 src/YammerShell.sln create mode 100644 src/YammerShell/CmdLets/AddYmGroupMembership.cs create mode 100644 src/YammerShell/CmdLets/AddYmRelationship.cs create mode 100644 src/YammerShell/CmdLets/GetYmGroup.cs create mode 100644 src/YammerShell/CmdLets/GetYmHelp.cs create mode 100644 src/YammerShell/CmdLets/GetYmMessage.cs create mode 100644 src/YammerShell/CmdLets/GetYmNetwork.cs create mode 100644 src/YammerShell/CmdLets/GetYmToken.cs create mode 100644 src/YammerShell/CmdLets/GetYmUser.cs create mode 100644 src/YammerShell/CmdLets/NewYmGroup.cs create mode 100644 src/YammerShell/CmdLets/NewYmMessage.cs create mode 100644 src/YammerShell/CmdLets/NewYmUser.cs create mode 100644 src/YammerShell/CmdLets/RemoveYmGroupMembership.cs create mode 100644 src/YammerShell/CmdLets/RemoveYmMessage.cs create mode 100644 src/YammerShell/CmdLets/SearchYmItem.cs create mode 100644 src/YammerShell/CmdLets/SendYmInvitation.cs create mode 100644 src/YammerShell/CmdLets/SetYmToken.cs create mode 100644 src/YammerShell/CmdLets/ShowYmRelationships.cs create mode 100644 src/YammerShell/CmdLets/ShowYmToken.cs create mode 100644 src/YammerShell/Properties/AssemblyInfo.cs create mode 100644 src/YammerShell/Properties/Resources.Designer.cs create mode 100644 src/YammerShell/Properties/Resources.resx create mode 100644 src/YammerShell/Request.cs create mode 100644 src/YammerShell/YammerObjects/YammerFile.cs create mode 100644 src/YammerShell/YammerObjects/YammerGroup.cs create mode 100644 src/YammerShell/YammerObjects/YammerMessage.cs create mode 100644 src/YammerShell/YammerObjects/YammerNetwork.cs create mode 100644 src/YammerShell/YammerObjects/YammerRelationship.cs create mode 100644 src/YammerShell/YammerObjects/YammerSearchResult.cs create mode 100644 src/YammerShell/YammerObjects/YammerTopic.cs create mode 100644 src/YammerShell/YammerObjects/YammerUser.cs create mode 100644 src/YammerShell/YammerShell.csproj create mode 100644 src/YammerShell/packages.config diff --git a/README.md b/README.md new file mode 100644 index 0000000..9a24801 --- /dev/null +++ b/README.md @@ -0,0 +1,59 @@ + ###################################################################### + ## __ __ _____ _ _ _ ## + ## \ \ / / / ____| | | | | ## + ## \ \_/ /_ _ _ __ ___ _ __ ___ ___ _ _| (___ | |__ ___| | | ## + ## \ / _` | '_ ` _ \| '_ ` _ \ / _ \ '__\___ \| '_ \ / _ \ | | ## + ## | | (_| | | | | | | | | | | | __/ | ____) | | | | __/ | | ## + ## |_|\__,_|_| |_| |_|_| |_| |_|\___|_| |_____/|_| |_|\___|_|_| ## + ## ## + ###################################################################### + +# YammerShell + +YammerShell is a Windows PowerShell module to access Yammer with PowerShell. It uses Yammer's REST API. + => therefore authentication via OAuth is required. + +The contained CommandLets cover the most important endpoints provided by the API. + + +## Importing the module + +1. Unpack the zip file. +2. Open Windows PowerShell. +3. Navigate to the directory with the unpacked files with `cd `. +4. Type `Import-Module .\YammerShell.dll`. + + +## How to get authenticated + +* Yammer API needs a registered application to access its endpoints. +* An application has a Bearer Token assigned. +* Using this token YammerShell has the same rights the user that created the app has. + +--> The CmdLet `Get-YmToken` helps you to register an application in Yammer. + _(**Warning**: to delete an app you have to contact the support!)_ + +To use the token of a registered app, type `Set-YmToken `. + + +## How to use YammerShell + +After you registered an app and obtained a token, +you can simply start YammerShell using the batch file [_StartYammerShell.bat](doc/_StartYammerShell.bat). + +It contains the following line where you have to change +1234 to your token and to the path where YammerShell.dll is located: + +```Batchfile +start powershell -NoExit -NoLogo -Command "Import-Module '\YammerShell.dll'; Set-YmToken '1234';` +``` + +To get a list of all CmdLets type `Get-YmHelp`. Also all available CmdLets are [documented on github](doc/README.md). + + +## Errors + +If you use YammerShell-CmdLets in a script it may happen that an error occurs while performing many actions in a short period. +This is caused by Yammer's API which has some [limitations of requests](https://developer.yammer.com/docs/rest-api-rate-limits). + +To fix it just add a small delay (e.g. with the CmdLet `Start-Sleep`) in your script to prevent too many requests. \ No newline at end of file diff --git a/doc/AddYmGroupMembership.md b/doc/AddYmGroupMembership.md new file mode 100644 index 0000000..9cb6196 --- /dev/null +++ b/doc/AddYmGroupMembership.md @@ -0,0 +1,45 @@ +# Add-YmGroupMembership + +Adds a user to a group specified by ID or email. If both is omitted the user that is currently authenticated will be added to the group + +## Syntax + +```PowerShell +Add-YmGroupMembership [-GroupId] [-UserId ] +``` + +```PowerShell +Add-YmGroupMembership [-GroupId] [-Email ] +``` + +## Parameters + +Parameter | Type | Required | Description +----------|------|----------|------------ +GroupId | int | true | The ID of the group where to add the user. +UserId | int | false | The ID of the user to add. +Email | String | false | The email of the user to add. If the email does not correspond to an existing user then the user will be invited to join the network (if you are network admin). + + +## Examples + +### Example 1 + +```PowerShell +PS:> Add-YmGroupMembership -GroupId 1234567 +``` +Adds the currently authenticated user to the group with the ID 1234567 + +### Example 2 + +```PowerShell +PS:> Add-YmGroupMembership 1234567 -UserId 1213141516 +``` +Adds the user with the ID 1213141516 to the group with the ID 1234567 + +### Example 3 + +```PowerShell +PS:> Add-YmGroupMembership 1234567 -Email user@company.com +``` +Adds the user with the email _user@company.com_ to the group with the ID 1234567 or sends an invitation if user is not yet registered on yammer. \ No newline at end of file diff --git a/doc/AddYmRelationship.md b/doc/AddYmRelationship.md new file mode 100644 index 0000000..5a15924 --- /dev/null +++ b/doc/AddYmRelationship.md @@ -0,0 +1,34 @@ +# Add-YmRelationship + +Add an org chart relationship for a user. + +## Syntax + +```PowerShell +Add-YmRelationship [-UserId ] [-Subordinates ] [-Superiors ] [-Colleagues ] +``` + +## Parameters + +Parameter | Type | Required | Description +----------|------|----------|------------ +UserId | int | false | The ID of the user to add the relationship to. If not specified the currently authenticated user gets used. +Subordinates | String[] | false | An array of email addresses of yammer users that are subordinates of the user specified by ID +Superiors | String[] | false | An array of email addresses of yammer users that are superiors of the user specified by ID +Colleagues | String[] | false | An array of email addresses of yammer users that are colleagues of the user specified by ID + +## Examples + +### Example 1 + +```PowerShell +PS:> Add-YmRelationship -UserId 1213141516 -Subordinates @('user@company.com') +``` +Create a relationship for the user with the ID 1213141516 where the user with the email _user@company.com_ is a subordinate. + +### Example 2 + +```PowerShell +PS:> Add-YmRelationship -Superiors @('user1@company.com') -Colleagues @('user2@company.com', 'user3@company.com') +``` +Create a relationship for the currently authenticated user where the user _user1@company.com_ is a superior and the users _user2@company.com_ and _user3@company.com_ are colleagues. \ No newline at end of file diff --git a/doc/GetYmGroup.md b/doc/GetYmGroup.md new file mode 100644 index 0000000..763f04d --- /dev/null +++ b/doc/GetYmGroup.md @@ -0,0 +1,38 @@ +# Get-YmGroup + +Returns all groups or a specific group selected by id. + +## Syntax + +```PowerShell +Get-YmGroup [[-Id] ] +``` + +## Returns + +> YammerShell.YammerObjects.YammerGroup +> YammerShell.YammerObjects.YammerGroup[] + + +## Parameters + +Parameter | Type | Required | Description +----------|------|----------|------------ +Id | int | false | The ID of a group to return. + + +## Examples + +### Example 1 + +```PowerShell +PS:> Get-YmGroup +``` +Returns all groups of the yammer network. + +### Example 2 + +```PowerShell +PS:> Get-YmGroup 1234567 +``` +Return the group with the ID 1234567 \ No newline at end of file diff --git a/doc/GetYmHelp.md b/doc/GetYmHelp.md new file mode 100644 index 0000000..b0e7c2e --- /dev/null +++ b/doc/GetYmHelp.md @@ -0,0 +1,27 @@ +# Get-YmHelp + +Shows a list of all Yammer-CmdLets. + +## Syntax + +```PowerShell +Get-YmHelp [-Force] +``` + +## Returns +> String + +## Parameters + +Parameter | Type | Required | Description +----------|------|----------|------------ +Force | SwitchParameter | false | Try to force YammerShell to help you. + +## Examples + +### Example 1 + +```PowerShell +PS:> Get-YmHelp +``` +Return a string with all YammerShell-CmdLet names and a short descripton. \ No newline at end of file diff --git a/doc/GetYmMessage.md b/doc/GetYmMessage.md new file mode 100644 index 0000000..026ff04 --- /dev/null +++ b/doc/GetYmMessage.md @@ -0,0 +1,106 @@ +# Get-YmMessage + +Shows messages of the user's Yammer network. + + +## Syntax + +```PowerShell +Get-YmMessage [-Id] +``` + +```PowerShell +Get-YmMessage -Sent [-Limit ] [-OlderThan ] +``` + +```PowerShell +Get-YmMessage -Received [-Private] [-Limit ] [-OlderThan ] +``` + +```PowerShell +Get-YmMessage -Topic +``` + +```PowerShell +Get-YmMessage -Top -Following +``` + +```PowerShell +Get-YmMessage -Top +``` + +```PowerShell +Get-YmMessage -Following +``` + +## Returns + +> YammerShell.YammerObjects.YammerMessage +> YammerShell.YammerObjects.YammerMessage[] + + +## Parameters + +Parameter | Type | Required | Description +----------|------|----------|------------ +Id | int | false | The ID of a message to get. +Sent | SwitchParameter | false | Only sent messages get returned if set. +Limit | int | false | The Maximum of returned messages. +OlderThan | int | false | The ID of a message. Specify this to return messages older than this message. +Received | SwitchParameter | false | All received messages get returned if set. +Private | SwitchParameter | false | Set this to receive only private messages. +Topic | SwitchParameter | false | The ID of a specific topic. +Top | SwitchParameter | false | Return top messages if set. +Following | SwitchParameter | false | Return messages you follow if set. + + +## Examples + +### Example 1 + +```PowerShell +PS:> Get-YmMessage -Id 806862287 +``` +Return the message with the ID 806862287. + +### Example 2 + +```PowerShell +PS:> Get-YmMessage -Received -Private -Limit 5 +``` +Return the first five received private messages of the authenticated user. + +### Example 3 + +```PowerShell +PS:> Get-YmMessage -Sent -OlderThan 806862287 +``` +Return messages sent by the authenticated user older than the message with the ID 806862287 + +### Example 4 + +```PowerShell +PS:> Get-YmMessage -Topic 18629862 +``` +Return messages for the topic with the ID 18629862. + +### Example 5 + +```PowerShell +PS:> Get-YmMessage -Top -Following +``` +Return the authenticated user’s message feed, based on the selection made between _Following_ and _Top_ conversations. + +### Example 6 + +```PowerShell +PS:> Get-YmMessage -Top +``` +Return the algorithmic feed for the authenticated user that corresponds to _Top_ conversations. The Top conversations feed is the feed currently shown in the Yammer mobile apps. + +### Example 7 + +```PowerShell +PS:> Get-YmMessage -Following +``` +Return the _Following_ feed which is conversations involving people, groups and topics that the authenticated user is following. diff --git a/doc/GetYmNetwork.md b/doc/GetYmNetwork.md new file mode 100644 index 0000000..9d24389 --- /dev/null +++ b/doc/GetYmNetwork.md @@ -0,0 +1,36 @@ +# Get-YmNetwork + +Returns a list of networks to which the current user has access to. + + +## Syntax + +```PowerShell +Get-YmNetwork [[-Id] ] +``` + +## Returns +> YammerShell.YammerObjects.YammerNetwork + +## Parameters + +Parameter | Type | Required | Description +----------|------|----------|------------ +Id | int | false | The ID to filter the networks after. + + +## Examples + +### Example 1 + +```PowerShell +PS:> Get-YmNetwork +``` +Returns all networks to which the currently authenticated user has access to. + +### Example 2 + +```PowerShell +PS:> Get-YmNetwork 495653 +``` +Return the network with the ID 495653 if the authenticated user as access to it. \ No newline at end of file diff --git a/doc/GetYmToken.md b/doc/GetYmToken.md new file mode 100644 index 0000000..21a4e6c --- /dev/null +++ b/doc/GetYmToken.md @@ -0,0 +1,24 @@ +# Get-YmToken + +Navigates you through the pages which are needed to **create a new application** and to get the bearer token. +Then it sets the received token. If you already registered an app you can set its token via [Set-YmToken](SetYmToken.md). + +## Syntax + +```PowerShell +Get-YmToken +``` + +## Examples + +### Example 1 + +```PowerShell +PS:> Get-YmToken +``` + +This first opens the page to register an app in yammer. +Then it lets you paste the _client id_ and the _client secret_. +Next you get redirected and have to paste the _secret_ you will receive there. +Now the bearer token gets automatically requested and set for this session. +It is recommended to _save this token_ for next PowerShell sessions where you can set it with [Set-YmToken](SetYmToken.md). \ No newline at end of file diff --git a/doc/GetYmUser.md b/doc/GetYmUser.md new file mode 100644 index 0000000..179d854 --- /dev/null +++ b/doc/GetYmUser.md @@ -0,0 +1,58 @@ +# Get-YmUser + +Returns all users in the user's Yammer network or a specific user. + +## Syntax + +```PowerShell +Get-YmUser [-Id] +``` + +```PowerShell +Get-YmUser -Current +``` + +```PowerShell +Get-YmUser -GroupId [-Limit ] [-Reverse] +``` + +```PowerShell +Get-YmUser -Email [-Limit ] [-Reverse] +``` + +```PowerShell +Get-YmUser -StartLetter [-Limit ] [-Reverse] +``` + +## Returns +> YammerShell.YammerObjects.YammerUser + + +## Parameters + +Parameter | Type | Required | Description +----------|------|----------|------------ +Id | int | true | The ID of a user to return +Current | SwitchParameter | true | Returns the currently authenticated user if set +Limit | int | false | The Maximum of returned users. Accepts values between 1 and 1000. +Reverse | SwitchParameter | false | Returns the users in reverse alphabetical order +Email | String | true | The email of one or more profiles to return +StartLetter | Char | true | The start letter of users to return + + + +## Examples + +### Example 1 + +```PowerShell +PS:> Get-YmUser -GroupId 1234567 -Limit 7 +``` +Returns the first seven users of the group with the ID 1234567 + +### Example 2 + +```PowerShell +PS:> Get-YmUser -Email 'user@company.com' -Reverse +``` +Returns all user profiles with the email _user@company.com_ in reverse alphabetical order \ No newline at end of file diff --git a/doc/NewYmGroup.md b/doc/NewYmGroup.md new file mode 100644 index 0000000..9f098f4 --- /dev/null +++ b/doc/NewYmGroup.md @@ -0,0 +1,38 @@ +# New-YmGroup + +Creates a new group in yammer. Returns the ID of the new group. + +## Syntax + +```PowerShell +New-YmGroup [-Name] [-Description ] [-Private] +``` + +## Returns +> System.Int32 + + +## Parameters + +Parameter | Type | Required | Description +----------|------|----------|------------ +Name | String | true | The name of the new group +Description | String | false | The description of the new group. +Private | SwitchParameter | false | Whether the new group should be private. + + +## Examples + +### Example 1 + +```PowerShell +PS:> $groupId = New-YmGroup 'Business Administration' -Description 'This is a group for the team Business Administration!' +``` +Creates a new group with the name _Business Administration_ and a description. The ID gets saved in $groupId. + +### Example 2 + +```PowerShell +PS:> New-YmGroup 'YammerShell Test Group' -Private +``` +Creates a new _private_ group with the name _YammerShell Test Group_. \ No newline at end of file diff --git a/doc/NewYmMessage.md b/doc/NewYmMessage.md new file mode 100644 index 0000000..b77ab00 --- /dev/null +++ b/doc/NewYmMessage.md @@ -0,0 +1,48 @@ +# New-YmMessage + +Posts a new message or announcement to the network or a group. Returns the id of that message. + +## Syntax + +```PowerShell +New-YmMessage [-Body] [-GroupId ] [-AnnouncementTitle ] +``` + +```PowerShell +New-YmMessage [-Body] -RepliedToId +``` + +```PowerShell +New-YmMessage [-Body] -DirectToUserIds +``` + +## Returns +> System.Int32 + + +## Parameters + +Parameter | Type | Required | Description +----------|------|----------|------------ +Body | String | true | The text body of the message. +GroupId | int | false | The ID of a group where the message gets posted. +AnnouncementTitle | String | false | The title of the announcement. If this parameter is set the message will be of type announcement. +RepliedToId | int | false | The ID of an other message to which the new message is a reply. +DirectToUserIds | int[] | false | IDs of users to send the message to. If this parameter is set the message will be private. + + +## Examples + +### Example 1 + +```PowerShell +PS:> New-YmMessage 'Hello World!' -GroupId 1234567 +``` +Creates a new message in the group with the ID 1234567. Returns the ID of this message. + +### Example 2 + +```PowerShell +PS:> New-YmMessage 'This is a private message!' -DirectToUserIds @(1234567890, 2345678901) +``` +Sends a new private message to the users with the IDs 1234567890 and 2345678901. \ No newline at end of file diff --git a/doc/NewYmUser.md b/doc/NewYmUser.md new file mode 100644 index 0000000..fc9b288 --- /dev/null +++ b/doc/NewYmUser.md @@ -0,0 +1,34 @@ +# New-YmUser + +Creates a new user. Current user should be a verified admin to perform this action. Returns the ID of the new user. + + +## Syntax + +```PowerShell +New-YmUser [-Email] [-FullName ] [-JobTitle ] [-DepartmentName ] [-Location ] [-WorkTelephone ] +``` + +## Returns +> System.Int32 + +## Parameters + +Parameter | Type | Required | Description +----------|------|----------|------------ +Email | String | true | The email address of the new user. +FullName | String | false | Pre- and surname of the new user separated by a space. +JobTitle | String | false | The job title of the new user. +DepartmentName | String | false | The name of the department of the new user. +Location | String | false | The location where the new user works at. +WorkTelephone | String | false | The work phone number of the new user. Must contain only numbers. + + +## Examples + +### Example 1 + +```PowerShell +PS:> New-YmUser 'user@company.com' -FullName 'Test User' -DepartmentName 'Sales' +``` +Creates a new user with the email _user@company.com_, the name _Test User_ and the department _Sales_. Returns the ID of the new user. \ No newline at end of file diff --git a/doc/README.md b/doc/README.md new file mode 100644 index 0000000..0a445f6 --- /dev/null +++ b/doc/README.md @@ -0,0 +1,22 @@ +# CmdLet Documentation + +CmdLet | Description +-------|------------ +[Add-YmGroupMembership](AddYmGroupMembership.md) | Adds a user to a group. +[Add-YmRelationship](AddYmRelationship.md) | Add an org chart relationship for a user. +[Get-YmGroup](GetYmGroup.md) | Returns all groups or a specific group selected by id. +[Get-YmHelp](GetYmHelp.md) | Shows a list of all Yammer-CmdLets. +[Get-YmMessage](GetYmMessage.md) | Shows messages of the user's Yammer network. +[Get-YmNetwork](GetYmNetwork.md) | Returns a list of networks to which the current user has access to. +[Get-YmToken](GetYmToken.md) | Navigates you through the pages which are needed to get the bearer token. +[Get-YmUser](GetYmUser.md) | Returns all users in the user's Yammer network or a specific user selected by username or id. +[New-YmGroup](NewYmGroup.md) | Creates a new group in yammer. +[New-YmMessage](NewYmMessage.md) | Posts a new message or announcement to the network or a group. +[New-YmUser](NewYmUser.md) | Creates a new user. Current user should be a verified admin to perform this action. +[Remove-Ym-GroupMembership](RemoveYmGroupMembership.md) | Remove a user from a group. +[Remove-YmMessage](RemoveYmMessage.md) | Deletes a message per id. +[Search-YmItem](SearchYmItem.md) | Search messages, users, topics and groups. +[Send-YmInvitation](SendYmInvitation.md) | Send someone an invitation to the yammer network. +[Set-YmToken](SetYmToken.md) | Sets the bearer token needed to access Yammer. +[Show-YmRelationships](ShowYmRelationships.md) | Show org chart relationships. +[Show-YmToken](ShowYmToken.md) | Shows the currently set token. \ No newline at end of file diff --git a/doc/RemoveYmGroupMembership.md b/doc/RemoveYmGroupMembership.md new file mode 100644 index 0000000..208b527 --- /dev/null +++ b/doc/RemoveYmGroupMembership.md @@ -0,0 +1,35 @@ +# Remove-YmGroupMembership + + +## Syntax + +```PowerShell +Remove-YmGroupMembership [-GroupId] [-UserId ] +``` + +## Returns +> System.Int32 + +## Parameters + +Parameter | Type | Required | Description +----------|------|----------|------------ +GroupId | int | true | The ID of the group where a user gets removed from +UserId | int | false | The ID of the user to leave the group + + +## Examples + +### Example 1 + +```PowerShell +PS:> Remove-YmGroupMembership -GroupId 1234567 +``` +Removes the currently authenticated user from the group with the ID 1234567. + +### Example 2 + +```PowerShell +PS:> Remove-YmGroupMembership 1234567 -UserId 2345678901 +``` +Removes the user with the ID 2345678901 from the group with the ID 1234567. \ No newline at end of file diff --git a/doc/RemoveYmMessage.md b/doc/RemoveYmMessage.md new file mode 100644 index 0000000..7f89ba2 --- /dev/null +++ b/doc/RemoveYmMessage.md @@ -0,0 +1,25 @@ +# Remove-YmMessage + +Deletes a message per ID. + +## Syntax + +```PowerShell +Remove-YmMessage [-Id] +``` + +## Parameters + +Parameter | Type | Required | Description +----------|------|----------|------------ +Id | int | true | The ID of the message to remove. + + +## Examples + +### Example 1 + +```PowerShell +PS:> Remove-YmMessage 123456789 +``` +Removes the message with the ID 123456789. \ No newline at end of file diff --git a/doc/SearchYmItem.md b/doc/SearchYmItem.md new file mode 100644 index 0000000..0dfe2d8 --- /dev/null +++ b/doc/SearchYmItem.md @@ -0,0 +1,37 @@ +# Search-YmItem + +Search messages, users, topics and groups. + +## Syntax + +```PowerShell +Search-YmItem [-SearchItem] [-Page ] [-Limit ] +``` + +## Returns +> YammerShell.YammerObjects.YammerSearchResult + +## Parameters + +Parameter | Type | Required | Description +----------|------|----------|------------ +SearchItem | String | true | The string to search items with. +Page | int | false | The number of the result page. Default is 1. +Limit | int | false | The maximum of result items for each result page. Between 1 and 20. Default is 20. + + +## Examples + +### Example 1 + +```PowerShell +PS:> Search-YmItem 'welcome' +``` +Searches messages, users, topics and groups for the word _welcome_. Returns an object containing message, user, topic, files and group items. + +### Example 2 + +```PowerShell +PS:> Search-YmItem 'welcome' -Page 1 -Limit 3 +``` +Searches yammer for the word _welcome_. Returns the first three results from result page one. \ No newline at end of file diff --git a/doc/SendYmInvitation.md b/doc/SendYmInvitation.md new file mode 100644 index 0000000..1f8881a --- /dev/null +++ b/doc/SendYmInvitation.md @@ -0,0 +1,25 @@ +# Send-YmInvitation + +Send an invitation to the yammer network to the specified emails. + +## Syntax + +```PowerShell +Send-YmInvitation [-Emails] +``` + +## Parameters + +Parameter | Type | Required | Description +----------|------|----------|------------ +Emails | String[] | true | The email addresses to send an invitation to. + + +## Examples + +### Example 1 + +```PowerShell +PS:> Send-YmInvitation @('user1@example.com', 'user2@example.com') +``` +Sends invitations to the emails _user1@example.com_ and _user2@example.com_. \ No newline at end of file diff --git a/doc/SetYmToken.md b/doc/SetYmToken.md new file mode 100644 index 0000000..3ebfdb0 --- /dev/null +++ b/doc/SetYmToken.md @@ -0,0 +1,22 @@ +# Set-YmToken + +## Syntax + +```PowerShell +Set-YmToken [-Token] +``` + +## Parameters + +Parameter | Type | Required | Description +----------|------|----------|------------ +Token | int | true | The Bearer Token that is needed to authorize. + +## Examples + +### Example 1 + +```PowerShell +PS:> Set-YmToken abc123-dfg456789 +``` +Set the token that YammerShell uses to abc123-dfg456789. \ No newline at end of file diff --git a/doc/ShowYmRelationships.md b/doc/ShowYmRelationships.md new file mode 100644 index 0000000..5aab534 --- /dev/null +++ b/doc/ShowYmRelationships.md @@ -0,0 +1,33 @@ +# Show-YmRelationships + +## Syntax + +```PowerShell +Show-YmRelationships [[-UserId] ] +``` + +## Returns +> YammerShell.YammerObjects.YammerRelationship + +## Parameters + +Parameter | Type | Required | Description +----------|------|----------|------------ +UserId | int | false | The ID of a user to show to relationships of + + +## Examples + +### Example 1 + +```PowerShell +PS:> Show-YmRelationships +``` +Return the relationships for the current authenticated user. + +### Example 2 + +```PowerShell +PS:> Show-YmRelationships -UserId 1213141516 +``` +Return the relationships for the user with the ID 1213141516. \ No newline at end of file diff --git a/doc/ShowYmToken.md b/doc/ShowYmToken.md new file mode 100644 index 0000000..dd9d5b1 --- /dev/null +++ b/doc/ShowYmToken.md @@ -0,0 +1,12 @@ +# Show-YmToken + +Returns the currently set token. + +## Syntax + +```PowerShell +Show-YmToken +``` + +## Returns +> String \ No newline at end of file diff --git a/scripts/CreateGroupsAndUsers.ps1 b/scripts/CreateGroupsAndUsers.ps1 new file mode 100644 index 0000000..44d3c80 --- /dev/null +++ b/scripts/CreateGroupsAndUsers.ps1 @@ -0,0 +1,52 @@ +Import-Module '.\YammerShell.dll' + +Set-YmToken abc123-def456ghi789 + +[xml]$employees = +' + + foxmulder@company.com + Fox Mulder + Marketing + + + + frankblack@company.com + Frank Black + Sales + + + + johndoe@company.com + John Doe + Development + +' + +$departments = @('Sales', 'Development', 'Marketing', 'Human Resources') +$groupIds = New-Object int[] $departments.Count + +for($i=0; $i -lt $departments.Count; $i++){ + $groupIds[$i] = New-YmGroup -Name $departments[$i] -Description 'Group of the department: ' + $departments[$i] # create a group for each department +} + +for($i=0; $i -lt $employees.FirstChild.User.Count; $i++){ + $newUser = $employees.FirstChild.User[$i] # get employee from xml + $userID = New-YmUser -Email $newUser.Email -FullName $newUser.FullName -DepartmentName $newUser.Department # create user for each employee + + $index = $departments.IndexOf($newUser.Department) # get id of department group + Add-YmGroupMembership -GroupId $groupIds[$index] -UserId $userID # add user to group +} + +New-YmMessage 'Welcome to Yammer! New groups for each department have been created and members have been added!' + +$groups = Get-YmGroup + +for($i=0; $i -lt $groups.Count; $i++){ + $group = $groups[$i] + + Write-Host "All users for group:" + $group.Name + Get-YmUser -GroupId $group.Id # list all users of a group +} + +Get-YmMessage # list all messages to see if new message was posted \ No newline at end of file diff --git a/scripts/CreateUserAndGroup.ps1 b/scripts/CreateUserAndGroup.ps1 new file mode 100644 index 0000000..b8efa13 --- /dev/null +++ b/scripts/CreateUserAndGroup.ps1 @@ -0,0 +1,26 @@ +Import-Module '.\YammerShell.dll' + +Set-YmToken abc123-def456ghi789 + +# crete a new group +$groupId = New-YmGroup 'Marketing' -Description 'Group of the department Marketing' + +# create a new user +$userId = New-YmUser -Email 'user@company.com' -FullName 'Max Power' -DepartmentName 'Marketing' + +# add user to group +Add-YmGroupMembership -GroupId $groupId -UserId $userId + +# post a new message +New-YmMessage 'Welcome to Yammer!' + +Get-YmGroup | ForEach-Object { + # list all groups + Write-Host 'All users for group:' + $_.Name + + # list all users of a group + Get-YmUser -GroupId $_.Id +} + +# list all messages +Get-YmMessage \ No newline at end of file diff --git a/scripts/_StartYammerShell.bat b/scripts/_StartYammerShell.bat new file mode 100644 index 0000000..ad80457 --- /dev/null +++ b/scripts/_StartYammerShell.bat @@ -0,0 +1 @@ +start powershell -NoExit -NoLogo -Command "Import-Module '.\YammerShell.dll'; Set-YmToken '1234'; \ No newline at end of file diff --git a/src/YammerShell.sln b/src/YammerShell.sln new file mode 100644 index 0000000..85553a9 --- /dev/null +++ b/src/YammerShell.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.25420.1 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "YammerShell", "YammerShell\YammerShell.csproj", "{37EF96FC-171A-4DA2-90B3-EAF32CAEA259}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {37EF96FC-171A-4DA2-90B3-EAF32CAEA259}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {37EF96FC-171A-4DA2-90B3-EAF32CAEA259}.Debug|Any CPU.Build.0 = Debug|Any CPU + {37EF96FC-171A-4DA2-90B3-EAF32CAEA259}.Release|Any CPU.ActiveCfg = Release|Any CPU + {37EF96FC-171A-4DA2-90B3-EAF32CAEA259}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/src/YammerShell/CmdLets/AddYmGroupMembership.cs b/src/YammerShell/CmdLets/AddYmGroupMembership.cs new file mode 100644 index 0000000..d2779e3 --- /dev/null +++ b/src/YammerShell/CmdLets/AddYmGroupMembership.cs @@ -0,0 +1,71 @@ +using System; +using System.Management.Automation; + +namespace YammerShell.CmdLets +{ + [Cmdlet(VerbsCommon.Add, "YmGroupMembership", DefaultParameterSetName = "UserId")] + public class AddYmGroupMembership : PSCmdlet + { + private Request _request; + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + Mandatory = true, + Position = 0, + HelpMessage = "ID of a yammer group" + )] + public int? GroupId { get; set; } + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + HelpMessage = "ID of a user to join the group", + ParameterSetName = "UserId" + )] + public int? UserId { get; set; } + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + HelpMessage = "Email of a user to join the group. If the email does not correspond to an existing user then the user will be invited to join the network too (if you are network admin).", + ParameterSetName = "Email" + )] + public string Email { get; set; } + + protected override void ProcessRecord() + { + var token = SessionState.PSVariable.Get(Properties.Resources.TokenVariable); + if (token == null) + { + WriteWarning(Properties.Resources.EmptyTokenWarning); + return; + } + _request = new Request(token.Value.ToString()); + + string email = string.Empty; + string userId = string.Empty; + + if (Email != null) + { + email = "&email=" + Email; + } + if (UserId != null) + { + userId = "&user_id=" + UserId; + } + + try + { + var url = string.Format("{0}group_memberships.json?group_id={1}{2}{3}", Properties.Resources.YammerApi, GroupId, userId, email); + _request.Post(url, string.Empty); + } + catch (Exception e) + { + var errorRecord = new ErrorRecord(e, "e", ErrorCategory.InvalidArgument, "Arguments invalid"); + WriteError(errorRecord); + } + } + + } +} diff --git a/src/YammerShell/CmdLets/AddYmRelationship.cs b/src/YammerShell/CmdLets/AddYmRelationship.cs new file mode 100644 index 0000000..057281a --- /dev/null +++ b/src/YammerShell/CmdLets/AddYmRelationship.cs @@ -0,0 +1,111 @@ +using System; +using System.Management.Automation; +using System.Text; + +namespace YammerShell.CmdLets +{ + [Cmdlet(VerbsCommon.Add, "YmRelationship")] + public class AddYmRelationship : PSCmdlet + { + private Request _request; + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + Position = 0, + HelpMessage = "ID of a user" + )] + public int? UserId { get; set; } + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + HelpMessage = "Emails of users that are subordinates" + )] + public string[] Subordinates { get; set; } + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + HelpMessage = "Emails of users that are superior" + )] + public string[] Superiors { get; set; } + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + HelpMessage = "Emails of users that are colleagues" + )] + public string[] Colleagues { get; set; } + + protected override void ProcessRecord() + { + var token = SessionState.PSVariable.Get(Properties.Resources.TokenVariable); + if (token == null) + { + WriteWarning(Properties.Resources.EmptyTokenWarning); + return; + } + _request = new Request(token.Value.ToString()); + + try + { + if (Subordinates == null && Superiors == null && Colleagues == null) + { + var errorRecord = new ErrorRecord(new ArgumentNullException(), "Missing parameters", ErrorCategory.InvalidArgument, Subordinates); + WriteError(errorRecord); + return; + } + + var url = string.Format("{0}relationships.json", Properties.Resources.YammerApi); + var postData = new StringBuilder(); + + if (UserId.HasValue) + { + postData.Append("user_id=" + UserId); + postData.Append("&"); + } + if (Subordinates != null && Subordinates.Length > 0) + { + postData.Append("subordinate=" + Subordinates[0]); + for (int i = 1; i < Subordinates.Length; i++) + { + postData.Append("&subordinate=" + Subordinates[i]); + } + if (Superiors.Length > 0 || Colleagues.Length > 0) + { + postData.Append("&"); + } + } + if (Superiors != null && Superiors.Length > 0) + { + postData.Append("superior=" + Superiors[0]); + for (int i = 1; i < Superiors.Length; i++) + { + postData.Append("&superior=" + Superiors[i]); + } + if (Colleagues.Length > 0) + { + postData.Append("&"); + } + } + if (Colleagues != null && Colleagues.Length > 0) + { + postData.Append("colleagues=" + Colleagues[0]); + for (int i = 1; i < Colleagues.Length; i++) + { + postData.Append("&colleagues=" + Colleagues[i]); + } + } + + _request.Post(url, postData.ToString()); // TODO test as admin + } + catch (Exception e) + { + var errorRecord = new ErrorRecord(e, "94", ErrorCategory.InvalidArgument, UserId); + WriteError(errorRecord); + } + } + + } +} diff --git a/src/YammerShell/CmdLets/GetYmGroup.cs b/src/YammerShell/CmdLets/GetYmGroup.cs new file mode 100644 index 0000000..dfff08f --- /dev/null +++ b/src/YammerShell/CmdLets/GetYmGroup.cs @@ -0,0 +1,81 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Management.Automation; +using YammerShell.YammerObjects; + +namespace YammerShell.CmdLets +{ + [Cmdlet(VerbsCommon.Get, "YmGroup")] + public class GetYmGroup : PSCmdlet + { + private Request _request; + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + Position = 0, + HelpMessage = "ID of a yammer group" + )] + public int? Id { get; set; } + + protected override void ProcessRecord() + { + var token = SessionState.PSVariable.Get(Properties.Resources.TokenVariable); + if (token == null) + { + WriteWarning(Properties.Resources.EmptyTokenWarning); + return; + } + _request = new Request(token.Value.ToString()); + + if (Id != null) + { + try + { + var group = JToken.Parse(_request.Get(Properties.Resources.YammerApi + "groups/" + Id + ".json")); + WriteObject(GetYammerGroupFromJToken(group)); + } + catch (Exception e) + { + var errorRecord = new ErrorRecord(e, "id", ErrorCategory.InvalidArgument, Id); + WriteError(errorRecord); + } + return; + } + try + { + var groups = JArray.Parse(_request.Get(Properties.Resources.YammerApi + "groups.json")); + var allYammerGroups = new List(); + foreach (var group in groups) + { + var yammerGroup = GetYammerGroupFromJToken(group); + allYammerGroups.Add(yammerGroup); + } + WriteObject(allYammerGroups, true); + } + catch (Exception e) + { + var errorRecord = new ErrorRecord(e, "parse", ErrorCategory.InvalidArgument, ""); + WriteError(errorRecord); + } + } + + private YammerGroup GetYammerGroupFromJToken(JToken group) + { + var yammerGroup = new YammerGroup(); + yammerGroup.Id = Convert.ToInt32(group["id"]); + yammerGroup.Email = (group["email"] ?? string.Empty).ToString(); + yammerGroup.FullName = group["full_name"].ToString(); + yammerGroup.Name = group["name"].ToString(); + yammerGroup.NetworkId = Convert.ToInt32(group["network_id"]); + yammerGroup.Description = (group["description"] ?? string.Empty).ToString(); + yammerGroup.Privacy = group["privacy"].ToString(); + yammerGroup.Url = (group["web_url"] ?? string.Empty).ToString(); + yammerGroup.CreatedAt = (DateTime)(group["created_at"] ?? DateTime.MinValue); + yammerGroup.CreatorId = Convert.ToInt32(group["creator_id"] ?? -1); + yammerGroup.Members = Convert.ToInt32(group["stats"]["members"]); + return yammerGroup; + } + } +} diff --git a/src/YammerShell/CmdLets/GetYmHelp.cs b/src/YammerShell/CmdLets/GetYmHelp.cs new file mode 100644 index 0000000..5dd9c62 --- /dev/null +++ b/src/YammerShell/CmdLets/GetYmHelp.cs @@ -0,0 +1,40 @@ +using System.Management.Automation; + +namespace YammerShell.CmdLets +{ + [Cmdlet(VerbsCommon.Get, "YmHelp")] + public class GetYmHelp : PSCmdlet + { + [Parameter( + HelpMessage = "You should better be polite..." + )] + public SwitchParameter Force { get; set; } + + protected override void ProcessRecord() + { + if (Force.IsPresent) + { + WriteObject("\nYou can not force YammerShell to help you.\n"); + return; + } + + var helpMessage = "\n" + + "-Add-YmGroupMembership: add a user to a group \n" + + "-Get-YmGroup: returns all groups or a specific group selected by id \n" + + "-Get-YmMessage: shows messages of the user's Yammer network \n" + + "-Get-YmNetwork: returns a list of networks to which the current user has access \n" + + "-Get-YmToken: navigates you through the pages which are needed to get the bearer token \n" + + "-Get-YmUser: returns all users in the user's Yammer network or a specific user selected by username \n" + + "-New-YmGroup: creates a new group in yammer \n" + + "-New-YmMessage: posts a new message or announcement to the network or a group \n" + + "-New-YmUser: Creates a new user. Current user should be a verified admin to perform this action \n" + + "-Remove-Ym-GroupMembership: remove a user from a group \n" + + "-Remove-YmMessage: deletes a message per id \n" + + "-Search-YmItem: search messages, users, topics and groups \n" + + "-Send-YmInvitation: send an invitation to the yammer network \n" + + "-Set-YmToken: sets the bearer token needed to access Yammer \n" + + "-Show-YmToken: shows the currently set token \n"; + WriteObject(helpMessage); + } + } +} diff --git a/src/YammerShell/CmdLets/GetYmMessage.cs b/src/YammerShell/CmdLets/GetYmMessage.cs new file mode 100644 index 0000000..368bf1b --- /dev/null +++ b/src/YammerShell/CmdLets/GetYmMessage.cs @@ -0,0 +1,233 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Management.Automation; +using YammerShell.YammerObjects; + +namespace YammerShell.CmdLets +{ + [Cmdlet(VerbsCommon.Get, "YmMessage", DefaultParameterSetName = "Id")] + public class GetYmMessage : PSCmdlet + { + private Request _request; + + [Parameter( + HelpMessage = "Return top messages", + ParameterSetName = "Network" + )] + public SwitchParameter Top { get; set; } + + [Parameter( + HelpMessage = "Return messages of followed users", + ParameterSetName = "Network" + )] + public SwitchParameter Following { get; set; } + + [Parameter( + HelpMessage = "Return all messages received by the user", + ParameterSetName = "ReceivedPrivate" + )] + public SwitchParameter Received { get; set; } + + [Parameter( + HelpMessage = "Return all private messages received by the user", + ParameterSetName = "ReceivedPrivate" + )] + public SwitchParameter Private { get; set; } + + [Parameter( + HelpMessage = "Return all private messages sent by the user", + ParameterSetName = "Sent" + )] + public SwitchParameter Sent { get; set; } + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + Position = 0, + HelpMessage = "Id of a message", + ParameterSetName = "Id" + )] + public int? Id { get; set; } + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + HelpMessage = "Limit of messages" + )] + public int? Limit { get; set; } + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + HelpMessage = "Returns messages older than this message ID" + )] + public int? OlderThan { get; set; } + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + HelpMessage = "The feed of messages for a hashtag specified by the numeric string ID", + ParameterSetName = "Topic" + )] + public int? Topic { get; set; } + + protected override void ProcessRecord() + { + var token = SessionState.PSVariable.Get(Properties.Resources.TokenVariable); + if (token == null) + { + WriteWarning(Properties.Resources.EmptyTokenWarning); + return; + } + _request = new Request(token.Value.ToString()); + + if (Id.HasValue) + { + try + { + var url = string.Format("{0}messages/{1}.json", Properties.Resources.YammerApi, Id); + var response = JToken.Parse(_request.Get(url)); + WriteObject(GetYammerMessage(response)); + } + catch (Exception e) + { + var errorRecord = new ErrorRecord(e, "id", ErrorCategory.InvalidArgument, Id); + WriteError(errorRecord); + } + return; + } + if (Sent.IsPresent || Received.IsPresent || Private.IsPresent) + { + WriteObject(GetMessages(), true); + } + else + { + WriteObject(GetNetworkMessages(), true); + } + } + + private IEnumerable GetMessages() + { + string requestUrl; + string parameters = string.Empty; + + if (Limit != null) + { + parameters = "?limit=" + Limit; + if (OlderThan != null) + { + parameters += "&older_than=" + OlderThan; + } + } + else + { + if (OlderThan != null) + { + parameters = "?older_than=" + OlderThan; + } + } + if (Private.IsPresent) + { + requestUrl = Properties.Resources.YammerApi + "messages/private.json"; + return GetMessagesFromApi(requestUrl, parameters); + } + if (Received.IsPresent) + { + requestUrl = Properties.Resources.YammerApi + "messages/received.json"; + return GetMessagesFromApi(requestUrl, parameters); + } + requestUrl = Properties.Resources.YammerApi + "messages/sent.json"; + return GetMessagesFromApi(requestUrl, parameters); + } + + public IEnumerable GetNetworkMessages() + { + string requestUrl; + string parameters = string.Empty; + + if (Limit != null) + { + parameters = "?limit=" + Limit; + if (OlderThan != null) + { + parameters += "&older_than=" + OlderThan; + } + } + else + { + if (OlderThan != null) + { + parameters = "?older_than=" + OlderThan; + } + } + + if (Topic.HasValue) + { + requestUrl = Properties.Resources.YammerApi + "messages/about_topic/" + Topic + ".json"; + return GetMessagesFromApi(requestUrl, parameters); + } + if (Top.IsPresent && Following.IsPresent) + { + requestUrl = Properties.Resources.YammerApi + "messages/my_feed.json"; + return GetMessagesFromApi(requestUrl, parameters); + } + if (Top.IsPresent) + { + requestUrl = Properties.Resources.YammerApi + "messages/algo.json"; + return GetMessagesFromApi(requestUrl, parameters); + } + if (Following.IsPresent) + { + requestUrl = Properties.Resources.YammerApi + "messages/following.json"; + return GetMessagesFromApi(requestUrl, parameters); + } + requestUrl = Properties.Resources.YammerApi + "messages.json"; + return GetMessagesFromApi(requestUrl, parameters); + } + + private IEnumerable GetMessagesFromApi(string requestUrl, string parameters) + { + var allMessages = new List(); + try + { + var result = JObject.Parse(_request.Get(requestUrl + parameters)); + var messages = JArray.Parse(result["messages"].ToString()); + + foreach (var message in messages) + { + allMessages.Add(GetYammerMessage(message)); + } + } + catch (Exception e) + { + var errorRecord = new ErrorRecord(e, "403", ErrorCategory.InvalidArgument, "Arguments invalid"); + WriteError(errorRecord); + } + return allMessages; + } + + private YammerMessage GetYammerMessage(JToken message) + { + var yammerMessage = new YammerMessage(); + yammerMessage.Id = Convert.ToInt32(message["id"]); + yammerMessage.SenderId = Convert.ToInt32(message["sender_id"]); + yammerMessage.RepliedToId = message.Value("replied_to_id"); + yammerMessage.CreatedAt = (DateTime)message["created_at"]; + yammerMessage.NetworkId = Convert.ToInt32(message["network_id"]); + yammerMessage.MessageType = message["message_type"].ToString(); + yammerMessage.GroupId = message.Value("group_id"); + yammerMessage.Body = message["body"]["plain"].ToString(); + yammerMessage.Url = message["web_url"].ToString(); + + var attachments = new List(); + foreach (var attachment in JArray.Parse(message["attachments"].ToString())) + { + attachments.Add(attachment["web_url"].ToString()); + } + yammerMessage.AttachmentUrls = attachments; + + return yammerMessage; + } + } +} diff --git a/src/YammerShell/CmdLets/GetYmNetwork.cs b/src/YammerShell/CmdLets/GetYmNetwork.cs new file mode 100644 index 0000000..5dccbde --- /dev/null +++ b/src/YammerShell/CmdLets/GetYmNetwork.cs @@ -0,0 +1,72 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Management.Automation; +using YammerShell.YammerObjects; + +namespace YammerShell.CmdLets +{ + [Cmdlet(VerbsCommon.Get, "YmNetwork")] + public class GetYmNetwork : PSCmdlet + { + private Request _request; + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + Position = 0, + HelpMessage = "With this parameter set you request all networks the user has access to but filtered by id." + )] + public int? Id { get; set; } + + protected override void ProcessRecord() + { + var token = SessionState.PSVariable.Get(Properties.Resources.TokenVariable); + if (token == null) + { + WriteWarning(Properties.Resources.EmptyTokenWarning); + return; + } + _request = new Request(token.Value.ToString()); + + try + { + var result = _request.Get(Properties.Resources.YammerApi + "networks/current.json?include_suspended=true"); + + var yammerNetworks = new List(); + foreach (var network in JArray.Parse(result)) + { + var networkId = Convert.ToInt32(network["id"]); + if (!Id.HasValue || Id == networkId) + { + yammerNetworks.Add(GetYammerNetwork(network, networkId)); + } + } + WriteObject(yammerNetworks); + } + catch (Exception e) + { + var errorRecord = new ErrorRecord(e, "42", ErrorCategory.InvalidArgument, ""); + WriteError(errorRecord); + } + } + + private YammerNetwork GetYammerNetwork(JToken network, int id) + { + var yammerNetwork = new YammerNetwork(); + yammerNetwork.Id = id; + yammerNetwork.Email = network["email"].ToString(); + yammerNetwork.Name = network["name"].ToString(); + yammerNetwork.Url = network["web_url"].ToString(); + yammerNetwork.Paid = (bool)network["paid"]; + yammerNetwork.IsOrgChartEnabled = (bool)network["is_org_chart_enabled"]; + yammerNetwork.IsGroupEnabled = (bool)network["is_group_enabled"]; + yammerNetwork.IsChatEnabled = (bool)network["is_chat_enabled"]; + yammerNetwork.IsTranslationEnabled = (bool)network["is_translation_enabled"]; + yammerNetwork.CreatedAt = (DateTime)network["created_at"]; + yammerNetwork.AllowSamlAuthentication = (bool)network["allow_saml_authentication"]; + yammerNetwork.EnforceOfficeAuthentication = (bool)network["enforce_office_authentication"]; + return yammerNetwork; + } + } +} diff --git a/src/YammerShell/CmdLets/GetYmToken.cs b/src/YammerShell/CmdLets/GetYmToken.cs new file mode 100644 index 0000000..887173d --- /dev/null +++ b/src/YammerShell/CmdLets/GetYmToken.cs @@ -0,0 +1,52 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Management.Automation; + +namespace YammerShell +{ + [Cmdlet(VerbsCommon.Get, "YmToken")] + public class GetYmToken : PSCmdlet + { + protected override void ProcessRecord() + { + WriteObject("First you have to register an application. Press any key to open 'https://www.yammer.com/client_applications' \n"); + Console.ReadKey(true); + System.Diagnostics.Process.Start("https://www.yammer.com/client_applications"); + + WriteObject("Click on 'Register new app' and fill the blanks. You have to set the redirect uri to 'http://www.google.de'. " + + "After your app has been registered you need to copy the CLIENT ID and paste it here: "); + var clientId = Console.ReadLine().Trim(); + + WriteObject("Now copy the CLIENT SECRET and paste it: "); + var clientSecret = Console.ReadLine().Trim(); + + var url = "https://www.yammer.com/oauth2/authorize?client_id=" + clientId + "&response_type=code&redirect_uri=https://www.google.de"; + WriteObject("\nTo receive an authorization code press any key to open '" + url + "'"); + Console.ReadKey(true); + System.Diagnostics.Process.Start(url); + + WriteObject("\nYou get redirected and have to click on 'Allow'. This redirects you to 'https://www.google.de/?code=[secret]' where [secret] is the code you need to copy and paste here: "); + var code = Console.ReadLine().Trim(); + + var tokenUrl = string.Format("https://www.yammer.com/oauth2/access_token?client_id={0}&client_secret={1}&code={2}", clientId, clientSecret, code); + var request = new Request(""); + try + { + var accessToken = JObject.Parse(request.Post(tokenUrl, string.Empty)); + + var bearer = accessToken["access_token"]["token"].ToString(); + var user = accessToken["user"]["name"].ToString(); + var network = accessToken["network"]["name"].ToString(); + + PSVariable token = new PSVariable(Properties.Resources.TokenVariable, bearer); + SessionState.PSVariable.Set(token); + WriteObject(string.Format("\nBearer token received and set for user '{0}' in Yammer network '{1}'. To show it type: Show-YmToken \n", user, network)); + } + catch (Exception e) + { + var errorRecord = new ErrorRecord(e, "0", ErrorCategory.PermissionDenied, tokenUrl); + WriteError(errorRecord); + } + } + } +} diff --git a/src/YammerShell/CmdLets/GetYmUser.cs b/src/YammerShell/CmdLets/GetYmUser.cs new file mode 100644 index 0000000..5c3deae --- /dev/null +++ b/src/YammerShell/CmdLets/GetYmUser.cs @@ -0,0 +1,289 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Management.Automation; +using YammerShell.YammerObjects; + +namespace YammerShell.CmdLets +{ + [Cmdlet(VerbsCommon.Get, "YmUser", DefaultParameterSetName = "Id")] + public class GetYmUser : PSCmdlet + { + private Request _request; + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + Position = 0, + HelpMessage = "ID of a user", + ParameterSetName = "Id" + )] + public int? Id { get; set; } + + [ValidateRange(1,1000)] + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + HelpMessage = "Limit returned users amount", + ParameterSetName = "Group" + )] + [Parameter(ParameterSetName = "Email")] + [Parameter(ParameterSetName = "StartLetter")] + [Parameter(ParameterSetName = "Id")] + public int? Limit { get; set; } + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + HelpMessage = "Return users in reverse order" + )] + public SwitchParameter Reverse { get; set; } + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + HelpMessage = "Return the current user", + ParameterSetName = "Current" + )] + public SwitchParameter Current { get; set; } + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + HelpMessage = "ID of a group", + Mandatory = true, + ParameterSetName = "Group" + )] + public int? GroupId { get; set; } + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + Mandatory = true, + HelpMessage = "Email of a user", + ParameterSetName = "Email" + )] + public string Email { get; set; } + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + HelpMessage = "Return users with usernames beginning with the given character", + Mandatory = true, + ParameterSetName = "StartLetter" + )] + public char? StartLetter { get; set; } + + protected override void ProcessRecord() + { + var token = SessionState.PSVariable.Get(Properties.Resources.TokenVariable); + if (token == null) + { + WriteWarning(Properties.Resources.EmptyTokenWarning); + return; + } + _request = new Request(token.Value.ToString()); + + var yammerUsers = new List(); + + if (Current.IsPresent) + { + try + { + var user = GetCurrentYammerUser(); + WriteObject(user); + } + catch (Exception e) + { + var errorRecord = new ErrorRecord(e, "3", ErrorCategory.InvalidArgument, Current); + WriteError(errorRecord); + } + return; + } + if (Id.HasValue) + { + try + { + var user = GetYammerUser(Id.Value); + WriteObject(user); + } + catch (Exception e) + { + var errorRecord = new ErrorRecord(e, "94", ErrorCategory.InvalidArgument, Id); + WriteError(errorRecord); + } + return; + } + if (Email != null) + { + try + { + var users = GetYammerUsers(Email); + WriteObject(users); + } + catch (Exception e) + { + var errorRecord = new ErrorRecord(e, "513", ErrorCategory.InvalidArgument, Email); + WriteError(errorRecord); + } + return; + } + if (GroupId.HasValue) + { + try + { + var users = GetYammerUsersInGroup(GroupId); + WriteObject(users); + } + catch (Exception e) + { + var errorRecord = new ErrorRecord(e, "g1", ErrorCategory.InvalidArgument, GroupId); + WriteError(errorRecord); + } + return; + } + try + { + WriteObject(GetYammerUsers(), true); + } + catch (Exception e) + { + var errorRecord = new ErrorRecord(e, "4566", ErrorCategory.InvalidArgument, Id); + WriteError(errorRecord); + } + } + + private object GetCurrentYammerUser() + { + var result = _request.Get(string.Format("{0}users/current.json", Properties.Resources.YammerApi)); + var user = JObject.Parse(result); + return GetYammerUser(user); + } + + private IEnumerable GetYammerUsersInGroup(int? groupId) + { + var result = _request.Get(string.Format("{0}users/in_group/{1}.json?reverse={2}", Properties.Resources.YammerApi, GroupId, Reverse.IsPresent)); + var groupUsers = JObject.Parse(result); + var users = JArray.Parse(groupUsers["users"].ToString()); + + var allYammerUsers = new List(); + foreach (var user in users) + { + allYammerUsers.Add(GetYammerUser(user)); + } + return allYammerUsers; + } + + public YammerUser GetYammerUser(int id) + { + var result = _request.Get(string.Format("{0}users/{1}.json", Properties.Resources.YammerApi, id)); + var user = JObject.Parse(result); + return GetYammerUser(user); + } + + public IEnumerable GetYammerUsers(string email) + { + var result = _request.Get(string.Format("{0}users/by_email.json?email={1}&reverse={2}", Properties.Resources.YammerApi, email, Reverse.IsPresent)); + var users = JArray.Parse(result); + + var allYammerUsers = new List(); + foreach (var user in users) + { + allYammerUsers.Add(GetYammerUser(user)); + } + return allYammerUsers; + } + + public IEnumerable GetYammerUsers() + { + var letterParameter = string.Empty; + if (StartLetter.HasValue) + { + letterParameter = "&letter=" + StartLetter; + } + + var allYammerUsers = new List(); + var requestsStarted = DateTime.Now.Ticks; + for (int page = 1; ; page++) + { + var result = _request.Get(string.Format("{0}users.json?page={1}&reverse={2}{3}", Properties.Resources.YammerApi, page, Reverse.IsPresent, letterParameter)); + var users = JArray.Parse(result); + + foreach (var user in users) + { + if (Limit == null || allYammerUsers.Count < Limit) + { + allYammerUsers.Add(GetYammerUser(user)); + } + else + { + return allYammerUsers; + } + } + if (users.Count == 0) + { + break; + } + // 50 users will be shown per page + if (page * 50 >= Limit && (Limit - page * 50) <= 0) + { + break; + } + // wait to prevent 10 requests in 10 seconds + if (page % 10 == 0) + { + if (requestsStarted + TimeSpan.FromSeconds(9).Ticks >= DateTime.Now.Ticks) + { + var PowerShellInstance = PowerShell.Create(); + PowerShellInstance.AddCommand("Start-Sleep"); + PowerShellInstance.AddParameter("Seconds", 2); + PowerShellInstance.Invoke(); + PowerShellInstance.Dispose(); + } + requestsStarted = DateTime.Now.Ticks; + } + } + return allYammerUsers; + } + + private YammerUser GetYammerUser(JToken user) + { + var yammerUser = new YammerUser(); + yammerUser.Id = Convert.ToInt32(GetToken(user, "id")); + yammerUser.UserName = GetToken(user, "name"); + yammerUser.FirstName = GetToken(user, "first_name"); + yammerUser.LastName = GetToken(user, "last_name"); + yammerUser.FullName = GetToken(user, "full_name"); + yammerUser.Email = GetToken(user, "email"); + yammerUser.JobTitle = GetToken(user, "job_title"); + yammerUser.Department = GetToken(user, "department"); + yammerUser.Timezone = GetToken(user, "timezone"); + yammerUser.NetworkId = Convert.ToInt32(GetToken(user, "network_id")); + yammerUser.NetworkName = GetToken(user, "network_name"); + yammerUser.Url = GetToken(user, "web_url"); + var activatedAt = user["activated_at"]; + yammerUser.ActivatedAt = activatedAt.Type == JTokenType.Null ? DateTime.MinValue : (DateTime)user["activated_at"]; + + var phoneNumbers = new List(); + var numbers = user["contact"]["phone_numbers"]; + foreach (var number in numbers) + { + phoneNumbers.Add(number["number"].ToString()); + } + yammerUser.PhoneNumbers = phoneNumbers; + + return yammerUser; + } + + private string GetToken(JToken token, string key) + { + var value = token[key]; + if (value == null) + { + return ""; + } + return value.ToString(); + } + + } +} diff --git a/src/YammerShell/CmdLets/NewYmGroup.cs b/src/YammerShell/CmdLets/NewYmGroup.cs new file mode 100644 index 0000000..d09289d --- /dev/null +++ b/src/YammerShell/CmdLets/NewYmGroup.cs @@ -0,0 +1,67 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Management.Automation; + +namespace YammerShell.CmdLets +{ + [Cmdlet(VerbsCommon.New, "YmGroup")] + public class NewYmGroup : PSCmdlet + { + private Request _request; + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + Mandatory = true, + Position = 0, + HelpMessage = "Name of the new yammer group" + )] + public string Name { get; set; } + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + HelpMessage = "Description of the new yammer group" + )] + public string Description { get; set; } + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + HelpMessage = "If the group should be private" + )] + public SwitchParameter Private { get; set; } + + protected override void ProcessRecord() + { + var token = SessionState.PSVariable.Get(Properties.Resources.TokenVariable); + if (token == null) + { + WriteWarning(Properties.Resources.EmptyTokenWarning); + return; + } + _request = new Request(token.Value.ToString()); + + string requestUrl = Properties.Resources.YammerApi + "groups.json?name=" + Name; + if (Private.IsPresent) + { + requestUrl += "&private=true"; + } + if (Description != null) + { + requestUrl += "&description=" + Description; + } + try + { + var response = _request.Post(requestUrl, string.Empty); + var newGroup = JObject.Parse(response); + WriteObject(Convert.ToInt32(newGroup["id"])); + } + catch (Exception e) + { + var errorRecord = new ErrorRecord(e, "94", ErrorCategory.InvalidArgument, Name); + WriteError(errorRecord); + } + } + } +} diff --git a/src/YammerShell/CmdLets/NewYmMessage.cs b/src/YammerShell/CmdLets/NewYmMessage.cs new file mode 100644 index 0000000..4828a5f --- /dev/null +++ b/src/YammerShell/CmdLets/NewYmMessage.cs @@ -0,0 +1,104 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; + +namespace YammerShell.CmdLets +{ + [Cmdlet(VerbsCommon.New, "YmMessage")] + public class NewYmMessage : PSCmdlet + { + private Request _request; + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + HelpMessage = "ID of an existing conversation", + ParameterSetName = "Replied" + )] + public int? RepliedToId { get; set; } + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + HelpMessage = "ID of a yammer group", + ParameterSetName = "Group" + )] + public int? GroupId { get; set; } + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + HelpMessage = "Send a private message to one or more users, specified by ID", + ParameterSetName = "Private" + )] + public int[] DirectToUserIds { get; set; } + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + Mandatory = true, + Position = 0, + HelpMessage = "Body of the message" + )] + public string Body { get; set; } + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + HelpMessage = "Set that the message is of type announcement and set the title of the announcement", + ParameterSetName = "Announcement" + )] + [Parameter(ParameterSetName = "Group")] + public string AnnouncementTitle { get; set; } + + protected override void ProcessRecord() + { + var token = SessionState.PSVariable.Get(Properties.Resources.TokenVariable); + if (token == null) + { + WriteWarning(Properties.Resources.EmptyTokenWarning); + return; + } + _request = new Request(token.Value.ToString()); + + string directToUsers = string.Empty; + string repliedTo = string.Empty; + string group = string.Empty; + string announcement = string.Empty; + + if (GroupId != null) + { + group = "&group_id=" + GroupId; + } + if (DirectToUserIds != null) + { + directToUsers = "&direct_to_user_ids=" + string.Join(",", DirectToUserIds.Select(i => i.ToString()).ToArray()); + } + if (AnnouncementTitle != null) + { + announcement = "&is_rich_text=true&message_type=announcement&title=" + AnnouncementTitle; + } + if (RepliedToId != null) + { + repliedTo = "&replied_to_id=" + RepliedToId; + } + + try + { + var response = _request.Post(string.Format("{0}messages.json?body={1}{2}{3}{4}{5}", Properties.Resources.YammerApi, Body, repliedTo, directToUsers, group, announcement), string.Empty); + var jObject = JObject.Parse(response); + var messages = JArray.Parse(jObject["messages"].ToString()); + var id = messages[0]["id"]; + WriteObject(Convert.ToInt32(id)); + } + catch (Exception e) + { + var errorRecord = new ErrorRecord(e, "42", ErrorCategory.InvalidArgument, "Arguments invalid"); + WriteError(errorRecord); + } + } + + } +} diff --git a/src/YammerShell/CmdLets/NewYmUser.cs b/src/YammerShell/CmdLets/NewYmUser.cs new file mode 100644 index 0000000..6a1adbc --- /dev/null +++ b/src/YammerShell/CmdLets/NewYmUser.cs @@ -0,0 +1,116 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Management.Automation; + +namespace YammerShell.CmdLets +{ + [Cmdlet(VerbsCommon.New, "YmUser")] + public class NewYmUser : PSCmdlet + { + private Request _request; + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + Mandatory = true, + Position = 0, + HelpMessage = "Email of the new user" + )] + public string Email { get; set; } + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + HelpMessage = "Full name of the new user" + )] + public string FullName { get; set; } + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + HelpMessage = "Job title of the new user" + )] + public string JobTitle { get; set; } + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + HelpMessage = "Department name of the new user" + )] + public string DepartmentName { get; set; } + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + HelpMessage = "Location of the new user" + )] + public string Location { get; set; } + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + HelpMessage = "Work phone number of the new user" + )] + public string WorkTelephone { get; set; } + + + protected override void ProcessRecord() + { + var token = SessionState.PSVariable.Get(Properties.Resources.TokenVariable); + if (token == null) + { + WriteWarning(Properties.Resources.EmptyTokenWarning); + return; + } + _request = new Request(token.Value.ToString()); + + string fullName = string.Empty; + string jobTitle = string.Empty; + string departmentName = string.Empty; + string location = string.Empty; + string workTelephone = string.Empty; + + if (FullName != null) + { + fullName = "&full_name=" + FullName; + } + if (jobTitle != null) + { + jobTitle = "&job_title=" + JobTitle; + } + if (DepartmentName != null) + { + departmentName = "&department_name=" + DepartmentName; + } + if (Location != null) + { + location = "&location=" + Location; + } + int ignore; + if (WorkTelephone != null && int.TryParse(WorkTelephone, out ignore)) + { + workTelephone = "&work_telephone=" + WorkTelephone; + } + else + { + var errorRecord = new ErrorRecord(new ArgumentException(), WorkTelephone, ErrorCategory.InvalidArgument, WorkTelephone); + WriteError(errorRecord); + return; + } + + try + { + // TODO test as admin if new user gets created and id is returned + var url = string.Format("{0}users.json?{1}{2}{3}{4}{5}{6}", Properties.Resources.YammerApi, Email, fullName, jobTitle, departmentName, location, workTelephone); + var response = _request.Post(url, string.Empty); + var newUser = JObject.Parse(response); + WriteObject(Convert.ToInt32(newUser["id"])); + } + catch (Exception e) + { + var errorRecord = new ErrorRecord(e, "X", ErrorCategory.InvalidArgument, Email); + WriteError(errorRecord); + } + } + } +} diff --git a/src/YammerShell/CmdLets/RemoveYmGroupMembership.cs b/src/YammerShell/CmdLets/RemoveYmGroupMembership.cs new file mode 100644 index 0000000..5cad3cc --- /dev/null +++ b/src/YammerShell/CmdLets/RemoveYmGroupMembership.cs @@ -0,0 +1,57 @@ +using System; +using System.Management.Automation; + +namespace YammerShell.CmdLets +{ + [Cmdlet(VerbsCommon.Remove, "YmGroupMembership", DefaultParameterSetName = "UserId")] + public class RemoveYmGroupMembership : PSCmdlet + { + private Request _request; + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + Mandatory = true, + Position = 0, + HelpMessage = "ID of a yammer group" + )] + public int? GroupId { get; set; } + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + HelpMessage = "ID of the user to leave the group", + ParameterSetName = "UserId" + )] + public int? UserId { get; set; } + + protected override void ProcessRecord() + { + var token = SessionState.PSVariable.Get(Properties.Resources.TokenVariable); + if (token == null) + { + WriteWarning(Properties.Resources.EmptyTokenWarning); + return; + } + _request = new Request(token.Value.ToString()); + + string userId = string.Empty; + if (UserId != null) + { + userId = "&user_id=" + UserId; + } + + try + { + var url = string.Format("{0}group_memberships.json?group_id={1}{2}", Properties.Resources.YammerApi, GroupId, userId); + _request.Delete(url); + } + catch (Exception e) + { + var errorRecord = new ErrorRecord(e, "e", ErrorCategory.InvalidArgument, "Arguments invalid"); + WriteError(errorRecord); + } + } + + } +} diff --git a/src/YammerShell/CmdLets/RemoveYmMessage.cs b/src/YammerShell/CmdLets/RemoveYmMessage.cs new file mode 100644 index 0000000..9f204cd --- /dev/null +++ b/src/YammerShell/CmdLets/RemoveYmMessage.cs @@ -0,0 +1,41 @@ +using System; +using System.Management.Automation; + +namespace YammerShell.CmdLets +{ + [Cmdlet(VerbsCommon.Remove, "YmMessage")] + public class RemoveYmMessage : PSCmdlet + { + private Request _request; + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + Mandatory = true, + Position = 0, + HelpMessage = "ID of the message to delete" + )] + public int Id { get; set; } + + protected override void ProcessRecord() + { + var token = SessionState.PSVariable.Get(Properties.Resources.TokenVariable); + if (token == null) + { + WriteWarning(Properties.Resources.EmptyTokenWarning); + return; + } + _request = new Request(token.Value.ToString()); + + try + { + _request.Delete(string.Format("{0}messages/{1}", Properties.Resources.YammerApi, Id)); + } + catch (Exception e) + { + var errorRecord = new ErrorRecord(e, "94", ErrorCategory.InvalidArgument, Id); + WriteError(errorRecord); + } + } + } +} diff --git a/src/YammerShell/CmdLets/SearchYmItem.cs b/src/YammerShell/CmdLets/SearchYmItem.cs new file mode 100644 index 0000000..b0b201b --- /dev/null +++ b/src/YammerShell/CmdLets/SearchYmItem.cs @@ -0,0 +1,220 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Management.Automation; +using YammerShell.YammerObjects; + +namespace YammerShell.CmdLets +{ + [Cmdlet(VerbsCommon.Search, "YmItem")] + public class SearchYmItem : PSCmdlet + { + private Request _request; + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + Position = 0, + Mandatory = true, + HelpMessage = "Term to search" + )] + public string SearchItem { get; set; } + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + HelpMessage = "Number of the result page (max 20 items per page)" + )] + public int Page { get; set; } = 1; + + [ValidateRange(1, 20)] + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + HelpMessage = "Maximum of results for each page (between 1 and 20)." + )] + public int Limit { get; set; } = 20; + + protected override void ProcessRecord() + { + var token = SessionState.PSVariable.Get(Properties.Resources.TokenVariable); + if (token == null) + { + WriteWarning(Properties.Resources.EmptyTokenWarning); + return; + } + _request = new Request(token.Value.ToString()); + + try + { + var url = string.Format("{0}search.json?search={1}&num_per_page={2}&page={3}", Properties.Resources.YammerApi, SearchItem, Limit, Page); + var response = JObject.Parse(_request.Get(url)); + + var searchResult = GetYammerSearchResult(response); + searchResult.Page = Page; + WriteObject(searchResult); + } + catch (Exception e) + { + var errorRecord = new ErrorRecord(e, "533", ErrorCategory.InvalidOperation, SearchItem); + WriteError(errorRecord); + } + } + + private YammerSearchResult GetYammerSearchResult(JObject response) + { + var yammerSearchResult = new YammerSearchResult(); + + var count = response["count"]; + yammerSearchResult.TotalMessages = Convert.ToInt32(count["messages"]); + yammerSearchResult.TotalGroups = Convert.ToInt32(count["groups"]); + yammerSearchResult.TotalTopics = Convert.ToInt32(count["topics"]); + yammerSearchResult.TotalFiles = Convert.ToInt32(count["uploaded_files"]); + yammerSearchResult.TotalUsers = Convert.ToInt32(count["users"]); + + var messages = new List(); + foreach (var message in JArray.Parse(response["messages"]["messages"].ToString())) + { + messages.Add(GetYammerMessage(message)); + } + yammerSearchResult.Messages = messages; + + var groups = new List(); + foreach (var group in JArray.Parse(response["groups"].ToString())) + { + groups.Add(GetYammerGroup(group)); + } + yammerSearchResult.Groups = groups; + + var topics = new List(); + foreach (var topic in JArray.Parse(response["topics"].ToString())) + { + topics.Add(GetYammerTopic(topic)); + } + yammerSearchResult.Topics = topics; + + var files = new List(); + foreach (var file in JArray.Parse(response["uploaded_files"].ToString())) + { + files.Add(GetYammerFile(file)); + } + yammerSearchResult.Files = files; + + var users = new List(); + foreach (var user in JArray.Parse(response["users"].ToString())) + { + users.Add(GetYammerUser(user)); + } + yammerSearchResult.Users = users; + + return yammerSearchResult; + } + + private YammerUser GetYammerUser(JToken user) + { + var yammerUser = new YammerUser(); + yammerUser.Id = Convert.ToInt32(GetToken(user, "id")); + yammerUser.UserName = GetToken(user, "name"); + yammerUser.FirstName = GetToken(user, "first_name"); + yammerUser.LastName = GetToken(user, "last_name"); + yammerUser.FullName = GetToken(user, "full_name"); + yammerUser.Email = GetToken(user, "email"); + yammerUser.JobTitle = GetToken(user, "job_title"); + yammerUser.Department = GetToken(user, "department"); + yammerUser.Timezone = GetToken(user, "timezone"); + yammerUser.NetworkId = Convert.ToInt32(GetToken(user, "network_id")); + yammerUser.NetworkName = GetToken(user, "network_name"); + yammerUser.Url = GetToken(user, "web_url"); + var activatedAt = user["activated_at"]; + yammerUser.ActivatedAt = activatedAt.Type == JTokenType.Null ? DateTime.MinValue : (DateTime)user["activated_at"]; + + var phoneNumbers = new List(); + foreach (var number in new JArray(user["phone_numbers"]).Children()) + { + phoneNumbers.Add(number.ToString()); + } + yammerUser.PhoneNumbers = phoneNumbers; + + return yammerUser; + } + + private string GetToken(JToken token, string key) + { + var value = token[key]; + if (value == null) + { + return ""; + } + return value.ToString(); + } + + private YammerFile GetYammerFile(JToken file) + { + var yammerFile = new YammerFile(); + + yammerFile.Id = Convert.ToInt32(file["id"]); + yammerFile.NetworkId = Convert.ToInt32(file["network_id"]); + yammerFile.GroupId = file.Value("group_id"); + yammerFile.OwnerId = file.Value("owner_id"); + yammerFile.Url = file["web_url"].ToString(); + yammerFile.Name = file["name"].ToString(); + yammerFile.Description = file["description"].ToString(); + yammerFile.ContentClass = file["content_class"].ToString(); + yammerFile.CreatedAt = (DateTime)file["created_at"]; + yammerFile.Privacy = file["privacy"].ToString(); + + return yammerFile; + } + + private YammerTopic GetYammerTopic(JToken topic) + { + var yammerTopic = new YammerTopic(); + yammerTopic.Id = Convert.ToInt32(topic["id"]); + yammerTopic.Name = topic["name"].ToString(); + yammerTopic.NetworkId = Convert.ToInt32(topic["network_id"]); + yammerTopic.Url = topic["web_url"].ToString(); + return yammerTopic; + } + + private YammerGroup GetYammerGroup(JToken group) + { + var yammerGroup = new YammerGroup(); + yammerGroup.Id = Convert.ToInt32(group["id"]); + yammerGroup.Email = group["email"].ToString(); + yammerGroup.FullName = group["full_name"].ToString(); + yammerGroup.Name = group["name"].ToString(); + yammerGroup.NetworkId = Convert.ToInt32(group["network_id"]); + yammerGroup.Description = group["description"].ToString(); + yammerGroup.Privacy = group["privacy"].ToString(); + yammerGroup.Url = group["web_url"].ToString(); + yammerGroup.CreatedAt = (DateTime)group["created_at"]; + yammerGroup.CreatorId = Convert.ToInt32(group["creator_id"]); + yammerGroup.Members = Convert.ToInt32(group["stats"]["members"]); + return yammerGroup; + } + + private YammerMessage GetYammerMessage(JToken message) + { + var yammerMessage = new YammerMessage(); + yammerMessage.Id = Convert.ToInt32(message["id"]); + yammerMessage.SenderId = Convert.ToInt32(message["sender_id"]); + yammerMessage.RepliedToId = message.Value("replied_to_id"); + yammerMessage.CreatedAt = (DateTime)message["created_at"]; + yammerMessage.NetworkId = Convert.ToInt32(message["network_id"]); + yammerMessage.MessageType = message["message_type"].ToString(); + yammerMessage.GroupId = message.Value("group_id"); + yammerMessage.Body = message["body"]["plain"].ToString(); + yammerMessage.Url = message["web_url"].ToString(); + + var attachments = new List(); + foreach (var attachment in JArray.Parse(message["attachments"].ToString())) + { + attachments.Add(attachment["web_url"].ToString()); + } + yammerMessage.AttachmentUrls = attachments; + + return yammerMessage; + } + + } +} diff --git a/src/YammerShell/CmdLets/SendYmInvitation.cs b/src/YammerShell/CmdLets/SendYmInvitation.cs new file mode 100644 index 0000000..07ee4b5 --- /dev/null +++ b/src/YammerShell/CmdLets/SendYmInvitation.cs @@ -0,0 +1,50 @@ +using System; +using System.Management.Automation; +using System.Text; + +namespace YammerShell.CmdLets +{ + [Cmdlet(VerbsCommunications.Send, "YmInvitation")] + public class SendYmInvitation : PSCmdlet + { + private Request _request; + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + Mandatory = true, + Position = 0, + HelpMessage = "Emails of users which have not yet joined the network." + )] + public string[] Emails { get; set; } + + protected override void ProcessRecord() + { + var token = SessionState.PSVariable.Get(Properties.Resources.TokenVariable); + if (token == null) + { + WriteWarning(Properties.Resources.EmptyTokenWarning); + return; + } + _request = new Request(token.Value.ToString()); + + try + { + var url = new StringBuilder(); + url.Append(Properties.Resources.YammerApi + "invitations.json?email=" + Emails[0]); + + for (int i = 1; i < Emails.Length; i++) + { + url.Append("&email="); + url.Append(Emails[i]); + } + _request.Post(url.ToString(), string.Empty); // TODO test as admin + } + catch (Exception e) + { + var errorRecord = new ErrorRecord(e, "01", ErrorCategory.InvalidArgument, Emails); + WriteError(errorRecord); + } + } + } +} diff --git a/src/YammerShell/CmdLets/SetYmToken.cs b/src/YammerShell/CmdLets/SetYmToken.cs new file mode 100644 index 0000000..0cd0a10 --- /dev/null +++ b/src/YammerShell/CmdLets/SetYmToken.cs @@ -0,0 +1,23 @@ +using System.Management.Automation; + +namespace YammerShell +{ + [Cmdlet(VerbsCommon.Set, "YmToken")] + public class SetYmToken : PSCmdlet + { + [Parameter( + Mandatory = true, + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + Position = 0, + HelpMessage = "Bearer token needed to authorize." + )] + public string Token { get; set; } + + protected override void ProcessRecord() + { + PSVariable token = new PSVariable(Properties.Resources.TokenVariable, Token); + SessionState.PSVariable.Set(token); + } + } +} diff --git a/src/YammerShell/CmdLets/ShowYmRelationships.cs b/src/YammerShell/CmdLets/ShowYmRelationships.cs new file mode 100644 index 0000000..421202a --- /dev/null +++ b/src/YammerShell/CmdLets/ShowYmRelationships.cs @@ -0,0 +1,113 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Management.Automation; +using YammerShell.YammerObjects; + +namespace YammerShell.CmdLets +{ + [Cmdlet(VerbsCommon.Show, "YmRelationships")] + public class ShowYmRelationships : PSCmdlet + { + private Request _request; + + [Parameter( + ValueFromPipelineByPropertyName = true, + ValueFromPipeline = true, + Position = 0, + HelpMessage = "ID of a user", + ParameterSetName = "Id" + )] + public int? UserId { get; set; } + + protected override void ProcessRecord() + { + var token = SessionState.PSVariable.Get(Properties.Resources.TokenVariable); + if (token == null) + { + WriteWarning(Properties.Resources.EmptyTokenWarning); + return; + } + _request = new Request(token.Value.ToString()); + + try + { + var response = _request.Get(Properties.Resources.YammerApi + "relationships.json?user_id=" + UserId); + + var relationships = JObject.Parse(response); + var allSubordinates = JArray.Parse(relationships["subordinates"].ToString()); + var allSuperiors = JArray.Parse(relationships["superiors"].ToString()); + var allColleagues = JArray.Parse(relationships["colleagues"].ToString()); + + var yammerRelationship = new YammerRelationship(); + var subordinates = new List(); + var colleagues = new List(); + var superiors = new List(); + + foreach (var subordinate in allSubordinates) + { + subordinates.Add(GetYammerUser(subordinate)); + } + yammerRelationship.Subordinates = subordinates; + + foreach (var colleague in allColleagues) + { + colleagues.Add(GetYammerUser(colleague)); + } + yammerRelationship.Colleagues = colleagues; + + foreach (var superior in allSuperiors) + { + superiors.Add(GetYammerUser(superior)); + } + yammerRelationship.Superiors = superiors; + + WriteObject(yammerRelationship); + } + catch (Exception e) + { + var errorRecord = new ErrorRecord(e, "94", ErrorCategory.InvalidArgument, UserId); + WriteError(errorRecord); + } + } + + private YammerUser GetYammerUser(JToken user) + { + var yammerUser = new YammerUser(); + yammerUser.UserName = GetToken(user, "name"); + yammerUser.Id = Convert.ToInt32(GetToken(user, "id")); + yammerUser.FirstName = GetToken(user, "first_name"); + yammerUser.LastName = GetToken(user, "last_name"); + yammerUser.FullName = GetToken(user, "full_name"); + yammerUser.Email = GetToken(user, "email"); + yammerUser.JobTitle = GetToken(user, "job_title"); + yammerUser.Department = GetToken(user, "department"); + yammerUser.Timezone = GetToken(user, "timezone"); + yammerUser.NetworkId = Convert.ToInt32(GetToken(user, "network_id")); + yammerUser.NetworkName = GetToken(user, "network_name"); + yammerUser.Url = GetToken(user, "web_url"); + var activatedAt = user["activated_at"]; + yammerUser.ActivatedAt = activatedAt.Type == JTokenType.Null ? DateTime.MinValue : (DateTime)user["activated_at"]; + + var phoneNumbers = new List(); + foreach (var number in new JArray(user["phone_numbers"]).Children()) + { + phoneNumbers.Add(number.ToString()); + } + yammerUser.PhoneNumbers = phoneNumbers; + + return yammerUser; + } + + private string GetToken(JToken token, string key) + { + var value = token[key]; + if (value == null) + { + return ""; + } + return value.ToString(); + } + + } +} diff --git a/src/YammerShell/CmdLets/ShowYmToken.cs b/src/YammerShell/CmdLets/ShowYmToken.cs new file mode 100644 index 0000000..c50136f --- /dev/null +++ b/src/YammerShell/CmdLets/ShowYmToken.cs @@ -0,0 +1,19 @@ +using System.Management.Automation; + +namespace YammerShell.CmdLets +{ + [Cmdlet(VerbsCommon.Show, "YmToken")] + public class ShowYmToken : PSCmdlet + { + protected override void ProcessRecord() + { + var token = SessionState.PSVariable.Get(Properties.Resources.TokenVariable); + if (token == null) + { + WriteWarning(Properties.Resources.EmptyTokenWarning); + return; + } + WriteObject(token.Value); + } + } +} diff --git a/src/YammerShell/Properties/AssemblyInfo.cs b/src/YammerShell/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..c92ee18 --- /dev/null +++ b/src/YammerShell/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("YammerShell")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("YammerShell")] +[assembly: AssemblyCopyright("Copyright © 2016")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("37ef96fc-171a-4da2-90b3-eaf32caea259")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/YammerShell/Properties/Resources.Designer.cs b/src/YammerShell/Properties/Resources.Designer.cs new file mode 100644 index 0000000..2159d72 --- /dev/null +++ b/src/YammerShell/Properties/Resources.Designer.cs @@ -0,0 +1,90 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace YammerShell.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("YammerShell.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to Bearer Token not set! You can set it with 'Set-YmToken [-Token] <string>' oder create a new with Get-YmToken.. + /// + internal static string EmptyTokenWarning { + get { + return ResourceManager.GetString("EmptyTokenWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to GLOBAL:AutoGeneratedVariableYammerBearerToken. + /// + internal static string TokenVariable { + get { + return ResourceManager.GetString("TokenVariable", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to https://www.yammer.com/api/v1/. + /// + internal static string YammerApi { + get { + return ResourceManager.GetString("YammerApi", resourceCulture); + } + } + } +} diff --git a/src/YammerShell/Properties/Resources.resx b/src/YammerShell/Properties/Resources.resx new file mode 100644 index 0000000..3e11926 --- /dev/null +++ b/src/YammerShell/Properties/Resources.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Bearer Token not set! You can set it with 'Set-YmToken [-Token] <string>' oder create a new with Get-YmToken. + + + GLOBAL:AutoGeneratedVariableYammerBearerToken + + + https://www.yammer.com/api/v1/ + + \ No newline at end of file diff --git a/src/YammerShell/Request.cs b/src/YammerShell/Request.cs new file mode 100644 index 0000000..9a27355 --- /dev/null +++ b/src/YammerShell/Request.cs @@ -0,0 +1,80 @@ +using System.IO; +using System.Net; +using System.Text; +using System.Web; + +namespace YammerShell +{ + public class Request + { + public Request(string token) + { + _token = token; + } + private string _token; + + public string Get(string url) + { + HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; + request.Method = WebRequestMethods.Http.Get; + request.Headers.Add("Authorization", "Bearer " + _token); + + HttpWebResponse response = request.GetResponse() as HttpWebResponse; + + string result; + using (StreamReader reader = new StreamReader(response.GetResponseStream())) + { + result = reader.ReadToEnd(); + } + response.Close(); + + return result; + } + + public string Post(string url, string postData) + { + HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; + request.Method = WebRequestMethods.Http.Post; + request.Headers.Add("Authorization", "Bearer " + _token); + + if (postData.StartsWith("{")) + { + request.ContentType = "application/json"; + } + else + { + request.ContentType = "x-www-form-urlencoded"; + postData = HttpUtility.UrlPathEncode(postData); + } + byte[] postBytes = Encoding.UTF8.GetBytes(postData); + request.ContentLength = postBytes.Length; + + using (var stream = request.GetRequestStream()) + { + stream.Write(postBytes, 0, postBytes.Length); + } + + HttpWebResponse response = request.GetResponse() as HttpWebResponse; + + string result; + using (StreamReader reader = new StreamReader(response.GetResponseStream())) + { + result = reader.ReadToEnd(); + } + response.Close(); + + return result; + } + + public void Delete(string url) + { + HttpWebRequest request = WebRequest.Create(HttpUtility.UrlPathEncode(url)) as HttpWebRequest; + request.Method = "DELETE"; + request.Headers.Add("Authorization", "Bearer " + _token); + + HttpWebResponse response = request.GetResponse() as HttpWebResponse; + response.Close(); + } + + } +} diff --git a/src/YammerShell/YammerObjects/YammerFile.cs b/src/YammerShell/YammerObjects/YammerFile.cs new file mode 100644 index 0000000..e646405 --- /dev/null +++ b/src/YammerShell/YammerObjects/YammerFile.cs @@ -0,0 +1,18 @@ +using System; + +namespace YammerShell.YammerObjects +{ + public class YammerFile + { + public int Id { get; set; } + public int NetworkId { get; set; } + public int? GroupId { get; set; } + public int? OwnerId { get; set; } + public string Url { get; set; } + public string Name { get; set; } + public string Description { get; set; } + public string ContentClass { get; set; } + public DateTime CreatedAt { get; set; } + public string Privacy { get; set; } + } +} \ No newline at end of file diff --git a/src/YammerShell/YammerObjects/YammerGroup.cs b/src/YammerShell/YammerObjects/YammerGroup.cs new file mode 100644 index 0000000..f592eef --- /dev/null +++ b/src/YammerShell/YammerObjects/YammerGroup.cs @@ -0,0 +1,19 @@ +using System; + +namespace YammerShell.YammerObjects +{ + public class YammerGroup + { + public int Id { get; set; } + public string Email { get; set; } + public string FullName { get; set; } + public string Name { get; set; } + public int NetworkId { get; set; } + public string Description { get; set; } + public string Privacy { get; set; } + public string Url { get; set; } + public DateTime CreatedAt { get; set; } + public int CreatorId { get; set; } + public int Members { get; set; } + } +} diff --git a/src/YammerShell/YammerObjects/YammerMessage.cs b/src/YammerShell/YammerObjects/YammerMessage.cs new file mode 100644 index 0000000..6302c3d --- /dev/null +++ b/src/YammerShell/YammerObjects/YammerMessage.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; + +namespace YammerShell.YammerObjects +{ + public class YammerMessage + { + public int Id { get; set; } + public int SenderId { get; set; } + public int? RepliedToId { get; set; } + public DateTime CreatedAt { get; set; } + public int NetworkId { get; set; } + public string MessageType { get; set; } + public int? GroupId { get; set; } + public string Body { get; set; } + public IEnumerable AttachmentUrls { get; set; } + public string Url { get; set; } + } +} diff --git a/src/YammerShell/YammerObjects/YammerNetwork.cs b/src/YammerShell/YammerObjects/YammerNetwork.cs new file mode 100644 index 0000000..afb7c90 --- /dev/null +++ b/src/YammerShell/YammerObjects/YammerNetwork.cs @@ -0,0 +1,20 @@ +using System; + +namespace YammerShell.YammerObjects +{ + public class YammerNetwork + { + public int Id { get; set; } + public string Email { get; set; } + public string Name { get; set; } + public string Url { get; set; } + public bool Paid { get; set; } + public bool IsOrgChartEnabled { get; set; } + public bool IsGroupEnabled { get; set; } + public bool IsChatEnabled { get; set; } + public bool IsTranslationEnabled { get; set; } + public DateTime CreatedAt { get; set; } + public bool AllowSamlAuthentication { get; set; } + public bool EnforceOfficeAuthentication { get; set; } + } +} \ No newline at end of file diff --git a/src/YammerShell/YammerObjects/YammerRelationship.cs b/src/YammerShell/YammerObjects/YammerRelationship.cs new file mode 100644 index 0000000..b42484b --- /dev/null +++ b/src/YammerShell/YammerObjects/YammerRelationship.cs @@ -0,0 +1,11 @@ +using System.Collections.Generic; + +namespace YammerShell.YammerObjects +{ + public class YammerRelationship + { + public IEnumerable Superiors { get; set; } + public IEnumerable Colleagues { get; set; } + public IEnumerable Subordinates { get; set; } + } +} diff --git a/src/YammerShell/YammerObjects/YammerSearchResult.cs b/src/YammerShell/YammerObjects/YammerSearchResult.cs new file mode 100644 index 0000000..95fb28c --- /dev/null +++ b/src/YammerShell/YammerObjects/YammerSearchResult.cs @@ -0,0 +1,20 @@ +using System.Collections.Generic; + +namespace YammerShell.YammerObjects +{ + public class YammerSearchResult + { + public int Page { get; set; } + public int TotalMessages { get; set; } + public int TotalGroups { get; set; } + public int TotalTopics { get; set; } + public int TotalFiles { get; set; } + public int TotalUsers { get; set; } + + public IEnumerable Messages { get; set; } + public IEnumerable Groups { get; set; } + public IEnumerable Topics { get; set; } + public IEnumerable Files { get; set; } + public IEnumerable Users { get; set; } + } +} diff --git a/src/YammerShell/YammerObjects/YammerTopic.cs b/src/YammerShell/YammerObjects/YammerTopic.cs new file mode 100644 index 0000000..1ffee15 --- /dev/null +++ b/src/YammerShell/YammerObjects/YammerTopic.cs @@ -0,0 +1,10 @@ +namespace YammerShell.YammerObjects +{ + public class YammerTopic + { + public int Id { get; set; } + public int NetworkId { get; set; } + public string Name { get; set; } + public string Url { get; set; } + } +} \ No newline at end of file diff --git a/src/YammerShell/YammerObjects/YammerUser.cs b/src/YammerShell/YammerObjects/YammerUser.cs new file mode 100644 index 0000000..a4843c1 --- /dev/null +++ b/src/YammerShell/YammerObjects/YammerUser.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; + +namespace YammerShell.YammerObjects +{ + public class YammerUser + { + public int Id { get; set; } + public string UserName { get; set; } + public string FirstName { get; set; } + public string LastName { get; set; } + public string FullName { get; set; } + public string Email { get; set; } + public string JobTitle { get; set; } + public string Department { get; set; } + public string Timezone { get; set; } + public int NetworkId { get; set; } + public string NetworkName { get; set; } + public IEnumerable PhoneNumbers { get; set; } + public DateTime ActivatedAt { get; set; } + public string Url { get; set; } + } +} diff --git a/src/YammerShell/YammerShell.csproj b/src/YammerShell/YammerShell.csproj new file mode 100644 index 0000000..5c8b457 --- /dev/null +++ b/src/YammerShell/YammerShell.csproj @@ -0,0 +1,103 @@ + + + + + Debug + AnyCPU + {37EF96FC-171A-4DA2-90B3-EAF32CAEA259} + Library + Properties + YammerShell + YammerShell + v3.5 + 512 + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\Newtonsoft.Json.9.0.1\lib\net35\Newtonsoft.Json.dll + True + + + + + False + ..\..\..\..\..\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\3.0\System.Management.Automation.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + True + True + Resources.resx + + + + + + + + + + + + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + + + + + + \ No newline at end of file diff --git a/src/YammerShell/packages.config b/src/YammerShell/packages.config new file mode 100644 index 0000000..ff91865 --- /dev/null +++ b/src/YammerShell/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file