├── .gitignore ├── LICENSE ├── README Assets └── AC_Angular.png ├── README-Localized ├── README-de-de.md ├── README-es-es.md ├── README-fr-fr.md ├── README-ja-jp.md ├── README-pt-br.md ├── README-ru-ru.md └── README-zh-tw.md ├── README.md ├── app ├── assets │ ├── Aero.png │ ├── Bird-art.png │ ├── Facial.png │ ├── Fearther-art.png │ ├── Leakage.png │ ├── MS Robot.png │ ├── Mountain-art.png │ ├── Win.png │ └── guitar-art.png ├── controllers │ ├── mainController.js │ ├── navBarController.js │ └── settingsController.js ├── index.html ├── scripts │ └── app.js ├── styles.css └── views │ ├── main.html │ └── settings.html ├── package.json └── server.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/* 2 | app/bower_components/* -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Office 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README Assets/AC_Angular.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OfficeDev/O365-Angular-ArtCurator/f2feca00a0ea67fa430d06487987ff43950d4b65/README Assets/AC_Angular.png -------------------------------------------------------------------------------- /README-Localized/README-de-de.md: -------------------------------------------------------------------------------- 1 | # Art Curator für Angular 2 | 3 | In diesem Beispiel wird veranschaulicht, wie Sie die Outlook-E-Mail-API verwenden, um E-Mails und Anhänge aus Office 365 abzurufen. Die API ist für [iOS](https://github.com/OfficeDev/O365-iOS-ArtCurator), [Android](https://github.com/OfficeDev/O365-Android-ArtCurator), Web (Angular Web App) und [Windows Phone](https://github.com/OfficeDev/O365-WinPhone-ArtCurator) ausgelegt. Lesen Sie dazu auch unseren [Artikel auf Medium](https://medium.com/office-app-development) und sehen Sie sich dieses [YouTube-Video mit der exemplarischen Vorgehensweise](https://www.youtube.com/watch?v=M88A6VB9IIw&feature=youtu.be) an. 4 | 5 | Mit Art Curator können Sie Ihren Posteingang auf andere Weise anzeigen. Angenommen, Sie besitzen ein Unternehmen, das künstlerisch gestaltete T-Shirts verkauft. Als Inhaber des Unternehmens erhalten Sie eine Vielzahl von E-Mails von Künstlern mit Designs, die Sie von den Künstlern erwerben sollen. Anstatt jede einzelne E-Mail mit Outlook zu öffnen, das angehängte Bild herunterzuladen und es dann zum Ansehen zu öffnen, können Sie mit Art Curator zuerst alle Anhänge Ihres Posteingangs (nur JPG- und PNG-Dateien) anzeigen, um auf effiziente Weise die gewünschten Designs auszuwählen. 6 | 7 | [![Art Curator Screenshot](../README Assets/AC_Angular.png)](https://youtu.be/4LOvkweDfhY "Click to see the sample in action.") 8 | 9 | In diesem Beispiel werden folgende Vorgänge der **Outlook-E-Mail-API** veranschaulicht: 10 | * [Abrufen von Ordnern](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#GetFolders) 11 | * [Abrufen von Nachrichten](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#Getmessages) (einschließlich Filtern und Verwendung der Auswahl) 12 | * [Abrufen von Anhängen](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#GetAttachments) 13 | * [Aktualisieren von Nachrichten](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#Updatemessages) 14 | * [Erstellen und Senden von Nachrichten](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#Sendmessages) (mit und ohne Anhang) 15 | 16 | In diesem Beispiel wird auch die Authentifizierung mit Azure Active Directory mithilfe der [Active Directory Authentifizierungsbibliothek (Active Directory Authentication Library, ADAL) für JavaScript](https://github.com/AzureAD/azure-activedirectory-library-for-js) veranschaulicht. 17 | 18 | 19 | ## Voraussetzungen 20 | 21 | Für dieses Beispiel ist Folgendes erforderlich: 22 | * [Node.js](https://nodejs.org/). Node ist für das Ausführen des Beispiels auf einem Entwicklungsserver und für das Installieren der Abhängigkeiten erforderlich. 23 | * Ein Office 365-Konto. Sie können sich für [ein Office 365-Entwicklerabonnement](http://aka.ms/ro9c62) registrieren. Dieses umfasst die Ressourcen, die Sie zum Erstellen von Office 365-Apps benötigen. 24 | 25 | 26 | ## Registrieren der App 27 | 28 | 1. Um dieses Beispiel schnell nutzen zu können, führen Sie die Anweisungen im [App-Registrierungstool des Outlook-Entwicklerportals](https://dev.outlook.com/appregistration) aus. 29 | 2. Melden Sie sich in **Schritt 1** mit Ihrem Office 365-Konto an oder klicken Sie auf die Schaltfläche für eine kostenlose Testversion. Fahren Sie nach der Anmeldung mit dem nächsten Schritt fort. 30 | 3. Geben Sie in **Schritt 2** folgende Werte in das Formular ein. 31 | * *App-Name:* Art Curator 32 | * *App-Typ:* Single-Page app (SPA) 33 | * *Umleitungs-URI:* http://127.0.0.1:8080/ 34 | * *Homepage-URL:* http://artcurator.{Ihre_Unterdomäne}.com (.onmicrosoft-Unterdomäne Ihres Office 365-Mandanten) 35 | 4. Wählen Sie in **Schritt 3** unter **E-Mail-API** die folgenden Berechtigungen aus. 36 | * *Lese- und Schreibberechtigungen für E-Mail* 37 | * *E-Mail senden* 38 | 5. Klicken Sie in **Schritt 4** auf **App registrieren**, um Ihre App im Azure Active Directory zu registrieren. 39 | 6. Kopieren Sie schließlich die **Client-ID** aus dem Formular, um sie im nächsten Abschnitt zu verwenden. 40 | 41 | 42 | ## Ausführen der App 43 | 44 | Öffnen Sie *app/scripts/app.js* und ersetzen Sie jeweils in den Zeilen 46 und 47 *{your_tenant}* mit der .onmicrosoft-Unterdomäne, die Sie für Ihren Office 365-Mandanten angegeben haben, und der vom Registrierungstool des Outlook-Entwicklerportals empfangenen Client-ID Ihrer für Azure registrierten App. 45 | 46 | Installieren Sie als Nächstes die erforderlichen Abhängigkeiten und führen Sie das Projekt über die Befehlszeile aus. Öffnen Sie dazu als Erstes eine Eingabeaufforderung und navigieren Sie zum Stammordner. Führen Sie anschließend folgende Schritte durch. 47 | 48 | 1. Installieren Sie die Projektabhängigkeiten, indem Sie ```npm install``` ausführen. 49 | 2. Nachdem nun alle Projektabhängigkeiten installiert sind, starten Sie den Entwicklungsserver, indem Sie ```node server.js``` im Stammordner ausführen. 50 | 3. Navigieren Sie im Webbrowser zu ```http://127.0.0.1:8080/```. 51 | 52 | 53 | ## Grundlegendes zum Code 54 | 55 | ### Verbinden mit Office 365 56 | 57 | Dieses Projekt verwendet für die Authentifizierung bei Azure Active Directory die [Active Directory Authentifizierungsbibliothek (Active Directory Authentication Library, ADAL) für JavaScript](https://github.com/AzureAD/azure-activedirectory-library-for-js), um Token für die Verwendung der Office 365-APIs anzufordern und zu empfangen. 58 | 59 | Der Dienst wird in *app/app.js* in der config-Funktion des Moduls konfiguriert. In *app/controllers/navBarController.js* gibt es zwei Funktionen, die die An- und Abmeldung bei Azure Active Directory verarbeiten, welches auch das Abrufen von Token verarbeitet. 60 | 61 | ### E-Mail-API 62 | 63 | Dieses Projekt verwendet Standard-REST-Aufrufe, um mit der E-Mail-API zu interagieren. Informationen zu den verfügbaren Endpunkten finden Sie im Leitfaden [Outlook Mail REST API](https://msdn.microsoft.com/en-us/office/office365/api/mail-rest-operations). 64 | 65 | Sämtliche Funktionen der E-Mail-API befinden sich in *app/controllers/mainController.js*. Zuerst werden alle im Mandanten des Benutzers verfügbaren Ordner abgerufen und mithilfe des in *localStorage* gespeicherten Werts nach dem Zielordner gesucht. Danach werden die 50 aktuellsten E-Mails abgerufen, die ungelesen sind und über Anhänge verfügen. Dann werden Aufrufe ausgeführt, um den Inhalt der einzelnen Anhänge zu abzurufen. An diesem Punkt liegen alle E-Mails und Inhalte der Anhänge vor. Sie werden in einem Array gespeichert, das der anzuzeigenden Ansicht zur Verfügung gestellt wird. 66 | 67 | Weitere Funktionen von *mainController.js* sind das Markieren von E-Mails als gelesen und das Erstellen und Versenden von Antworten. 68 | 69 | ### Einschränkungen 70 | 71 | Die folgenden Funktionen sind in der aktuellen Version nicht enthalten. 72 | 73 | * Unterstützung anderer Dateien als .png und .jpg 74 | * Verarbeitung von E-Mails mit mehreren Anhängen 75 | * Paging (Abrufen von mehr als 50 E-Mails) 76 | * Verarbeitung der Eindeutigkeit von Ordnernamen 77 | * Der Ordner zum Senden muss ein Ordner der obersten Ebene sein. 78 | 79 | ## Sicherheitshinweis 80 | [ADAL JS](https://github.com/AzureAD/azure-activedirectory-library-for-js) überprüft das von Azure AD empfangene Token nicht. Dies ist Aufgabe des Back-End der App, und solange Sie das Back-End nicht aufrufen, wissen Sie nicht, ob der Benutzer ein zulässiges Token erworben hat. Geschäftsanwendungen sollten aus Sicherheitsgründen eine serverseitige Komponente zur Benutzerauthentifizierung in der Webanwendung integriert haben. Ohne diese Überprüfung des Tokens durch das Back-End ist die App anfällig für Angriffe wie z. B. das [Confused-Deputy-Problem](https://en.wikipedia.org/wiki/Confused_deputy_problem). Weitere Informationen finden Sie in diesem [Blogbeitrag](http://www.cloudidentity.com/blog/2015/02/19/introducing-adal-js-v1/). 81 | 82 | 83 | ## Fragen und Kommentare 84 | 85 | - Wenn Sie beim Ausführen dieses Beispiels Probleme haben, [melden Sie sie bitte](https://github.com/OfficeDev/O365-Angular-ArtCurator/issues). 86 | - Allgemeine Fragen zu den Office 365-APIs können Sie auf [Stack Overflow](http://stackoverflow.com/) stellen. Stellen Sie sicher, dass Ihre Fragen oder Kommentare mit [office365] markiert sind. 87 | 88 | 89 | ## Zusätzliche Ressourcen 90 | 91 | * [Erstellen einer Angular-App mit Office 365-APIs](http://aka.ms/get-started-with-js) 92 | * [Office 365-APIs – Plattformübersicht](http://msdn.microsoft.com/office/office365/howto/platform-development-overview) 93 | * [Office Dev Center](http://dev.office.com/) 94 | * [Art Curator für iOS](https://github.com/OfficeDev/O365-iOS-ArtCurator) 95 | * [Art Curator für Android](https://github.com/OfficeDev/O365-Android-ArtCurator) 96 | * [Art Curator für Windows Phone](https://github.com/OfficeDev/O365-WinPhone-ArtCurator) 97 | 98 | ## Copyright 99 | Copyright (c) 2015 Microsoft. Alle Rechte vorbehalten. 100 | -------------------------------------------------------------------------------- /README-Localized/README-es-es.md: -------------------------------------------------------------------------------- 1 | # Art Curator para Angular 2 | 3 | Este ejemplo muestra cómo usar la API de Correo de Outlook para obtener correos electrónicos y datos adjuntos de Office 365. Se ha creado para [iOS](https://github.com/OfficeDev/O365-iOS-ArtCurator), [Android](https://github.com/OfficeDev/O365-Android-ArtCurator), Web (aplicación web Angular) y [Windows Phone](https://github.com/OfficeDev/O365-WinPhone-ArtCurator). Consulte nuestro [artículo en Medium](https://medium.com/office-app-development) y este [vídeo tutorial en YouTube](https://www.youtube.com/watch?v=M88A6VB9IIw&feature=youtu.be). 4 | 5 | Art Curator es una forma diferente de ver la bandeja de entrada. Imagine que posee una empresa que vende camisetas artísticas. Como propietario de la empresa, recibe muchos mensajes de correo electrónico de artistas con diseños que desean que compre. En vez de usar Outlook y abrir cada correo electrónico por separado, descargar la imagen adjunta y, a continuación, abrirla para verla, puede usar Art Curator para proporcionarle una primera vista del archivo adjunto (../limitada a archivos .jpg y .png) de su bandeja de entrada para elegir y seleccionar los diseños que le gustan de una forma más eficaz. 6 | 7 | [![Art Curator Screenshot](../README Assets/AC_Angular.png)](https://youtu.be/4LOvkweDfhY "Click to see the sample in action.") 8 | 9 | Este ejemplo muestra las siguientes operaciones desde la **API de Correo de Outlook**: 10 | * [Obtener carpetas](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#GetFolders) 11 | * [Obtener mensajes](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#Getmessages) (incluyendo la selección de filtrado y uso) 12 | * [Obtener datos adjuntos](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#GetAttachments) 13 | * [Actualizar mensajes](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#Updatemessages) 14 | * [Crear y enviar mensajes](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#Sendmessages) (con y sin datos adjuntos) 15 | 16 | Este ejemplo también muestra la autenticación con Azure Active Directory mediante la [biblioteca de autenticación de Active Directory (ADAL) para JavaScript](https://github.com/AzureAD/azure-activedirectory-library-for-js). 17 | 18 | 19 | ## Requisitos previos 20 | 21 | Este ejemplo requiere lo siguiente: 22 | * [Node.js](https://nodejs.org/). Node es necesario para ejecutar el ejemplo en un servidor de desarrollo y para instalar las dependencias. 23 | * Una cuenta de Office 365. Puede registrarse en [una suscripción a Office 365 Developer](http://aka.ms/ro9c62) que incluye los recursos que necesita para comenzar a crear aplicaciones de Office 365. 24 | 25 | 26 | ## Registrar la aplicación 27 | 28 | 1. Para poner este ejemplo en funcionamiento rápidamente, vaya a la [herramienta de registro de aplicaciones del Portal de desarrollo de Outlook](https://dev.outlook.com/appregistration). 29 | 2. En el **Paso 1**, inicie sesión con su cuenta existente de Office 365 o haga clic en el botón para obtener una prueba gratuita. Después de iniciar sesión, vaya al paso siguiente. 30 | 3. En el **Paso 2**, rellene el formulario con los siguientes valores. 31 | * *Nombre de la aplicación:* Art Curator 32 | * *Tipo de aplicación:* Aplicación de una sola página (SPA) 33 | * *Identificador URI de redireccionamiento:* http://127.0.0.1:8080/ 34 | * *Dirección URL de página principal:* http://artcurator.{your_subdomain}.com (el subdominio de .onmicrosoft de su inquilino de Office 365) 35 | 4. En el **Paso 3**, seleccione los siguientes permisos debajo de **API de correo**. 36 | * *Leer y escribir correo* 37 | * *Enviar correo* 38 | 5. En el **Paso 4**, haga clic en **Registrar aplicación** para registrar su aplicación con Azure Active Directory. 39 | 6. Por último, copie el **identificador de cliente** desde el formulario para usarlo en la siguiente sección. 40 | 41 | 42 | ## Ejecutar la aplicación 43 | 44 | Abra *app/scripts/app.js* y reemplace *{su_inquilino}* con el subdominio de .onmicrosoft que especificó para su inquilino de Office 365 y el identificador de cliente de su aplicación de Azure registrada que recibió desde la herramienta de registro de aplicaciones del Portal de desarrollo de Outlook en el último paso, en las líneas 46 y 47 respectivamente. 45 | 46 | A continuación, instale las dependencias necesarias y ejecute el proyecto a través de la línea de comandos. Empiece abriendo un símbolo del sistema y vaya a la carpeta raíz. Una vez allí, siga los siguientes pasos. 47 | 48 | 1. Instale las dependencias del proyecto ejecutando ```npm install```. 49 | 2. Ahora que todas las dependencias del proyecto están instaladas, inicie el servidor de desarrollo ejecutando ```node server.js``` en la carpeta raíz. 50 | 3. Vaya a ```http://127.0.0.1:8080/``` en el explorador web. 51 | 52 | 53 | ## Entender el código 54 | 55 | ### Conectarse a Office 365 56 | 57 | Este proyecto usa [Azure Active Directory usando la biblioteca de Azure Active Directory (ADAL) para JavaScript](https://github.com/AzureAD/azure-activedirectory-library-for-js) para autenticar con Azure Active Directory con el fin de solicitar y recibir tokens para su uso con las API de Office 365. 58 | 59 | El servicio está configurado en *app/app.js* en la función de configuración del módulo. En *app/controllers/navBarController.js*, hay dos funciones que controlan el inicio y el cierre de sesión de Azure Active Directory, que también controla la adquisición de tokens. 60 | 61 | ### API de correo 62 | 63 | Este proyecto usa llamadas REST estándar para interactuar con la API de correo. Consulte la [referencia de la API de REST de Correo de Outlook](https://msdn.microsoft.com/en-us/office/office365/api/mail-rest-operations) para obtener información sobre los puntos de conexión disponibles. 64 | 65 | Toda la funcionalidad de la API de correo reside en *app/controllers/mainController.js*. En primer lugar, obtiene todas las carpetas disponibles en el inquilino del usuario y usa el valor almacenado en *localStorage* para encontrar la carpeta de destino. A continuación, obtiene los 50 correos electrónicos más recientes que no se han leído y contienen datos adjuntos. Después, se realizan llamadas para obtener el contenido de cada uno de los archivos adjuntos. En este punto, dispone de todos los correos electrónicos y del contenido de los datos adjuntos y se almacenan en una matriz que está disponible para su visualización. 66 | 67 | Otra funcionalidad incluida en *mainController.js* incluye marcar los correos electrónicos como leídos y crear y enviar respuestas. 68 | 69 | ### Limitaciones 70 | 71 | Las características siguientes no se incluyen en la versión actual. 72 | 73 | * Compatibilidad de archivos además de .png y .jpg 74 | * Controlar un solo correo electrónico con varios datos adjuntos 75 | * Paginación (obtener más de 50 correos electrónicos) 76 | * Controlar la unicidad del nombre de carpeta 77 | * La carpeta de envío debe ser una carpeta de nivel superior 78 | 79 | ## Aviso de seguridad 80 | [ADAL JS](https://github.com/AzureAD/azure-activedirectory-library-for-js) no valida el token recibido desde Azure AD. Cuenta con el back-end de la aplicación para hacerlo, y hasta que llame al back-end, no sabe si el usuario obtuvo un token aceptable. Las aplicaciones empresariales deberían tener un componente del lado del servidor para la autenticación integrada del usuario en la aplicación web por motivos de seguridad. Sin esta validación del token del lado del back-end, su aplicación es susceptible a los ataques de seguridad como el [problema "confused deputy"](https://en.wikipedia.org/wiki/Confused_deputy_problem). Consulte esta [publicación del blog](http://www.cloudidentity.com/blog/2015/02/19/introducing-adal-js-v1/) para obtener más información. 81 | 82 | 83 | ## Preguntas y comentarios 84 | 85 | - Si tiene algún problema al ejecutar este ejemplo, [regístrelo](https://github.com/OfficeDev/O365-Angular-ArtCurator/issues). 86 | - Para realizar preguntas generales acerca de las API de Office 365, publíquelas en [Stack Overflow](http://stackoverflow.com/). Asegúrese de que sus preguntas o comentarios se etiquetan con [office365]. 87 | 88 | 89 | ## Recursos adicionales 90 | 91 | * [Crear una aplicación de Angular con las API de Office 365](http://aka.ms/get-started-with-js) 92 | * [Información general de la plataforma de las API de Office 365](http://msdn.microsoft.com/office/office365/howto/platform-development-overview) 93 | * [Centro de desarrollo de Office](http://dev.office.com/) 94 | * [Art Curator para iOS](https://github.com/OfficeDev/O365-iOS-ArtCurator) 95 | * [Art Curator para Android](https://github.com/OfficeDev/O365-Android-ArtCurator) 96 | * [Art Curator para Windows Phone](https://github.com/OfficeDev/O365-WinPhone-ArtCurator) 97 | 98 | ## Copyright 99 | Copyright (c) 2015 Microsoft. Todos los derechos reservados. 100 | 101 | -------------------------------------------------------------------------------- /README-Localized/README-fr-fr.md: -------------------------------------------------------------------------------- 1 | # Art Curator pour Angular 2 | 3 | Cet exemple présente comment utiliser l’API de messagerie Outlook pour obtenir des messages électroniques et des pièces jointes à partir d’Office 365. Il est conçu pour [iOS](https://github.com/OfficeDev/O365-iOS-ArtCurator), [Android](https://github.com/OfficeDev/O365-Android-ArtCurator), Web (application web Angular) et [Windows Phone](https://github.com/OfficeDev/O365-WinPhone-ArtCurator). Consultez notre [article sur Medium](https://medium.com/office-app-development) et cette [vidéo YouTube présentant la procédure pas à pas](https://www.youtube.com/watch?v=M88A6VB9IIw&feature=youtu.be). 4 | 5 | Art Curator propose une nouvelle façon d’afficher votre boîte de réception. Imaginez que vous êtes propriétaire d’une entreprise qui vend des tee-shirts artistiques. En tant que propriétaire de l’entreprise, vous recevez de nombreux messages électroniques de la part d’artistes comportant des conceptions qu’ils tentent de vous vendre. Au lieu d’utiliser Outlook et d’ouvrir chaque message individuellement, de télécharger l’image jointe, puis de l’ouvrir pour l’afficher, vous pouvez utiliser Art Curator pour avoir un premier aperçu des pièces jointes de votre boîte de réception (../limité aux fichiers .jpg et .png) afin de sélectionner et choisir les conceptions qui vous plaisent de façon plus efficace. 6 | 7 | [![Art Curator Screenshot](../README Assets/AC_Angular.png)](https://youtu.be/4LOvkweDfhY "Click to see the sample in action.") 8 | 9 | Cet exemple illustre les opérations suivantes à réaliser à partir de l’**API de messagerie Outlook** : 10 | * [Obtenir des dossiers](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#GetFolders) 11 | * [Obtenir des messages](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#Getmessages) (y compris le filtrage et la sélection) 12 | * [Obtenir des pièces jointes](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#GetAttachments) 13 | * [Mettre à jour des messages](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#Updatemessages) 14 | * [Créer et envoyer des messages](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#Sendmessages) (avec et sans pièce jointe) 15 | 16 | Cet exemple présente également l’authentification auprès d’Azure Active Directory à l’aide d’[ADAL (Active Directory Authentication Library) pour JavaScript](https://github.com/AzureAD/azure-activedirectory-library-for-js). 17 | 18 | 19 | ## Conditions requises 20 | 21 | Cet exemple nécessite les éléments suivants : 22 | * [Node.js](https://nodejs.org/). Node est requis pour exécuter l’exemple sur un serveur de développement et installer des dépendances. 23 | * Un compte Office 365. Vous pouvez vous inscrire à [Office 365 Developer](http://aka.ms/ro9c62) pour accéder aux ressources dont vous avez besoin pour commencer à créer des applications Office 365. 24 | 25 | 26 | ## Inscription de l’application 27 | 28 | 1. Pour configurer et exécuter cet exemple rapidement, utilisez l’[outil d’inscription d’application auprès du portail de développement Outlook](https://dev.outlook.com/appregistration). 29 | 2. À l’**étape 1**, connectez-vous avec votre compte Office 365 existant ou cliquez sur le bouton pour obtenir une version d’évaluation gratuite. Une fois que vous êtes connecté, passez à l’étape suivante. 30 | 3. À l’**étape 2**, remplissez le formulaire avec les valeurs suivantes. 31 | * *Nom d’application :* Art Curator 32 | * *Type d’application :* application monopage (SPA) 33 | * *URI de redirection :* http://127.0.0.1:8080/ 34 | * *URL de la page d’accueil :* http://artcurator.{votre_sous-domaine}.com (le sous-domaine .onmicrosoft de votre client Office 365) 35 | 4. À l’**étape 3**, sélectionnez les autorisations suivantes sous **API de messagerie**. 36 | * *Lire et écrire un courrier électronique* 37 | * *Envoyer un courrier électronique* 38 | 5. À l’**étape 4**, cliquez sur **Inscrire l’application** pour inscrire votre application auprès d’Azure Active Directory. 39 | 6. Enfin, copiez l’**ID client** à partir du formulaire à utiliser dans la section suivante. 40 | 41 | 42 | ## Exécuter l’application 43 | 44 | Ouvrez *app/scripts/app.js* et remplacez *{votre_client}* par le sous-domaine .onmicrosoft que vous avez indiqué pour votre client Office 365 et l’ID client de votre application Azure inscrite envoyé par l’outil d’inscription d’application auprès du portail de développement Outlook lors de la dernière étape (lignes 46 et 47, respectivement). 45 | 46 | Ensuite, installez les dépendances nécessaires et exécutez le projet par l’intermédiaire de la ligne de commande. Commencez par ouvrir une invite de commandes et accédez au dossier racine. Une fois que vous l’avez trouvé, suivez les étapes ci-dessous. 47 | 48 | 1. Installez des dépendances du projet en exécutant ```npm install```. 49 | 2. Maintenant que toutes les dépendances du projet sont installées, démarrez le serveur de développement en exécutant ```node server.js``` dans le dossier racine. 50 | 3. Accédez à ```http://127.0.0.1:8080/``` dans votre navigateur web. 51 | 52 | 53 | ## Comprendre le code 54 | 55 | ### Connexion à Office 365. 56 | 57 | Ce projet utilise [Azure Active Directory à l’aide d’ADAL (Azure Active Directory Library) pour JavaScript](https://github.com/AzureAD/azure-activedirectory-library-for-js) pour s’authentifier auprès d’Azure Active Directory afin de demander et de recevoir des jetons pour pouvoir utiliser des API Office 365. 58 | 59 | Le service est configuré dans *app/app.js* dans la fonction de configuration du module. Dans *app/controllers/navBarController.js*, il existe deux fonctions qui gèrent la connexion à Azure Active Directory et la déconnexion. Azure Active Directory gère également l’acquisition de jetons. 60 | 61 | ### API de messagerie 62 | 63 | Ce projet utilise des appels REST standard qui permettent d’interagir avec l’API de messagerie. Reportez-vous à l’article relatif à la [référence d’API REST de messagerie Outlook](https://msdn.microsoft.com/en-us/office/office365/api/mail-rest-operations) pour plus d’informations sur les points de terminaison disponibles. 64 | 65 | L’ensemble des fonctionnalités d’API de messagerie se trouvent dans le fichier *app/controllers/mainController.js*. Tout d’abord, elle obtient tous les dossiers disponibles sur le client de l’utilisateur et utilise la valeur stockée dans *localStorage* pour rechercher le dossier cible. Après cela, elle obtient les 50 derniers courriers électroniques non lus comportant des pièces jointes. Ensuite, des appels sont émis pour obtenir le contenu de toutes ces pièces jointes. À ce stade, elle comporte tous les courriers électroniques et l’ensemble du contenu des pièces jointes qui sont stockés dans une matrice affichable. 66 | 67 | D’autres fonctionnalités incluses dans *mainController.js* comprennent le marquage des courriers électroniques comme lus, ainsi que la création et l’envoi de réponses. 68 | 69 | ### Limitations 70 | 71 | Les fonctionnalités suivantes ne sont pas incluses dans la version actuelle. 72 | 73 | * Prise en charge de formats de fichiers autres que .png et .jpg 74 | * Gestion d’un courrier électronique unique avec plusieurs pièces jointes 75 | * Pagination (réception de plus de 50 courriers électroniques) 76 | * Gestion de l’unicité des noms de dossiers 77 | * Dossier de soumission devant être un dossier de niveau supérieur 78 | 79 | ## Note de sécurité 80 | [ADAL JS](https://github.com/AzureAD/azure-activedirectory-library-for-js) ne valide pas le jeton envoyé par Azure Active Directory. Cette validation incombe au serveur principal de l’application, et jusqu’à ce que vous appeliez ce dernier, vous ne savez pas si l’utilisateur a obtenu un jeton acceptable. Pour des raisons de sécurité, les applications d’entreprise doivent comporter un composant côté serveur intégré à l’application web pour l’authentification des utilisateurs. Sans la validation du jeton par le serveur principal, votre application est vulnérable aux attaques de sécurité, telles que les [problèmes de député confus (confused deputy problem)](https://en.wikipedia.org/wiki/Confused_deputy_problem). Consultez ce [billet de blog](http://www.cloudidentity.com/blog/2015/02/19/introducing-adal-js-v1/) pour plus d’informations. 81 | 82 | 83 | ## Questions et commentaires 84 | 85 | - Si vous rencontrez des problèmes lors de l’exécution de cet exemple, veuillez [les consigner](https://github.com/OfficeDev/O365-Angular-ArtCurator/issues). 86 | - Pour des questions générales relatives aux API Office 365, publiez sur [Stack Overflow](http://stackoverflow.com/). Posez vos questions avec la balise [office365]. 87 | 88 | 89 | ## Ressources supplémentaires 90 | 91 | * [Création d’une application Angular avec des API Office 365](http://aka.ms/get-started-with-js) 92 | * [Présentation de la plateforme des API Office 365](http://msdn.microsoft.com/office/office365/howto/platform-development-overview) 93 | * [Centre de développement Office](http://dev.office.com/) 94 | * [Art Curator pour iOS](https://github.com/OfficeDev/O365-iOS-ArtCurator) 95 | * [Art Curator pour Android](https://github.com/OfficeDev/O365-Android-ArtCurator) 96 | * [Art Curator pour Windows Phone](https://github.com/OfficeDev/O365-WinPhone-ArtCurator) 97 | 98 | ## Copyright 99 | Copyright (c) 2015 Microsoft. Tous droits réservés. 100 | -------------------------------------------------------------------------------- /README-Localized/README-ja-jp.md: -------------------------------------------------------------------------------- 1 | # Angular 用 Art Curator 2 | 3 | このサンプルでは、Outlook メール API を使用して Office 365 からメールと添付ファイルを取得する方法を示します。これは、[iOS](https://github.com/OfficeDev/O365-iOS-ArtCurator)、[Android](https://github.com/OfficeDev/O365-Android-ArtCurator)、Web (Angular Web アプリ)、[Windows Phone](https://github.com/OfficeDev/O365-WinPhone-ArtCurator) 用に作成されています。[article on Medium](https://medium.com/office-app-development) and this [YouTube のチュートリアル ビデオ](https://www.youtube.com/watch?v=M88A6VB9IIw&feature=youtu.be)をご確認ください。 4 | 5 | Art Curator は、受信トレイを表示する別の方法です。芸術的な T シャツを販売する会社を経営していると想像してみてください。会社のオーナーであるあなたのもとには、買ってほしいと思うデザインを示したたくさんのメールがアーティストから届きます。Outlook を使用して個々のメールを開き、添付の画像をダウンロードしてから開いて表示する代わりに、Art Curator を使用すると、受信トレイの添付ファイル優先 (..jpg と .png ファイルに限定) ビューが最初に表示され、より効率的な方法で気に入ったデザインを選べるようになります。 6 | 7 | [![Art Curator Screenshot](../README Assets/AC_Angular.png)](https://youtu.be/4LOvkweDfhY "Click to see the sample in action.") 8 | 9 | このサンプルでは、**Outlook メール API** から行う次の操作を示します。 10 | * [フォルダーの取得](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#GetFolders) 11 | * [メッセージの取得](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#Getmessages) (フィルター処理、および選択の使用を含む) 12 | * [添付ファイルの取得](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#GetAttachments) 13 | * [メッセージの更新](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#Updatemessages) 14 | * [メッセージの作成と送信](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#Sendmessages) (添付ファイルがある場合とない場合) 15 | 16 | また、このサンプルでは [JavaScript 用 Active Directory 認証ライブラリ (ADAL)](https://github.com/AzureAD/azure-activedirectory-library-for-js) を使用した Azure Active Directory での認証も示しています。 17 | 18 | 19 | ## 前提条件 20 | 21 | このサンプルを実行するには次のものが必要です。 22 | * [Node.js](https://nodejs.org/)。Node は、開発サーバーでサンプルを実行して、依存関係をインストールするために必要です。 23 | * Office 365 アカウント。Office 365 アプリのビルドを開始するために必要なリソースを含む [Office 365 Developer サブスクリプション](http://aka.ms/ro9c62)にサインアップできます。 24 | 25 | 26 | ## アプリを登録する 27 | 28 | 1. このサンプルをすばやく稼働状態にするには、[Outlook デベロッパー ポータル アプリ登録ツール](https://dev.outlook.com/appregistration)にアクセスしてください。 29 | 2. **手順 1** で、既存の Office 365 アカウントでサインインするか、またはボタンをクリックして無料試用版を入手します。サインインした後、次の手順に進みます。 30 | 3. **手順 2** で、次の値をフォームに記入します。 31 | * *アプリ名:* Art Curator 32 | * *アプリの種類:* Single-Page app (SPA) 33 | * *リダイレクト URI:* http://127.0.0.1:8080/ 34 | * *ホーム ページ URL:* http://artcurator.{your_subdomain}.com (Office 365 テナントの .onmicrosoft のサブドメイン) 35 | 4. **手順 3** で、**メール API** の下の次のアクセス許可を選びます。 36 | * *メールの読み取りと書き込み* 37 | * *メールの送信* 38 | 5. **手順 4** で、**[アプリの登録]** をクリックして、Azure Active Directory にアプリケーションを登録します。 39 | 6. 最後に、次のセクションで使用するフォームから**クライアント ID** をコピーします。 40 | 41 | 42 | ## アプリの実行 43 | 44 | *app/scripts/app.js* を開き、行 46 で *{your_tenant}* を Office 365 テナントのために指定した .onmicrosoft のサブドメインに置き換え、行 47 で最後の手順で Outlook デベロッパー ポータル アプリ登録ツールから受け取った登録済みの Azure アプリケーションのクライアント ID を記入します。 45 | 46 | 次に、必要な依存関係をインストールし、コマンドラインからプロジェクトを実行します。まず、コマンド プロンプトを開き、ルート フォルダーに移動します。移動したら、以下の手順を行います。 47 | 48 | 1. ```npm install``` を実行して、プロジェクトの依存関係をインストールします。 49 | 2. これで、すべてのプロジェクトの依存関係がインストールされたので、ルート フォルダーで ```node server.js``` を実行して開発サーバーを起動します。 50 | 3. Web ブラウザーで ```http://127.0.0.1:8080/``` に移動します。 51 | 52 | 53 | ## コードを理解する 54 | 55 | ### Office 365 への接続 56 | 57 | このプロジェクトでは、Office 365 API を使用するためのトークンを要求して受け取るために、[JavaScript 用 Azure Active Directory Library (ADAL) を使用した Azure Active Directory](https://github.com/AzureAD/azure-activedirectory-library-for-js) を使用して Azure Active Directory で認証します。 58 | 59 | サービスは、*app/app.js* のモジュールの config 関数内で構成されています。*app/controllers/navBarController.js* には、トークンの取得も処理する Azure Active Directory へのログインとログアウトを処理する 2 つの関数があります。 60 | 61 | ### メール API 62 | 63 | このプロジェクトでは、メール API を操作する標準的な REST 呼び出しを使用します。使用可能なエンドポイントの詳細については、「[Outlook メール REST API リファレンス](https://msdn.microsoft.com/ja-jp/office/office365/api/mail-rest-operations)」をご参照ください。 64 | 65 | すべてのメール API 機能は、*app/controllers/mainController.js* にあります。まずユーザーのテナントで利用可能なすべてのフォルダーを取得し、*localStorage* に保存されている値を使用して対象のフォルダーを検索します。その後、ファイルが添付されている未読の直近のメールを 50 通取得します。次に、これらの添付ファイルのそれぞれのコンテンツを取得するために呼び出しが行われます。この時点で、すべてのメールと添付ファイルの内容があり、これらは表示用のビューで使用できる配列に格納されます。 66 | 67 | *mainController.js* に含まれるその他の機能には、メールに開封済みマークを付け、返信を作成して送信する機能があります。 68 | 69 | ### 制限事項 70 | 71 | 現在のバージョンでは、次の機能は含まれません。 72 | 73 | * .png と.jpg 以外のファイルのサポート 74 | * 添付ファイルが複数ある 1 つのメールの処理 75 | * ページング (50 通を超えるメールの受け取り) 76 | * フォルダー名の一意性の処理 77 | * 送信フォルダーは最上位のフォルダーでなければならない 78 | 79 | ## セキュリティに関する通知 80 | [ADAL JS](https://github.com/AzureAD/azure-activedirectory-library-for-js) では Azure AD から受信したトークンを検証しません。これを行うにはアプリのバックエンドを使用するため、バックエンドを呼び出すまではユーザーが許容可能なトークンを取得していたかどうかが分かりません。セキュリティ上の理由で、ビジネス アプリケーションには、ユーザー認証用のサーバー側コンポーネントが Web アプリケーションに組み込まれている必要があります。このバックエンドのトークン検証がない場合、アプリは [混乱した使節の問題](https://en.wikipedia.org/wiki/Confused_deputy_problem)などのセキュリティ攻撃に対して脆弱になります。詳細については、この [ブログの投稿](http://www.cloudidentity.com/blog/2015/02/19/introducing-adal-js-v1/)をご確認ください。 81 | 82 | 83 | ## 質問とコメント 84 | 85 | このサンプルの実行について問題がある場合は、[問題をログに記録](https://github.com/OfficeDev/O365-Angular-ArtCurator/issues)してください。 86 | Office 365 API 全般の質問については、[Stack Overflow](http://stackoverflow.com/) に投稿してください。質問やコメントには、必ず [office365] のタグを付けてください。 87 | 88 | 89 | ## その他の技術情報 90 | 91 | * [Office 365 API で Angular アプリを作成する](http://aka.ms/get-started-with-js) 92 | * [Office 365 API プラットフォームの概要](http://msdn.microsoft.com/office/office365/howto/platform-development-overview) 93 | * [Office デベロッパー センター](http://dev.office.com/) 94 | * [iOS 用 Art Curator](https://github.com/OfficeDev/O365-iOS-ArtCurator) 95 | * [Android 用 Art Curator](https://github.com/OfficeDev/O365-Android-ArtCurator) 96 | * [Windows Phone 用 Art Curator](https://github.com/OfficeDev/O365-WinPhone-ArtCurator) 97 | 98 | ## 著作権 99 | Copyright (c) 2015 Microsoft.All rights reserved. 100 | 101 | -------------------------------------------------------------------------------- /README-Localized/README-pt-br.md: -------------------------------------------------------------------------------- 1 | # Art Curator para Angular 2 | 3 | Este exemplo demonstra como usar a API de Email do Outlook para obter emails e anexos do Office 365. Ele foi criado para [iOS](https://github.com/OfficeDev/O365-iOS-ArtCurator), [Android](https://github.com/OfficeDev/O365-Android-ArtCurator), Web (aplicativo Web do Angular) e [Windows Phone](https://github.com/OfficeDev/O365-WinPhone-ArtCurator). Confira nosso [artigo sobre o Medium](https://medium.com/office-app-development) e este [vídeo com o passo a passo no YouTube](https://www.youtube.com/watch?v=M88A6VB9IIw&feature=youtu.be). 4 | 5 | O Art Curator oferece uma maneira diferente de exibir sua caixa de entrada. Imagine que você possui uma empresa que vende camisetas artísticas. Como proprietário da empresa, você recebe muitos emails de artistas com designs que eles querem que você compre. Em vez de usar o Outlook e abrir cada email individualmente, baixando a imagem anexada, e, em seguida, abrir a imagem para exibi-la, você pode usar o Art Curator para ter uma exibição prévia do anexo (../limitado aos arquivos: .jpg e .png) de sua caixa de entrada para escolher designs que você gosta de uma forma mais eficiente. 6 | 7 | [![Art Curator Screenshot](../README Assets/AC_Angular.png)](https://youtu.be/4LOvkweDfhY "Click to see the sample in action.") 8 | 9 | Este exemplo demonstra as seguintes operações a partir da **API de Email do Outlook**: 10 | * [Obter pastas](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#GetFolders) 11 | * [Obter mensagens](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#Getmessages) (incluindo filtragem e o uso da opção selecionar) 12 | * [Obter anexos](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#GetAttachments) 13 | * [Atualizar mensagens](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#Updatemessages) 14 | * [Criar e enviar mensagens](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#Sendmessages) (com e sem anexo) 15 | 16 | Este exemplo também demonstra a autenticação com o Azure Active Directory usando a [ADAL (Active Directory Authentication Library) para JavaScript](https://github.com/AzureAD/azure-activedirectory-library-for-js). 17 | 18 | 19 | ## Pré-requisitos 20 | 21 | Esse exemplo requer o seguinte: 22 | * [Node.js](https://nodejs.org/). O nó é necessário para executar o exemplo em um servidor de desenvolvimento e para instalar as dependências. 23 | * Uma conta do Office 365. Inscreva-se em [uma assinatura de Desenvolvedor do Office 365](http://aka.ms/ro9c62) que inclui os recursos necessários para começar a criar aplicativos do Office 365. 24 | 25 | 26 | ## Registrar o aplicativo 27 | 28 | 1. Para colocar este exemplo em funcionamento rapidamente, acesse a [Ferramenta de Registro do Aplicativo do Portal de Desenvolvedor do Outlook](https://dev.outlook.com/appregistration). 29 | 2. Na **Etapa 1**, entre com sua conta do Office 365 ou clique no botão para obter uma avaliação gratuita. Depois de entrar, prossiga para a próxima etapa. 30 | 3. Na **Etapa 2**, preencha o formulário com os seguintes valores. 31 | * *Nome do Aplicativo:* Art Curator 32 | * *Tipo de Aplicativo:* aplicativo de Página Única (Single-Page App, SPA) 33 | * *URI de Redirecionamento:* http://127.0.0.1:8080/ 34 | * *URL da Home Page:* http://artcurator.{seu_subdominio}.com (o subdomínio de .onmicrosoft de seu locatário do Office 365) 35 | 4. Na **Etapa 3**, escolha as seguintes permissões em **API de Email**. 36 | * *Ler e gravar emails* 37 | * *Enviar email* 38 | 5. Na **Etapa 4**, clique em **Registrar Aplicativo** para registrar seu aplicativo no Azure Active Directory. 39 | 6. Por fim, copie a **ID de cliente** do formulário para usar na próxima seção. 40 | 41 | 42 | ## Executar o aplicativo 43 | 44 | Abra *app/scripts/app.js* e substitua *{seu_locatario}* com o subdomínio de .onmicrosoft especificado para seu locatário do Office 365 e a ID de cliente do aplicativo do Azure registrado que você recebeu da Ferramenta de Registro do Aplicativo do Portal de Desenvolvedor do Outlook na última etapa nas linhas 46 e 47 , respectivamente. 45 | 46 | Em seguida, instale as dependências necessárias e execute o projeto através da linha de comando. Comece abrindo um prompt de comando e navegando para a pasta raiz. Chegando lá, siga as etapas abaixo. 47 | 48 | 1. Instalar dependências do projeto executando ```npm install```. 49 | 2. Agora que todas as dependências do projeto estão instaladas, inicie o servidor de desenvolvimento executando ```node server.js``` na pasta raiz. 50 | 3. Navegue para ```http://127.0.0.1:8080/``` em seu navegador da Web. 51 | 52 | 53 | ## Compreender o código 54 | 55 | ### Conectar-se ao Office 365 56 | 57 | Este projeto utiliza o [Azure Active Directory usando a ADAL (Azure Active Directory Library) para JavaScript](https://github.com/AzureAD/azure-activedirectory-library-for-js) na autenticação com o Azure Active Directory para solicitar e receber tokens para usar as APIs do Office 365. 58 | 59 | O serviço está configurado no *app/app.js* na função de configuração do módulo. Em *app/controllers/navBarController.js*, há duas funções que manipulam o logon e o logoff do Azure Active Directory que também trata da adquisição de tokens. 60 | 61 | ### API de Email 62 | 63 | Este projeto usa chamadas REST padrão para interagir com a API de Email. Confira a [referência da API REST de Email do Outlook](https://msdn.microsoft.com/pt-br/office/office365/api/mail-rest-operations) para obter detalhes sobre os pontos de extremidade disponíveis. 64 | 65 | A funcionalidade completa da API de Email reside em *app/controllers/mainController.js*. Primeiro, ela obtém todas as pastas disponíveis no locatário do usuário e usa o valor armazenado em *localStorage* para localizar a pasta de destino. Depois disso, ela obtém os 50 emails mais recentes que não foram lidos e têm anexos. Em seguida, chamadas são feitas para acessar o conteúdo de cada um desses anexos. Neste ponto, ela tem todos os emails e conteúdo dos anexos, e tudo isso é armazenado em uma matriz que fica disponível no modo de exibição a ser apresentado. 66 | 67 | Outras funcionalidades disponíveis em *mainController.js* incluem a marcação de emails como lidos e a criação e envio de respostas. 68 | 69 | ### Limitações 70 | 71 | Os recursos a seguir não são incluídos na versão atual. 72 | 73 | * Suporte a arquivos além de .png e .jpg 74 | * Lidar com uma única mensagem de email com vários anexos 75 | * Paginação (recebendo mais de 50 emails) 76 | * Lidar com exclusividade de nome de pasta 77 | * A pasta de envio deve ser uma pasta de nível superior 78 | 79 | ## Observação sobre segurança 80 | [ADAL JS](https://github.com/AzureAD/azure-activedirectory-library-for-js) não valida o token recebido do Azure AD. Ele se baseia no back-end do aplicativo para fazê-lo, e até que o back-end seja chamado, você não saberá se o usuário obteve um token aceitável. Os aplicativos de negócios devem ter um componente no servidor para autenticar usuários criado no aplicativo Web por motivos de segurança. Sem essa validação do token de back-end, seu aplicativo está sujeito a violações de segurança, como [problemas de Confused Deputy](https://en.wikipedia.org/wiki/Confused_deputy_problem). Confira esta [postagem de blog](http://www.cloudidentity.com/blog/2015/02/19/introducing-adal-js-v1/) para saber mais. 81 | 82 | 83 | ## Perguntas e comentários 84 | 85 | - Se você tiver problemas para executar este exemplo [registre um problema](https://github.com/OfficeDev/O365-Angular-ArtCurator/issues). 86 | - Para perguntas gerais sobre as APIs do Office 365, poste no [Stack Overflow](http://stackoverflow.com/). Verifique se suas perguntas ou seus comentários estão marcados com [office365]. 87 | 88 | 89 | ## Recursos adicionais 90 | 91 | * [Create an Angular app with Office 365 APIs](http://aka.ms/get-started-with-js) 92 | * [Visão geral da plataforma de APIs do Office 365](http://msdn.microsoft.com/office/office365/howto/platform-development-overview) 93 | * [Centro de Desenvolvimento do Office](http://dev.office.com/) 94 | * [Art Curator para iOS](https://github.com/OfficeDev/O365-iOS-ArtCurator) 95 | * [Art Curator para Android](https://github.com/OfficeDev/O365-Android-ArtCurator) 96 | * [Art Curator para Windows Phone](https://github.com/OfficeDev/O365-WinPhone-ArtCurator) 97 | 98 | ## Copyright 99 | Copyright © 2015 Microsoft. Todos os direitos reservados. 100 | 101 | -------------------------------------------------------------------------------- /README-Localized/README-ru-ru.md: -------------------------------------------------------------------------------- 1 | # Art Curator для Angular 2 | 3 | В этом примере показано, как извлекать сообщения и вложения из Office 365 с помощью API Почты Outlook. Это приложение создано для [iOS](https://github.com/OfficeDev/O365-iOS-ArtCurator), [Android](https://github.com/OfficeDev/O365-Android-ArtCurator), веб-браузера (веб-приложение на платформе Angular) и [Windows Phone](https://github.com/OfficeDev/O365-WinPhone-ArtCurator). Просмотрите нашу [статью на сайте Medium](https://medium.com/office-app-development) и это [видеоруководство на YouTube](https://www.youtube.com/watch?v=M88A6VB9IIw&feature=youtu.be). 4 | 5 | Art Curator воплощает новый подход к просмотру папки "Входящие". Представьте, что вы владеете компанией, которая продает дизайнерские футболки. Как владелец компании вы получаете много сообщений с рисунками от художников. Вместо того чтобы использовать Outlook и открывать каждое сообщение отдельно, скачивать вложенный рисунок и открывать его для просмотра, можно использовать Art Curator для просмотра вложений (только файлы JPG и PNG) из папки "Входящие". Таким образом выбирать понравившиеся рисунки намного удобнее. 6 | 7 | [![Art Curator Screenshot](../README Assets/AC_Angular.png)](https://youtu.be/4LOvkweDfhY "Click to see the sample in action.") 8 | 9 | В этом примере демонстрируются следующие операции из **API Почты Outlook**: 10 | * [Извлечение папок](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#GetFolders) 11 | * [Извлечение сообщений](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#Getmessages) (в том числе фильтрация и использование выборки) 12 | * [Извлечение вложений](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#GetAttachments) 13 | * [Обновление сообщений](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#Updatemessages) 14 | * [Создание и отправка сообщений](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#Sendmessages) (с вложением или без него) 15 | 16 | Кроме того, в этом примере демонстрируется проверка подлинности в Azure Active Directory с помощью библиотеки [Active Directory Authentication Library (ADAL) для JavaScript](https://github.com/AzureAD/azure-activedirectory-library-for-js). 17 | 18 | 19 | ## Необходимые компоненты 20 | 21 | Для этого примера требуются следующие компоненты: 22 | * [Node.js](https://nodejs.org/). Платформа Node необходима для установки зависимостей и запуска примера на сервере разработки. 23 | * Учетная запись Office 365. Вы можете [подписаться на план Office 365 для разработчиков](http://aka.ms/ro9c62), который включает ресурсы, необходимые для создания приложений Office 365. 24 | 25 | 26 | ## Регистрация приложения 27 | 28 | 1. Чтобы быстро настроить и запустить этот пример, перейдите на страницу [Outlook Dev Portal App Registration Tool](https://dev.outlook.com/appregistration). 29 | 2. На **шаге 1** войдите с помощью существующей учетной записи Office 365 или нажмите кнопку, чтобы получить бесплатную пробную версию. После входа перейдите к следующему действию. 30 | 3. На **шаге 2** заполните форму, используя приведенные ниже значения. 31 | * *Название приложения:* Art Curator 32 | * *Тип приложения:* Одностраничное приложение (SPA) 33 | * *URI перенаправления:* http://127.0.0.1:8080/ 34 | * *URL-адрес домашней страницы:* http://artcurator.{your_subdomain}.com (поддомен .onmicrosoft клиента Office 365) 35 | 4. На **шаге 3** выберите следующие разрешения в разделе **API Почты**. 36 | * *Чтение и создание писем от имени пользователя* 37 | * *Отправка почты* 38 | 5. На **шаге 4** нажмите кнопку **Зарегистрировать приложение**, чтобы зарегистрировать приложение в Azure Active Directory. 39 | 6. Наконец, скопируйте **идентификатор клиента** из формы для использования в следующем разделе. 40 | 41 | 42 | ## Запуск приложения 43 | 44 | Откройте файл *app/scripts/app.js* и замените *{your_tenant}* поддоменом .onmicrosoft, который вы указали для своего клиента Office 365, и идентификатором клиента, который вы получили на странице Outlook Dev Portal App Registration Tool на предыдущем шаге, в строках 46 и 47 соответственно. 45 | 46 | Затем установите необходимые зависимости и запустите проект с помощью командной строки. Для начала откройте командную строку и перейдите в корневую папку. Затем выполните указанные ниже действия. 47 | 48 | 1. Установите зависимости проекта с помощью команды ```npm install```. 49 | 2. Теперь, когда все зависимости проекта установлены, запустите сервер разработки с помощью файла ```node server.js``` в корневой папке. 50 | 3. Перейдите на страницу ```http://127.0.0.1:8080/``` в веб-браузере. 51 | 52 | 53 | ## Сведения о коде 54 | 55 | ### Подключение к Office 365 56 | 57 | Для запроса и получения маркеров при использовании API Office 365 необходима проверка подлинности. В этом проекте она выполняется в Azure Active Directory с помощью библиотеки [Azure Active Directory Library (ADAL) для JavaScript](https://github.com/AzureAD/azure-activedirectory-library-for-js). 58 | 59 | Служба настроена в файле *app/app.js* в функции конфигурации модуля. В файле *app/controllers/navBarController.js* есть две функции, которые отвечают за вход в службу Azure Active Directory и выход из нее. Azure Active Directory также отвечает за получение маркеров. 60 | 61 | ### API Почты 62 | 63 | В этом проекте используются стандартные вызовы REST для связи с API Почты. Дополнительные сведения о доступных конечных точках см. в [справочнике по REST API Почты Outlook](https://msdn.microsoft.com/en-us/office/office365/api/mail-rest-operations) 64 | 65 | Все функции API Почты включены в контроллер *app/controllers/mainController.js*. Сначала он извлекает сведения обо всех папках, доступных на клиенте пользователя, и использует значение в строке *localStorage* для поиска целевой папки. После этого он извлекает сведения о 50 последних непрочитанных сообщениях с вложениями. Затем с помощью вызовов он извлекает содержимое каждого из этих вложений. На этом этапе все сообщения и содержимое вложений извлечены и хранятся в массиве, доступном для просмотра. 66 | 67 | Кроме того, контроллер *mainController.js* может помечать сообщения как прочтенные, а также создавать и отправлять ответы. 68 | 69 | ### Ограничения 70 | 71 | Указанные ниже функции не включены в текущую версию. 72 | 73 | * Поддержка типов файлов, отличных от PNG и JPG 74 | * Обработка одного сообщения с несколькими вложениями 75 | * Подкачка (извлечение более 50 сообщений) 76 | * Обработка уникальности имен папок 77 | * Папкой отправки должна быть папка верхнего уровня 78 | 79 | ## Уведомление по безопасности 80 | [ADAL JS](https://github.com/AzureAD/azure-activedirectory-library-for-js) не проверяет маркер, полученный из Azure AD. За это отвечает серверная часть приложения, и до вызова серверной части неизвестно, получил ли пользователь допустимый маркер. Из соображений безопасности в бизнес-приложения должен быть встроен серверный компонент для проверки подлинности пользователей. Без этой проверки маркеров ваше приложение уязвимо для атак, например [атак на доверие](https://en.wikipedia.org/wiki/Confused_deputy_problem). Дополнительные сведения см. в этой [записи блога](http://www.cloudidentity.com/blog/2015/02/19/introducing-adal-js-v1/). 81 | 82 | 83 | ## Вопросы и комментарии 84 | 85 | — Если у вас не получается запустить этот пример, [сообщите о проблеме](https://github.com/OfficeDev/O365-Angular-ArtCurator/issues). 86 | — Общие вопросы об API Office 365 задавайте на сайте [Stack Overflow](http://stackoverflow.com/). Обязательно помечайте свои вопросы и комментарии тегом [office365]. 87 | 88 | 89 | ## Дополнительные ресурсы 90 | 91 | * [Создание приложения Angular с API Office 365](http://aka.ms/get-started-with-js) 92 | * [Обзор платформы API Office 365](http://msdn.microsoft.com/office/office365/howto/platform-development-overview) 93 | * [Центр разработки для Office](http://dev.office.com/) 94 | * [Art Curator для iOS](https://github.com/OfficeDev/O365-iOS-ArtCurator) 95 | * [Art Curator для Android](https://github.com/OfficeDev/O365-Android-ArtCurator) 96 | * [Art Curator для Windows Phone](https://github.com/OfficeDev/O365-WinPhone-ArtCurator) 97 | 98 | ## Авторские права 99 | (c) Корпорация Майкрософт (Microsoft Corporation), 2015. Все права защищены. 100 | 101 | -------------------------------------------------------------------------------- /README-Localized/README-zh-tw.md: -------------------------------------------------------------------------------- 1 | # 適用於 Angular 的 Art Curator 2 | 3 | 這個範例會示範如何使用 Outlook Mail API 來取得 Office 365 的電子郵件和附件。它針對 [iOS](https://github.com/OfficeDev/O365-iOS-ArtCurator)、[Android](https://github.com/OfficeDev/O365-Android-ArtCurator)、Web (Angular Web 應用程式) 和 [Windows Phone](https://github.com/OfficeDev/O365-WinPhone-ArtCurator) 建立。查看我們在 [上的文章](https://medium.com/office-app-development)與此 [YouTube 上的逐步解說影片](https://www.youtube.com/watch?v=M88A6VB9IIw&feature=youtu.be)。 4 | 5 | Art Curator 提供不同的方法來檢視您的收件匣。假設您擁有一家銷售藝術 T 恤的公司。身為公司的擁有人,您會收到大量藝術家的電子郵件,希望您購買他們的設計。比起使用 Outlook 並開啟每個個別的電子郵件、下載附加的圖片,然後開啟它來檢視;您可以先使用 Art Curator 來預覽收件匣的附件 (../限於 .jpg 和 .png 檔案),以更有效率的方式挑選所要的設計。 6 | 7 | [![Art Curator Screenshot](../README Assets/AC_Angular.png)](https://youtu.be/4LOvkweDfhY "Click to see the sample in action.") 8 | 9 | 這個範例會示範來自 **Outlook Mail API** 的下列作業︰ 10 | * [取得資料夾](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#GetFolders) 11 | * [取得訊息](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#Getmessages) (包括篩選和使用選取) 12 | * [取得附件](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#GetAttachments) 13 | * [更新訊息](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#Updatemessages) 14 | * [建立和傳送訊息](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#Sendmessages) (包含和不含附件) 15 | 16 | 本範例也會示範使用 [JavaScript 適用的 Active Directory 驗證程式庫 (ADAL)](https://github.com/AzureAD/azure-activedirectory-library-for-js) 進行 Azure Active Directory 的驗證。 17 | 18 | 19 | ## 必要條件 20 | 21 | 此範例需要下列項目: 22 | * [Node.js](https://nodejs.org/)。需要有 Node 才能在開發伺服器上執行範例以及安裝相依項目。 23 | * Office 365 帳戶。您可以註冊 [Office 365 開發人員訂用帳戶](http://aka.ms/ro9c62),其中包含開始建置 Office 365 應用程式所需的資源。 24 | 25 | 26 | ## 註冊應用程式 27 | 28 | 1. 若要讓此範例快速地啟動並執行,請移至 [Outlook 開發人員入口網站應用程式註冊工具](https://dev.outlook.com/appregistration)。 29 | 2. 在**步驟 1** 中,以現有的 Office 365 帳號登入,或按一下按鈕,以取得免費的試用版。登入後,請繼續下一個步驟。 30 | 3. 在**步驟 2** 中,以下列值填寫表單。 31 | * *應用程式名稱︰* Art Curator 32 | * *應用程式類型︰* 單頁應用程式 (SPA) 33 | * *重新導向 URI︰* http://127.0.0.1:8080/ 34 | * *首頁 URL︰* http://artcurator.{your_subdomain}.com (您 Office 365 租用戶的 .onmicrosoft 子網域) 35 | 4. 在**步驟 3** 中,選取**Mail API** 下方的下列權限。 36 | * *閱讀和撰寫郵件* 37 | * *傳送郵件* 38 | 5. 在**步驟 4** 中,按一下 [註冊應用程式] 以 Azure Active Directory 來註冊您的應用程式。 39 | 6. 最後,從表單中複製**「用戶端識別碼」**在下一區段中使用。 40 | 41 | 42 | ## 執行應用程式 43 | 44 | 開啟 *app/scripts/app.js*,並分別以您指定的 Office 365 租用戶 .onmicrosoft 子網域,和您從「Outlook 開發人員入口網站應用程式註冊工具」所收到,註冊的 Azure 應用程式用戶端識別碼,來取代最後一個步驟中,第 46 和 47 行上的 *{your_tenant}*。 45 | 46 | 接下來,安裝所需的相依性,並透過命令列執行專案。開始時,請開啟命令提示字元並瀏覽至根資料夾。一旦到達那裏,請依照下列步驟。 47 | 48 | 1. 藉由執行 ```npm install``` 來安裝專案相依性。 49 | 2. 現在已安裝所有專案相依性,執行根資料夾中的 ```node server.js``` 以啟動程式開發伺服器。 50 | 3. 在網頁瀏覽器中瀏覽至 ```http://127.0.0.1:8080/```。 51 | 52 | 53 | ## 瞭解程式碼 54 | 55 | ### 連線至 Office 365 56 | 57 | 此專案使用[「使用 JavaScript 適用的 Active Directory 驗證程式庫 (ADAL) 的 Azure Active Directory」](https://github.com/AzureAD/azure-activedirectory-library-for-js)來驗證 Azure Active Directory,才能要求並接收使用 Office 365 API 的權杖。 58 | 59 | 該服務要在模組的組態函數中 *app/app.js* 內設定。在 *app/controllers/navBarController.js* 中,有兩個函數會處理 Azure Active Directory 的登入和登出,它們也處理權杖的取得。 60 | 61 | ### Mail API 62 | 63 | 此專案會使用標準的 REST 呼叫來與 Mail API 互動。請參閱 [「Outlook Mail REST API 參照」](https://msdn.microsoft.com/en-us/office/office365/api/mail-rest-operations)以獲得關於可用端點的詳細資訊。 64 | 65 | 所有的 Mail API 功能存在於以下路徑:*app/controllers/mainController.js*。首先,它會在使用者租用戶中取得所有可用的資料夾,並使用 *localStorage 中的儲存值*來尋找目標資料夾。在那之後,它會取得 50 封未閱讀而且有附件的最新電子郵件。然後,進行呼叫以取得這些附件中每一個的內容。此時,它已經具有所有的電子郵件和附件的內容,並儲存在可於檢視中顯示的陣列內。 66 | 67 | 其他包含在 *mainController.js* 內的功能,包括將電子郵件標示為已閱讀和傳送回應。 68 | 69 | ### 限制 70 | 71 | 目前的版本不包含下列功能。 72 | 73 | * .png 和 .jpg 以外的檔案支援 74 | * 處理有多個附件的單一電子郵件 75 | * 分頁 (取得 50 封以上的電子郵件) 76 | * 處理資料夾名稱的唯一性 77 | * 提交資料夾必須是最上層的資料夾 78 | 79 | ## 安全性注意事項 80 | [ADAL JS](https://github.com/AzureAD/azure-activedirectory-library-for-js) 並不會驗證從 Azure AD 所收到的權杖。它依賴應用程式的後端來進行驗證,且在您您呼叫後端之前,都不會知道使用者是否已取得可接受的權杖。基於安全理由,商務應用程式應在 Web 應用程式中,內建供使用者驗證用的伺服器端元件。若沒有這個後端權杖驗證,您的應用程式會受到安全性攻擊,例如[「混淆代理問題」](https://en.wikipedia.org/wiki/Confused_deputy_problem)。看看此[部落格文章](http://www.cloudidentity.com/blog/2015/02/19/introducing-adal-js-v1/)以獲得更多資訊。 81 | 82 | 83 | ## 問題和建議 84 | 85 | - 如果執行此範例有任何問題,請[開立問題](https://github.com/OfficeDev/O365-Angular-ArtCurator/issues)。 86 | - 若您對於 Office 365 API 有任何疑問,請張貼到 [[堆疊溢位]](http://stackoverflow.com/)。請務必以 [Office365] 標記您的問題和建議。 87 | 88 | 89 | ## 其他資源 90 | 91 | * [使用 Office 365 API 來建立 Angular 應用程式](http://aka.ms/get-started-with-js) 92 | * [Office 365 API 平台概觀](http://msdn.microsoft.com/office/office365/howto/platform-development-overview) 93 | * [Office 開發人員中心](http://dev.office.com/) 94 | * [適用於 iOS 的 Art Curator](https://github.com/OfficeDev/O365-iOS-ArtCurator) 95 | * [適用於 Android 的 Art Curator](https://github.com/OfficeDev/O365-Android-ArtCurator) 96 | * [適用於 Windows Phone 的 Art Curator](https://github.com/OfficeDev/O365-WinPhone-ArtCurator) 97 | 98 | ## 著作權 99 | Copyright (c) 2015 Microsoft.著作權所有,並保留一切權利。 100 | 101 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [ARCHIVED] Art Curator for Angular 2 | 3 | **Note:** This repo is archived and no longer actively maintained. Security vulnerabilities may exist in the project, or its dependencies. If you plan to reuse or run any code from this repo, be sure to perform appropriate security checks on the code or dependencies first. Do not use this project as the starting point of a production Office Add-in. Always start your production code by using the Office/SharePoint development workload in Visual Studio, or the [Yeoman generator for Office Add-ins](https://github.com/OfficeDev/generator-office), and follow security best practices as you develop the add-in. 4 | 5 | This sample demonstrates how to use the Outlook Mail API to get emails and attachments from Office 365. It's built for [iOS](https://github.com/OfficeDev/O365-iOS-ArtCurator), [Android](https://github.com/OfficeDev/O365-Android-ArtCurator), Web (Angular web app), and [Windows Phone](https://github.com/OfficeDev/O365-WinPhone-ArtCurator). Check out our [article on Medium](https://medium.com/office-app-development) and this [walkthrough video on YouTube](https://www.youtube.com/watch?v=M88A6VB9IIw&feature=youtu.be). 6 | 7 | Art Curator is a different way to view your inbox. Imagine you own a company that sells artistic t-shirts. As the owner of the company, you receive lots of emails from artists with designs they want you to buy. Instead of using Outlook and opening every individual email, downloading the attached picture, and then opening it to view, you can use Art Curator to give you an attachment-first (limited to .jpg and .png files) view of your inbox to pick and choose designs you like in a more efficient way. 8 | 9 | [![Art Curator Screenshot](./README Assets/AC_Angular.png)](https://youtu.be/4LOvkweDfhY "Click to see the sample in action.") 10 | 11 | This sample demonstrates the following operations from the **Outlook Mail API**: 12 | * [Get folders](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#GetFolders) 13 | * [Get messages](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#Getmessages) (including filtering and using select) 14 | * [Get attachments](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#GetAttachments) 15 | * [Update messages](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#Updatemessages) 16 | * [Create and send messages](https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#Sendmessages) (with and without an attachment) 17 | 18 | This sample also demonstrates authentication with Azure Active Directory using [Active Directory Authentication Library (ADAL) for JavaScript](https://github.com/AzureAD/azure-activedirectory-library-for-js). 19 | 20 | 21 | ## Prerequisites 22 | 23 | This sample requires the following: 24 | * [Node.js](https://nodejs.org/). Node is required to run the sample on a development server and to install dependencies. 25 | * An Office 365 account. You can sign up for [an Office 365 Developer subscription](http://aka.ms/ro9c62) that includes the resources that you need to start building Office 365 apps. 26 | 27 | 28 | ## Register the app 29 | 30 | 1. To get this sample up and running quickly, go to the [Outlook Dev Portal App Registration Tool](https://dev.outlook.com/appregistration). 31 | 2. In **Step 1**, sign in with your existing Office 365 account or click the button to get a free trial. After you sign in, proceed to the next step. 32 | 3. In **Step 2**, fill out the form with the following values. 33 | * *App Name:* Art Curator 34 | * *App Type:* Single-Page app (SPA) 35 | * *Redirect URI:* http://127.0.0.1:8080/ 36 | * *Home Page URL:* http://artcurator.{your_subdomain}.com (the subdomain of .onmicrosoft of your Office 365 tenant) 37 | 4. In **Step 3**, select the following permissions underneath **Mail API**. 38 | * *Read and write mail* 39 | * *Send mail* 40 | 5. In **Step 4**, click **Register App** to register your application with Azure Active Directory. 41 | 6. Finally, copy the **Client ID** from the form to use in the next section. 42 | 43 | 44 | ## Run the app 45 | 46 | Open *app/scripts/app.js* and replace *{your_tenant}* with the subdomain of .onmicrosoft you specified for your Office 365 tenant and the client ID of your registered Azure application that you received from the Outlook Dev Portal App Registration Tool in the last step on lines 46 and 47, respectively. 47 | 48 | Next, install the necessary dependencies and run the project via the command line. Begin by opening a command prompt and navigating to the root folder. Once there, follow the steps below. 49 | 50 | 1. Install project dependencies by running ```npm install```. 51 | 2. Now that all the project dependencies are installed, start the development server by running ```node server.js``` in the root folder. 52 | 3. Navigate to ```http://127.0.0.1:8080/``` in your web browser. 53 | 54 | 55 | ## Understand the code 56 | 57 | ### Connect to Office 365 58 | 59 | This project uses [Azure Active Directory using Azure Active Directory Library (ADAL) for JavaScript](https://github.com/AzureAD/azure-activedirectory-library-for-js) to authenticate with Azure Active Directory in order to request and receive tokens for using the Office 365 APIs. 60 | 61 | The service is configured in *app/app.js* in the module's config function. In *app/controllers/navBarController.js*, there are two functions that handle logging in and out of Azure Active Directory which handles acquiring tokens as well. 62 | 63 | ### Mail API 64 | 65 | This project uses standard REST calls to interact with the Mail API. Refer to the [Outlook Mail REST API reference](https://msdn.microsoft.com/en-us/office/office365/api/mail-rest-operations) for details on the available endpoints. 66 | 67 | All of the Mail API functionality lives in *app/controllers/mainController.js*. First, it gets all of the folders available on the user's tenant and uses the stored value in *localStorage* to find the target folder. After that, it gets the 50 most recent emails that are unread and have attachments. Then, calls are made to get the content of each of those attachments. At this point, it has all of the emails and contents of the attachments and they are stored in an array that is made available to the view for display. 68 | 69 | Other functionality included in *mainController.js* includes marking emails as read and creating and sending responses. 70 | 71 | ### Limitations 72 | 73 | The following features are not included in the current version. 74 | 75 | * File support beyond .png and .jpg 76 | * Handling a single email with multiple attachments 77 | * Paging (getting more than 50 emails) 78 | * Handling folder name uniqueness 79 | * Submission folder must be a top-level folder 80 | 81 | ## Security notice 82 | [ADAL JS](https://github.com/AzureAD/azure-activedirectory-library-for-js) does not validate the token received from Azure AD. It relies on the app’s backend to do so, and until you call the backend, you don’t know if the user obtained an acceptable token. Business applications should have a server-side component for user authentication built into the web application for security reasons. Without this backend token validation, your app is susceptible to security attacks such as the [confused deputy problem](https://en.wikipedia.org/wiki/Confused_deputy_problem). Check out this [blog post](http://www.cloudidentity.com/blog/2015/02/19/introducing-adal-js-v1/) for more information. 83 | 84 | 85 | ## Questions and comments 86 | 87 | - If you have any trouble running this sample, please [log an issue](https://github.com/OfficeDev/O365-Angular-ArtCurator/issues). 88 | - For general questions about the Office 365 APIs, post to [Stack Overflow](http://stackoverflow.com/). Make sure that your questions or comments are tagged with [office365]. 89 | 90 | 91 | ## Additional resources 92 | 93 | * [Create an Angular app with Office 365 APIs](http://aka.ms/get-started-with-js) 94 | * [Office 365 APIs platform overview](http://msdn.microsoft.com/office/office365/howto/platform-development-overview) 95 | * [Office Dev Center](http://dev.office.com/) 96 | * [Art Curator for iOS](https://github.com/OfficeDev/O365-iOS-ArtCurator) 97 | * [Art Curator for Android](https://github.com/OfficeDev/O365-Android-ArtCurator) 98 | * [Art Curator for Windows Phone](https://github.com/OfficeDev/O365-WinPhone-ArtCurator) 99 | 100 | ## Copyright 101 | Copyright (c) 2015 Microsoft. All rights reserved. 102 | 103 | 104 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information, see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. 105 | -------------------------------------------------------------------------------- /app/assets/Aero.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OfficeDev/O365-Angular-ArtCurator/f2feca00a0ea67fa430d06487987ff43950d4b65/app/assets/Aero.png -------------------------------------------------------------------------------- /app/assets/Bird-art.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OfficeDev/O365-Angular-ArtCurator/f2feca00a0ea67fa430d06487987ff43950d4b65/app/assets/Bird-art.png -------------------------------------------------------------------------------- /app/assets/Facial.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OfficeDev/O365-Angular-ArtCurator/f2feca00a0ea67fa430d06487987ff43950d4b65/app/assets/Facial.png -------------------------------------------------------------------------------- /app/assets/Fearther-art.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OfficeDev/O365-Angular-ArtCurator/f2feca00a0ea67fa430d06487987ff43950d4b65/app/assets/Fearther-art.png -------------------------------------------------------------------------------- /app/assets/Leakage.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OfficeDev/O365-Angular-ArtCurator/f2feca00a0ea67fa430d06487987ff43950d4b65/app/assets/Leakage.png -------------------------------------------------------------------------------- /app/assets/MS Robot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OfficeDev/O365-Angular-ArtCurator/f2feca00a0ea67fa430d06487987ff43950d4b65/app/assets/MS Robot.png -------------------------------------------------------------------------------- /app/assets/Mountain-art.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OfficeDev/O365-Angular-ArtCurator/f2feca00a0ea67fa430d06487987ff43950d4b65/app/assets/Mountain-art.png -------------------------------------------------------------------------------- /app/assets/Win.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OfficeDev/O365-Angular-ArtCurator/f2feca00a0ea67fa430d06487987ff43950d4b65/app/assets/Win.png -------------------------------------------------------------------------------- /app/assets/guitar-art.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OfficeDev/O365-Angular-ArtCurator/f2feca00a0ea67fa430d06487987ff43950d4b65/app/assets/guitar-art.png -------------------------------------------------------------------------------- /app/controllers/mainController.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file. 3 | */ 4 | 5 | (function () { 6 | angular 7 | .module('artCuratorApp') 8 | .controller('MainController', MainController) 9 | .controller('ModalInstanceController', ModalInstanceController) 10 | .filter('MyShortFilter', MyShortFilter); 11 | 12 | // Inject dependencies to protect app from minification. 13 | MainController.$inject = ['$http', 'localStorageService', '$q', '$modal', 'adalAuthenticationService']; 14 | ModalInstanceController.$inject = ['$scope', '$modalInstance', 'selectedEmail', 'emailAction', '$q']; 15 | MyShortFilter.$inject = ['$filter']; 16 | 17 | /** 18 | * The code for MainController. Does heavy lifting for the application and makes the calls to the Office 365 API. 19 | */ 20 | function MainController($http, localStorageService, $q, $modal, adalService) { 21 | var vm = this; 22 | vm.emails = null; 23 | vm.hasEmailsWithAttachments = false; 24 | 25 | /** 26 | * Checks for ContentType of attachment is supported. 27 | */ 28 | var isSupportedContentType = function (contentType) { 29 | // List of support content types. Basic images right now. 30 | var supportedContentTypes = ['image/jpg', 'image/jpeg', 'image/png']; 31 | 32 | for (var i = 0; i < supportedContentTypes.length; i++) { 33 | if (supportedContentTypes[i] == contentType) { 34 | vm.hasEmailsWithAttachments = true; 35 | return true; 36 | } 37 | } 38 | 39 | // If code gets here, means that contentType is not supported. 40 | return false; 41 | } 42 | 43 | /** 44 | * 1. Gets folders from Exchange. 45 | * 2. If target folder is found, get emails in it. If not, show error. 46 | * 3. Get attachments from emails. If valid content type, construct data URi. If not, ignore. 47 | */ 48 | if (adalService.userInfo.isAuthenticated) { 49 | $http.get('https://outlook.office365.com/api/v1.0/me/folders') 50 | .then(function (response) { 51 | console.log('Got folders from Exchange...'); 52 | var folders = response.data.value; 53 | 54 | var targetFolderName = localStorageService.get('targetFolder' + adalService.userInfo.userName); 55 | var targetFolder = null; 56 | 57 | // Iterate over returned olders until target folder is found. 58 | folders.some(function (folder) { 59 | if (folder.DisplayName == targetFolderName) { 60 | targetFolder = folder; 61 | return true; 62 | } 63 | }); 64 | 65 | // Get messages from targetFolder, if found. 66 | if (targetFolder == null) { 67 | vm.folderError = true; 68 | } else { 69 | // Get the 50 most recent, unread emails that have attachments from target folder. 70 | $http.get('https://outlook.office365.com/api/v1.0/me/folders/' + targetFolder.Id + '/messages?$filter=HasAttachments eq true AND IsRead eq false&$top=50&$orderby=HasAttachments,DateTimeReceived desc') 71 | .then(function (response) { 72 | console.log('Got messages from ' + targetFolder.DisplayName + ' folder.'); 73 | vm.emails = response.data.value; 74 | 75 | // Show error message if no emails were returned from query. 76 | if (vm.emails.length == 0) { 77 | vm.messagesError = true; 78 | } else { 79 | // Add HTTP requests to a promises array so further execution is halted until all complete. 80 | var promises = []; 81 | 82 | //$http.defaults.headers.common.Accept = 'text/plain'; 83 | // Get attachments of each returned message. 84 | vm.emails.some(function (email) { 85 | promises.push( 86 | $http.get('https://outlook.office365.com/api/v1.0/me/messages/' + email.Id + '/attachments?$select=ContentType') 87 | .then(function (response) { 88 | // Check content type of attachment to see if it's supported (list in isSupportedContentType). 89 | if (!isSupportedContentType(response.data.value[0].ContentType)) { 90 | console.log('An email with an unsupported content type was ignored.'); 91 | removeById(email.Id); 92 | } else { 93 | console.log("Getting attachment for email with subject: " + email.Subject); 94 | 95 | promises.push( 96 | // An email with and attachment with a valid ContentType has been found, get it. 97 | $http.get('https://outlook.office365.com/api/v1.0/me/messages/' + email.Id + '/attachments/' + response.data.value[0].Id) 98 | .then(function (response) { 99 | var imageUrl = "data:" + response.data.ContentType + ";base64," + response.data.ContentBytes; 100 | email.AttachmentSrc = imageUrl; 101 | email.AttachmentName = response.data.Name; 102 | email.DateTimeReceived = new Date(email.DateTimeReceived); 103 | }, function (error) { 104 | console.log('Failed to download attachment.', error); 105 | }) 106 | ); 107 | } 108 | }, function (error) { 109 | console.log('Failed to get attachment for ' + email.Subject + ' email.', error); 110 | }) 111 | ); 112 | }); 113 | 114 | // Wait for all HTTP requests to complete until taking further action. 115 | $q.all(promises) 116 | .then(function (response) { 117 | console.log('Processed all emails.'); 118 | 119 | if (!vm.hasEmailsWithAttachments) { 120 | console.log('No new submissions in this folder.'); 121 | vm.messagesError = true; 122 | } 123 | }); 124 | } 125 | }, function (error) { 126 | console.log('Failed to get messages from ' + targetFolder.DisplayName + ' folder.', error); 127 | }); 128 | }; 129 | }, function (error) { 130 | console.log('Failed to get folders from Exchange.', error); 131 | }); 132 | }; 133 | 134 | /** 135 | * Function to take action on the email that a user selects. 136 | */ 137 | var emailAction = function (type, email) { 138 | var info; 139 | var markAsRead; 140 | var respond; 141 | var response; 142 | 143 | // Determine which action was requested and fetch settings based on that. 144 | if (type == 'like') { 145 | info = 'Performing like actions...'; 146 | markAsRead = localStorageService.get('likeMarkAsRead' + adalService.userInfo.userName); 147 | respond = localStorageService.get('likeRespond' + adalService.userInfo.userName); 148 | response = localStorageService.get('likeResponse' + adalService.userInfo.userName); 149 | } else if (type == 'dislike') { 150 | info = 'Performing dislike actions...'; 151 | markAsRead = localStorageService.get('dislikeMarkAsRead' + adalService.userInfo.userName); 152 | respond = localStorageService.get('dislikeRespond' + adalService.userInfo.userName); 153 | response = localStorageService.get('dislikeResponse' + adalService.userInfo.userName); 154 | } 155 | 156 | // Add HTTP requests to a promises array so further execution is halted until all complete. 157 | var promises = []; 158 | 159 | // Mark email as read if setting calls for it. 160 | if (markAsRead == true || markAsRead == 'true') { 161 | var markRequest = { 162 | method: 'PATCH', 163 | url: 'https://outlook.office365.com/api/v1.0/me/messages/' + email.Id, 164 | data: { 165 | "IsRead": true 166 | } 167 | }; 168 | 169 | promises.push( 170 | $http(markRequest) 171 | .then(function (response) { 172 | console.log('Marked email as read.'); 173 | removeById(email.Id); 174 | }, function (error) { 175 | console.log('Unable to mark message as read. Check app permissions.', error); 176 | }) 177 | ); 178 | } 179 | 180 | // Respond to the email if setting calls for it. 181 | if (respond == true || respond == 'true') { 182 | var respondRequest = { 183 | method: 'POST', 184 | url: 'https://outlook.office365.com/api/v1.0/me/sendmail', 185 | data: { 186 | 'Message': { 187 | 'Subject': 'RE: ' + email.Subject, 188 | 'Body': { 189 | 'ContentType': 'Text', 190 | 'Content': response 191 | }, 192 | 'ToRecipients': [{ 193 | 'EmailAddress': { 194 | 'Address': email.Sender.EmailAddress.Address 195 | } 196 | }] 197 | }, 198 | 'SaveToSentItems': 'true' 199 | } 200 | }; 201 | 202 | promises.push( 203 | $http(respondRequest) 204 | .then(function (response) { 205 | console.log('Responded to email.'); 206 | }, function (error) { 207 | console.log('Unable to send response. Check app permissions.', error); 208 | }) 209 | ); 210 | } 211 | 212 | return promises; 213 | }; 214 | 215 | /** 216 | * Function to remove an email from the collection of emails by its ID. 217 | */ 218 | var removeById = function (id) { 219 | for (var i = 0; i < vm.emails.length; i++) { 220 | if (vm.emails[i].Id == id) { 221 | vm.emails.splice(i, 1); 222 | break; 223 | } 224 | } 225 | 226 | if (vm.emails.length == 0) { 227 | console.log('No more submissions left in folder.'); 228 | vm.messagesError = true; 229 | } 230 | }; 231 | 232 | /** 233 | * Click handler for when a user clicks on an attachment to bring up the details modal. 234 | */ 235 | vm.open = function (size, selectedEmail) { 236 | var modalInstance = $modal.open({ 237 | animation: true, 238 | templateUrl: 'myModalContent.html', 239 | controller: 'ModalInstanceController', 240 | controllerAs: 'modal', 241 | size: size, 242 | resolve: { 243 | selectedEmail: function () { 244 | return selectedEmail; 245 | }, 246 | emailAction: function () { 247 | return emailAction; 248 | } 249 | } 250 | }); 251 | 252 | modalInstance.result.then(function () { }, function () { 253 | console.log('User took no action on the selected email.'); 254 | }); 255 | }; 256 | 257 | /** 258 | * Function to send three emails with a supported ContentType to the user's inbox. 259 | */ 260 | vm.populateInboxWithArt = function () { 261 | var stockImages = [ 262 | 'Aero.png', 263 | 'Bird-art.png', 264 | 'Facial.png', 265 | 'Fearther-art.png', 266 | 'guitar-art.png', 267 | 'Leakage.png', 268 | 'MS Robot.png', 269 | 'Mountain-art.png', 270 | 'Win.png', 271 | ]; 272 | 273 | // Add HTTP requests to a promises array so further execution is halted until all complete. 274 | var promises = []; 275 | for (var i = 0; i < stockImages.length; i++) { 276 | promises.push(sendStockImageEmail(stockImages[i])); 277 | }; 278 | 279 | // After all emails are sent, inform the user. 280 | $q.all(promises).then(function () { 281 | vm.emailsSentMessage = stockImages.length + ' new submissions have been sent to Inbox. Refresh the page when you receive them and move them to your target folder.'; 282 | }); 283 | }; 284 | 285 | /** 286 | * Function to convert a local image file to a base 64 encoded string to send via email. 287 | */ 288 | var getContentBytes = function (fileName) { 289 | return $q(function (resolve, reject) { 290 | // Construct file path. 291 | fileName = '../../assets/' + fileName; 292 | 293 | // Construct HTTP request. 294 | var request = { 295 | url: fileName, 296 | method: 'GET', 297 | responseType: 'blob' 298 | }; 299 | 300 | // Fire HTTP request and read resulting file as a binary string. 301 | $http(request) 302 | .then(function (response) { 303 | var reader = new FileReader(); 304 | 305 | // After reader reads the file, encode it to base 64. 306 | reader.onload = function (readFile) { 307 | var binaryString = readFile.target.result; 308 | resolve(btoa(binaryString)); 309 | }; 310 | 311 | reader.readAsBinaryString(response.data); 312 | }, function (error) { 313 | reject('Unable to read image file.', error); 314 | }); 315 | }); 316 | }; 317 | 318 | /** 319 | * Function to send an email with an attachment to the signed in user to populate Inbox. 320 | */ 321 | var sendStockImageEmail = function (fileName) { 322 | return $q(function (resolve, reject) { 323 | // Get base 64 encoded string of an image, then send it. 324 | getContentBytes(fileName).then(function (contentBytes) { 325 | // Construct HTTP request. 326 | var request = { 327 | method: 'POST', 328 | url: 'https://outlook.office365.com/api/v1.0/me/sendmail', 329 | data: { 330 | 'Message': { 331 | 'Subject': fileName, 332 | 'Body': { 333 | 'ContentType': 'Text', 334 | 'Content': 'Check out ' + fileName + '!' 335 | }, 336 | 'ToRecipients': [{ 337 | 'EmailAddress': { 338 | 'Address': adalService.userInfo.userName 339 | } 340 | }], 341 | "Attachments": [{ 342 | "@odata.type": '#Microsoft.OutlookServices.FileAttachment', 343 | "Name": fileName, 344 | "ContentBytes": contentBytes, 345 | "ContentType": 'image/png' 346 | }], 347 | }, 348 | 'SaveToSentItems': 'true' 349 | } 350 | }; 351 | 352 | // Fire HTTP request to send an email to the signed in user with an attachment. 353 | $http(request) 354 | .then(function (response) { 355 | console.log('Sent ' + fileName + ' to Inbox.'); 356 | resolve(); 357 | }, function (error) { 358 | console.log('Unable to send email. Check app permissions.'); 359 | reject(); 360 | }); 361 | }); 362 | }); 363 | }; 364 | }; 365 | 366 | /** 367 | * Controller for the modal that opens when a user clicks on an email. 368 | */ 369 | function ModalInstanceController($scope, $modalInstance, selectedEmail, emailAction, $q) { 370 | var vm = this; 371 | vm.email = selectedEmail; 372 | 373 | // Click handler for the like button on the emails detail modal. 374 | vm.like = function () { 375 | console.log('User clicked like.'); 376 | $q.all(emailAction('like', selectedEmail)).then(function () { 377 | $modalInstance.close(); 378 | }); 379 | }; 380 | 381 | // Click handler for the dislike button on the emails detail modal. 382 | vm.dislike = function () { 383 | console.log('User clicked dislike.'); 384 | $q.all(emailAction('dislike', selectedEmail)).then(function () { 385 | $modalInstance.close(); 386 | }); 387 | }; 388 | }; 389 | 390 | /** 391 | * Customer filter to display time in the format we want (mirrors Outlook). 392 | */ 393 | function MyShortFilter($filter) { 394 | return function (text) { 395 | var dateObject = new Date(text); 396 | return $filter('date')(dateObject, "EEEE M/d/yyyy h:mm a"); 397 | } 398 | }; 399 | })(); 400 | 401 | // ********************************************************* 402 | // 403 | // O365-Angular-ArtCurator, https://github.com/OfficeDev/O365-Angular-ArtCurator 404 | // 405 | // Copyright (c) Microsoft Corporation 406 | // All rights reserved. 407 | // 408 | // MIT License: 409 | // Permission is hereby granted, free of charge, to any person obtaining 410 | // a copy of this software and associated documentation files (the 411 | // "Software"), to deal in the Software without restriction, including 412 | // without limitation the rights to use, copy, modify, merge, publish, 413 | // distribute, sublicense, and/or sell copies of the Software, and to 414 | // permit persons to whom the Software is furnished to do so, subject to 415 | // the following conditions: 416 | // 417 | // The above copyright notice and this permission notice shall be 418 | // included in all copies or substantial portions of the Software. 419 | // 420 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 421 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 422 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 423 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 424 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 425 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 426 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 427 | // 428 | // ********************************************************* -------------------------------------------------------------------------------- /app/controllers/navBarController.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file. 3 | */ 4 | 5 | (function () { 6 | angular 7 | .module('artCuratorApp') 8 | .controller('NavbarController', NavbarController); 9 | 10 | // Inject dependencies to protect app from minification. 11 | NavbarController.$inject = ['adalAuthenticationService', 'localStorageService']; 12 | 13 | /** 14 | * The code for NavbarController. Basically handles nav bar tasks + default settings. 15 | */ 16 | function NavbarController(adalService, localStorageService) { 17 | var vm = this; 18 | 19 | // Properties 20 | vm.isCollapsed; 21 | 22 | // Does initialization work for the navbar. 23 | var activate = function () { 24 | vm.isCollapsed = true; 25 | isSettingsSet(); 26 | }; 27 | 28 | // Click handler for the "Connect" option on the navigation bar. 29 | vm.login = function () { 30 | adalService.login(); 31 | }; 32 | 33 | // Click handler for the "Disconnect" option on the navigation bar. 34 | vm.logout = function () { 35 | adalService.logOut(); 36 | }; 37 | 38 | // Checks if app needs default settings. 39 | var isSettingsSet = function () { 40 | var value = localStorageService.get('targetFolder' + adalService.userInfo.userName); 41 | 42 | // If setting wasn't available, set all default settings. 43 | if (value == null) { 44 | setDefaultSettings(); 45 | } 46 | }; 47 | 48 | // Sets default settings for app. 49 | var setDefaultSettings = function () { 50 | var defaults = [ 51 | ['targetFolder', 'Inbox'], 52 | ['likeMarkAsRead', true], 53 | ['likeRespond', true], 54 | ['likeResponse', "Excellent submission. Please email me at your convenience to discuss a sale."], 55 | ['dislikeMarkAsRead', true], 56 | ['dislikeRespond', true], 57 | ['dislikeResponse', "This submission isn't what I'm looking for. Thank you anyway."] 58 | ]; 59 | 60 | // Iterate over settings options, append the signed in username, and set a default setting. 61 | defaults.forEach(function (setting) { 62 | var result = localStorageService.set(setting[0] + adalService.userInfo.userName, setting[1]); 63 | if (!result) { 64 | console.log('Error setting: ', setting[0]); 65 | } 66 | }) 67 | }; 68 | 69 | // Initialize controller. 70 | activate(); 71 | }; 72 | })(); 73 | 74 | // ********************************************************* 75 | // 76 | // O365-Angular-ArtCurator, https://github.com/OfficeDev/O365-Angular-ArtCurator 77 | // 78 | // Copyright (c) Microsoft Corporation 79 | // All rights reserved. 80 | // 81 | // MIT License: 82 | // Permission is hereby granted, free of charge, to any person obtaining 83 | // a copy of this software and associated documentation files (the 84 | // "Software"), to deal in the Software without restriction, including 85 | // without limitation the rights to use, copy, modify, merge, publish, 86 | // distribute, sublicense, and/or sell copies of the Software, and to 87 | // permit persons to whom the Software is furnished to do so, subject to 88 | // the following conditions: 89 | // 90 | // The above copyright notice and this permission notice shall be 91 | // included in all copies or substantial portions of the Software. 92 | // 93 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 94 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 95 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 96 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 97 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 98 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 99 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 100 | // 101 | // ********************************************************* -------------------------------------------------------------------------------- /app/controllers/settingsController.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file. 3 | */ 4 | 5 | (function () { 6 | angular 7 | .module('artCuratorApp') 8 | .controller('SettingsController', SettingsController); 9 | 10 | // Inject dependencies to protect app from minification. 11 | SettingsController.$inject = ['localStorageService', 'adalAuthenticationService', '$location']; 12 | 13 | /** 14 | * The code for SettingsController. Handles the form logic for settings.html. 15 | */ 16 | function SettingsController(localStorageService, adalService, $location) { 17 | var vm = this; 18 | 19 | // If user logs out while on the settings page, this will make sure they get sent back to the root. 20 | if (!adalService.userInfo.isAuthenticated) { 21 | $location.path('/'); 22 | } 23 | 24 | var settingsKeys = ['targetFolder', 'likeMarkAsRead', 'likeRespond', 'likeResponse', 'dislikeMarkAsRead', 'dislikeRespond', 'dislikeResponse']; 25 | vm.settingsValues = {}; 26 | 27 | // Get values from localStorage for all settings. 28 | settingsKeys.forEach(function (key) { 29 | vm.settingsValues[key] = localStorageService.get(key + adalService.userInfo.userName); 30 | 31 | if (key != 'targetFolder' && key != 'likeResponse' && key != 'dislikeResponse') { 32 | vm.settingsValues[key] = localStorageService.get(key + adalService.userInfo.userName) == 'true' || localStorageService.get(key + adalService.userInfo.userName) == true; 33 | } 34 | }); 35 | 36 | vm.signedInUser = adalService.userInfo.userName; 37 | 38 | /** 39 | * Save settings on click and redirect to the main page. 40 | */ 41 | vm.saveSettings = function () { 42 | settingsKeys.forEach(function (key) { 43 | var result = localStorageService.set(key + adalService.userInfo.userName, vm.settingsValues[key]); 44 | 45 | if (!result) { 46 | console.log('Error saving :', key); 47 | vm.error = true; 48 | } 49 | }); 50 | 51 | $location.path('/'); 52 | }; 53 | 54 | /** 55 | * Log out the user and redirect to the root page. 56 | */ 57 | vm.logOut = function () { 58 | adalService.logOut(); 59 | $location.path('/'); 60 | }; 61 | }; 62 | })(); 63 | 64 | // ********************************************************* 65 | // 66 | // O365-Angular-ArtCurator, https://github.com/OfficeDev/O365-Angular-ArtCurator 67 | // 68 | // Copyright (c) Microsoft Corporation 69 | // All rights reserved. 70 | // 71 | // MIT License: 72 | // Permission is hereby granted, free of charge, to any person obtaining 73 | // a copy of this software and associated documentation files (the 74 | // "Software"), to deal in the Software without restriction, including 75 | // without limitation the rights to use, copy, modify, merge, publish, 76 | // distribute, sublicense, and/or sell copies of the Software, and to 77 | // permit persons to whom the Software is furnished to do so, subject to 78 | // the following conditions: 79 | // 80 | // The above copyright notice and this permission notice shall be 81 | // included in all copies or substantial portions of the Software. 82 | // 83 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 84 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 85 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 86 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 87 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 88 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 89 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 90 | // 91 | // ********************************************************* -------------------------------------------------------------------------------- /app/index.html: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Art Curator 10 | 11 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 64 |
65 |
66 |
67 |
68 |
69 | 70 | 71 | 72 | 82 | -------------------------------------------------------------------------------- /app/scripts/app.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file. 3 | */ 4 | 5 | (function () { 6 | angular 7 | .module('artCuratorApp', [ 8 | 'ngRoute', 9 | 'AdalAngular', 10 | 'LocalStorageModule', 11 | 'ui.bootstrap', 12 | 'angular-loading-bar' 13 | ]) 14 | 15 | .config(['$routeProvider', '$httpProvider', 'adalAuthenticationServiceProvider', 'localStorageServiceProvider', 'cfpLoadingBarProvider', '$locationProvider', config]); 16 | 17 | function config($routeProvider, $httpProvider, adalProvider, localStorageServiceProvider, cfpLoadingBarProvider, $locationProvider) { 18 | 19 | // Configure the routes. 20 | $routeProvider 21 | .when('/', { 22 | templateUrl: 'views/main.html', 23 | controller: 'MainController', 24 | controllerAs: 'main' 25 | }) 26 | .when('/settings', { 27 | templateUrl: 'views/settings.html', 28 | controller: 'SettingsController', 29 | controllerAs: 'settings' 30 | }) 31 | .otherwise({ 32 | redirectTo: '/' 33 | }); 34 | 35 | // Remove the '#' from the URL. 36 | $locationProvider.html5Mode(true).hashPrefix('!'); 37 | 38 | // Allow cross domain requests to be made. 39 | $httpProvider.defaults.useXDomain = true; 40 | delete $httpProvider.defaults.headers.common['X-Requested-With']; 41 | 42 | // Initialize ADAL JS to handle authentication. 43 | // See https://github.com/AzureAD/azure-activedirectory-library-for-js for details. 44 | adalProvider.init( 45 | { 46 | tenant: '{your_tenant}.onmicrosoft.com', 47 | clientId: 'XXXXXXXXXXXXXXXXXXXXXXXX', 48 | endpoints: { 49 | 'https://outlook.office365.com': 'https://outlook.office365.com', 50 | }, 51 | cacheLocation: 'localStorage' // Enable this for IE, as sessionStorage does not work for localhost. 52 | }, 53 | $httpProvider 54 | ); 55 | 56 | // Local storage configuration. 57 | localStorageServiceProvider 58 | .setPrefix('artCurator'); 59 | 60 | // Remove spinner from loading bar. 61 | cfpLoadingBarProvider.includeSpinner = false; 62 | }; 63 | })(); 64 | 65 | // ********************************************************* 66 | // 67 | // O365-Angular-ArtCurator, https://github.com/OfficeDev/O365-Angular-ArtCurator 68 | // 69 | // Copyright (c) Microsoft Corporation 70 | // All rights reserved. 71 | // 72 | // MIT License: 73 | // Permission is hereby granted, free of charge, to any person obtaining 74 | // a copy of this software and associated documentation files (the 75 | // "Software"), to deal in the Software without restriction, including 76 | // without limitation the rights to use, copy, modify, merge, publish, 77 | // distribute, sublicense, and/or sell copies of the Software, and to 78 | // permit persons to whom the Software is furnished to do so, subject to 79 | // the following conditions: 80 | // 81 | // The above copyright notice and this permission notice shall be 82 | // included in all copies or substantial portions of the Software. 83 | // 84 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 85 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 86 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 87 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 88 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 89 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 90 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 91 | // 92 | // ********************************************************* 93 | 94 | -------------------------------------------------------------------------------- /app/styles.css: -------------------------------------------------------------------------------- 1 | .modal { 2 | overflow-y: auto; 3 | } 4 | 5 | .modal-open { 6 | overflow:auto; 7 | overflow-x:hidden; 8 | margin-right: auto !important; 9 | } 10 | 11 | .img-responsive { 12 | margin-left: auto; 13 | margin-right: auto; 14 | } 15 | 16 | .modal-footer { 17 | text-align: center; 18 | } 19 | 20 | .modal-button { 21 | width: 100px; 22 | } -------------------------------------------------------------------------------- /app/views/main.html: -------------------------------------------------------------------------------- 1 | 3 |
4 | 5 |
6 |

Welcome to Art Curator! Connect to Office 365 with the button on the navigation bar so we can start fetching new art from 7 | your inbox.

8 |
9 |
10 | 11 |
12 |

Folder not found.

13 |
14 |

No new submissions found.

15 | 16 |
{{main.emailsSentMessage}}
17 |
18 |
19 | 20 |
21 |
22 | 23 |
24 |
25 |
26 |
27 | 43 |
44 |
45 |
46 | -------------------------------------------------------------------------------- /app/views/settings.html: -------------------------------------------------------------------------------- 1 | 3 | 4 |
5 |
6 |
7 |
8 | 13 | 14 |
15 |
16 |

Like actions 17 | What do we do when you want it? 18 | 19 |

20 |
21 | 25 |
26 |
27 |
28 | 32 |
33 | 34 |
35 |
36 |
37 |

Dislike actions 38 | What do we do when you don't want it? 39 | 40 |

41 |
42 | 46 |
47 |
48 |
49 | 53 |
54 | 55 |
56 |
57 | 58 | 59 |
60 |
61 |
62 |

Account

63 |
{{settings.signedInUser}}
64 | 65 |
66 |
67 |
68 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "art-curator", 3 | "version": "1.0.0", 4 | "license": "MIT", 5 | "main": "server.js", 6 | "dependencies": { 7 | "express": "^4.12.3", 8 | "morgan": "^1.5.2", 9 | "path": "^0.11.14" 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /server.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file. 3 | */ 4 | 5 | var express = require('express'); 6 | var app = express(); 7 | var morgan = require('morgan'); 8 | var path = require('path'); 9 | 10 | // Initialize variables. 11 | var port = process.env.PORT || 8080; 12 | 13 | // Configure morgan module to log all requests. 14 | app.use(morgan('dev')); 15 | 16 | // Set the app folder to serve public assets. 17 | app.use(express.static(__dirname + '/app')); 18 | 19 | // Set up our one route to the index.html file. 20 | app.get('*', function (req, res) { 21 | res.sendFile(path.join(__dirname + '/app/index.html')); 22 | }); 23 | 24 | // Start the app. 25 | app.listen(port); 26 | console.log('Listening on port ' + port + '...'); 27 | 28 | // ********************************************************* 29 | // 30 | // O365-Angular-ArtCurator, https://github.com/OfficeDev/O365-Angular-ArtCurator 31 | // 32 | // Copyright (c) Microsoft Corporation 33 | // All rights reserved. 34 | // 35 | // MIT License: 36 | // Permission is hereby granted, free of charge, to any person obtaining 37 | // a copy of this software and associated documentation files (the 38 | // "Software"), to deal in the Software without restriction, including 39 | // without limitation the rights to use, copy, modify, merge, publish, 40 | // distribute, sublicense, and/or sell copies of the Software, and to 41 | // permit persons to whom the Software is furnished to do so, subject to 42 | // the following conditions: 43 | // 44 | // The above copyright notice and this permission notice shall be 45 | // included in all copies or substantial portions of the Software. 46 | // 47 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 48 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 49 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 50 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 51 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 52 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 53 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 54 | // 55 | // ********************************************************* --------------------------------------------------------------------------------