Fehler behoben
This commit is contained in:
parent
832ebf099a
commit
b0c9541c14
628
main.go
628
main.go
@ -18,451 +18,363 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|||||||
|
|
||||||
Entwickelt mit Unterstützung von Claude.ai, einem KI-Assistenten von Anthropic, PBC.
|
Entwickelt mit Unterstützung von Claude.ai, einem KI-Assistenten von Anthropic, PBC.
|
||||||
*/
|
*/
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"crypto/md5"
|
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"encoding/xml"
|
|
||||||
"encoding/csv"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"html/template"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
|
||||||
"time"
|
"time"
|
||||||
|
"unicode"
|
||||||
|
|
||||||
"github.com/go-ldap/ldap/v3"
|
"github.com/go-ldap/ldap/v3"
|
||||||
"golang.org/x/text/encoding/charmap"
|
"gopkg.in/yaml.v2"
|
||||||
"golang.org/x/text/transform"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Config struct {
|
type Person struct {
|
||||||
LDAPServer string
|
FirstName string
|
||||||
BindDN string
|
LastName string
|
||||||
BindPassword string
|
Email string
|
||||||
SearchBase string
|
Department string
|
||||||
ServerPort string
|
Phones []Phone
|
||||||
}
|
RawPhoneNumber string
|
||||||
|
InternalPhone string
|
||||||
type AddressBook struct {
|
IsContact bool // Neues Feld zur Unterscheidung zwischen Benutzern und Kontakten
|
||||||
XMLName xml.Name `xml:"AddressBook"`
|
|
||||||
Version string `xml:"version,attr"`
|
|
||||||
PBGroups []PBGroup `xml:"pbgroup"`
|
|
||||||
Contacts []Contact `xml:"Contact"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type PBGroup struct {
|
|
||||||
ID int `xml:"id,attr"`
|
|
||||||
Name string `xml:"name"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type Contact struct {
|
|
||||||
FirstName string `xml:"FirstName"`
|
|
||||||
LastName string `xml:"LastName"`
|
|
||||||
Frequent int `xml:"Frequent"`
|
|
||||||
Phones []Phone `xml:"Phone"`
|
|
||||||
Department string `xml:"Department,omitempty"`
|
|
||||||
Group int `xml:"Group"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type Phone struct {
|
type Phone struct {
|
||||||
Type string `xml:"type,attr"`
|
PhoneNumber string
|
||||||
PhoneNumber string `xml:"phonenumber"`
|
Type string
|
||||||
AccountIndex int `xml:"accountindex"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type YealinkPhoneBook struct {
|
type Config struct {
|
||||||
XMLName xml.Name `xml:"YealinkIPPhoneDirectory"`
|
PhoneRules struct {
|
||||||
Entries []YealinkEntry `xml:"DirectoryEntry"`
|
Country struct {
|
||||||
|
Prefix string `yaml:"prefix"`
|
||||||
|
AreaCodes []string `yaml:"area_codes"`
|
||||||
|
InternalPrefix string `yaml:"internal_prefix"`
|
||||||
|
} `yaml:"country"`
|
||||||
|
InvalidNumber string `yaml:"invalid_number"`
|
||||||
|
} `yaml:"phone_rules"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type YealinkEntry struct {
|
type LDAPConfig struct {
|
||||||
Name string `xml:"Name"`
|
Server string
|
||||||
Telephone string `xml:"Telephone"`
|
Port string
|
||||||
Mobile string `xml:"Mobile,omitempty"`
|
BindDN string
|
||||||
OtherMobile string `xml:"Other,omitempty"`
|
BindPassword string
|
||||||
}
|
BaseDN string
|
||||||
|
Filter string
|
||||||
// Neue Struktur für das Contact-Format
|
|
||||||
type ContactXML struct {
|
|
||||||
XMLName xml.Name `xml:"contacts"`
|
|
||||||
Contacts []ContactEntry `xml:"contact"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type ContactEntry struct {
|
|
||||||
Name string `xml:"name,attr"`
|
|
||||||
Number string `xml:"number,attr"`
|
|
||||||
FirstName string `xml:"firstname,attr"`
|
|
||||||
LastName string `xml:"lastname,attr"`
|
|
||||||
Phone string `xml:"phone,attr"`
|
|
||||||
Mobile string `xml:"mobile,attr"`
|
|
||||||
Email string `xml:"email,attr"`
|
|
||||||
Address string `xml:"address,attr"`
|
|
||||||
City string `xml:"city,attr"`
|
|
||||||
State string `xml:"state,attr"`
|
|
||||||
Zip string `xml:"zip,attr"`
|
|
||||||
Comment string `xml:"comment,attr"`
|
|
||||||
ID string `xml:"id,attr"`
|
|
||||||
Info string `xml:"info,attr"`
|
|
||||||
Presence string `xml:"presence,attr"`
|
|
||||||
Starred string `xml:"starred,attr"`
|
|
||||||
Directory string `xml:"directory,attr"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
err error
|
cachedData []Person
|
||||||
config Config
|
lastUpdate time.Time
|
||||||
cache struct {
|
tmpl *template.Template
|
||||||
grandstreamFile *os.File
|
ldapConfig LDAPConfig
|
||||||
yealinkFile *os.File
|
serverPort string
|
||||||
contactFile *os.File
|
config Config
|
||||||
hash []byte
|
|
||||||
lastUpdate time.Time
|
|
||||||
mutex sync.RWMutex
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
loadEnvConfig()
|
||||||
|
loadYAMLConfig()
|
||||||
|
loadTemplate()
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadEnvConfig() {
|
||||||
|
requiredEnvVars := []string{
|
||||||
|
"LDAP_SERVER", "LDAP_PORT", "LDAP_BIND_DN", "LDAP_BIND_PASSWORD",
|
||||||
|
"LDAP_BASE_DN", "LDAP_FILTER", "SERVER_PORT",
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, envVar := range requiredEnvVars {
|
||||||
|
if value := os.Getenv(envVar); value == "" {
|
||||||
|
log.Fatalf("Required environment variable %s is not set", envVar)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ldapConfig = LDAPConfig{
|
||||||
|
Server: os.Getenv("LDAP_SERVER"),
|
||||||
|
Port: os.Getenv("LDAP_PORT"),
|
||||||
|
BindDN: os.Getenv("LDAP_BIND_DN"),
|
||||||
|
BindPassword: os.Getenv("LDAP_BIND_PASSWORD"),
|
||||||
|
BaseDN: os.Getenv("LDAP_BASE_DN"),
|
||||||
|
Filter: os.Getenv("LDAP_FILTER"),
|
||||||
|
}
|
||||||
|
|
||||||
|
serverPort = os.Getenv("SERVER_PORT")
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadYAMLConfig() {
|
||||||
|
configPath := filepath.Join("static", "config.yaml")
|
||||||
|
configFile, err := os.ReadFile(configPath)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to read config file: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = yaml.Unmarshal(configFile, &config)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to parse config file: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
validateConfig()
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateConfig() {
|
||||||
|
if config.PhoneRules.Country.Prefix == "" ||
|
||||||
|
len(config.PhoneRules.Country.AreaCodes) == 0 ||
|
||||||
|
config.PhoneRules.Country.InternalPrefix == "" ||
|
||||||
|
config.PhoneRules.InvalidNumber == "" {
|
||||||
|
log.Fatalf("Missing required configuration in config.yaml")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadTemplate() {
|
||||||
|
var err error
|
||||||
|
tmpl, err = template.ParseFiles(filepath.Join("static", "index.html"))
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to parse template: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
config = Config{
|
go cacheRefresher()
|
||||||
LDAPServer: os.Getenv("LDAP_SERVER"),
|
|
||||||
BindDN: os.Getenv("BIND_DN"),
|
|
||||||
BindPassword: os.Getenv("BIND_PASSWORD"),
|
|
||||||
SearchBase: os.Getenv("SEARCH_BASE"),
|
|
||||||
ServerPort: os.Getenv("SERVER_PORT"),
|
|
||||||
}
|
|
||||||
|
|
||||||
if config.ServerPort == "" {
|
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
|
||||||
config.ServerPort = "8080"
|
http.HandleFunc("/", handler)
|
||||||
}
|
|
||||||
|
|
||||||
// Initialisiere den Cache vor dem Start des Servers
|
log.Printf("Server starting on port %s", serverPort)
|
||||||
err = initializeCache()
|
log.Fatal(http.ListenAndServe(":"+serverPort, nil))
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("Fehler beim Initialisieren des Caches: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
http.HandleFunc("/phonebook.xml", grandstreamPhoneBookHandler)
|
|
||||||
http.HandleFunc("/yphonebook.xml", yealinkPhoneBookHandler)
|
|
||||||
http.HandleFunc("/Contacts.xml", contactXMLHandler)
|
|
||||||
http.HandleFunc("/phonebook.csv", csvExportHandler)
|
|
||||||
|
|
||||||
log.Printf("Server starting on port %s", config.ServerPort)
|
|
||||||
log.Fatal(http.ListenAndServe(":"+config.ServerPort, nil))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func grandstreamPhoneBookHandler(w http.ResponseWriter, r *http.Request) {
|
func cacheRefresher() {
|
||||||
servePhoneBook(w, r, cache.grandstreamFile)
|
for {
|
||||||
}
|
newData, err := fetchDataFromLDAP()
|
||||||
|
if err != nil {
|
||||||
func yealinkPhoneBookHandler(w http.ResponseWriter, r *http.Request) {
|
log.Printf("Error refreshing cache: %v", err)
|
||||||
servePhoneBook(w, r, cache.yealinkFile)
|
} else if !dataEqual(cachedData, newData) {
|
||||||
}
|
cachedData = newData
|
||||||
|
lastUpdate = time.Now()
|
||||||
func contactXMLHandler(w http.ResponseWriter, r *http.Request) {
|
log.Println("Cache updated")
|
||||||
servePhoneBook(w, r, cache.contactFile)
|
}
|
||||||
}
|
time.Sleep(5 * time.Minute)
|
||||||
|
|
||||||
func csvExportHandler(w http.ResponseWriter, r *http.Request) {
|
|
||||||
err := updateCachedXMLIfNeeded()
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Fehler beim Aktualisieren der Kontakte", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
contacts, err := getADContacts()
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Fehler beim Abrufen der Kontakte", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "text/csv; charset=windows-1252")
|
|
||||||
w.Header().Set("Content-Disposition", "attachment; filename=phonebook.csv")
|
|
||||||
|
|
||||||
if err := exportToCSV(contacts, w); err != nil {
|
|
||||||
http.Error(w, "Fehler beim Exportieren als CSV", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func servePhoneBook(w http.ResponseWriter, r *http.Request, file *os.File) {
|
func dataEqual(a, b []Person) bool {
|
||||||
err := updateCachedXMLIfNeeded()
|
if len(a) != len(b) {
|
||||||
if err != nil {
|
return false
|
||||||
http.Error(w, "Fehler beim Aktualisieren der Kontakte", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
for i := range a {
|
||||||
cache.mutex.RLock()
|
if !personEqual(a[i], b[i]) {
|
||||||
defer cache.mutex.RUnlock()
|
return false
|
||||||
|
}
|
||||||
w.Header().Set("Content-Type", "application/xml")
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
|
|
||||||
_, err = file.Seek(0, 0)
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("Fehler beim Zurücksetzen des Datei-Offsets: %v", err)
|
|
||||||
http.Error(w, "Interner Serverfehler", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = io.Copy(w, file)
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("Fehler beim Kopieren der XML-Datei: %v", err)
|
|
||||||
}
|
}
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func initializeCache() error {
|
func personEqual(a, b Person) bool {
|
||||||
log.Println("Initialisiere Cache...")
|
return a.FirstName == b.FirstName &&
|
||||||
|
a.LastName == b.LastName &&
|
||||||
// Führen Sie updateCachedXMLIfNeeded aus, um die Caching-Dateien zu erstellen
|
a.Email == b.Email &&
|
||||||
err := updateCachedXMLIfNeeded()
|
a.InternalPhone == b.InternalPhone &&
|
||||||
if err != nil {
|
a.Department == b.Department &&
|
||||||
return fmt.Errorf("Fehler beim Initialisieren des Caches: %v", err)
|
phonesEqual(a.Phones, b.Phones)
|
||||||
}
|
|
||||||
|
|
||||||
// Überprüfen Sie, ob alle erforderlichen Dateien erstellt wurden
|
|
||||||
if cache.grandstreamFile == nil || cache.yealinkFile == nil || cache.contactFile == nil {
|
|
||||||
return fmt.Errorf("Nicht alle erforderlichen Cache-Dateien wurden erstellt")
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Println("Cache erfolgreich initialisiert")
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func updateCachedXMLIfNeeded() error {
|
func phonesEqual(a, b []Phone) bool {
|
||||||
cache.mutex.Lock()
|
if len(a) != len(b) {
|
||||||
defer cache.mutex.Unlock()
|
return false
|
||||||
|
|
||||||
contacts, err := getADContacts()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
}
|
||||||
|
for i := range a {
|
||||||
newHash := calculateHash(contacts)
|
if a[i] != b[i] {
|
||||||
if cache.grandstreamFile != nil && cache.yealinkFile != nil && cache.contactFile != nil && bytes.Equal(newHash, cache.hash) {
|
return false
|
||||||
return nil
|
}
|
||||||
}
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
addressBook := AddressBook{
|
func handler(w http.ResponseWriter, r *http.Request) {
|
||||||
Version: "1.0",
|
log.Printf("Received request for: %s", r.URL.Path)
|
||||||
PBGroups: []PBGroup{
|
|
||||||
{ID: 1, Name: "Blacklist"},
|
|
||||||
{ID: 2, Name: "Work"},
|
|
||||||
{ID: 3, Name: "Friend"},
|
|
||||||
},
|
|
||||||
Contacts: contacts,
|
|
||||||
}
|
|
||||||
|
|
||||||
yealinkPhoneBook := YealinkPhoneBook{
|
if time.Since(lastUpdate) > 5*time.Minute {
|
||||||
Entries: make([]YealinkEntry, len(contacts)),
|
newData, err := fetchDataFromLDAP()
|
||||||
}
|
if err != nil {
|
||||||
|
log.Printf("Error refreshing cache: %v", err)
|
||||||
for i, c := range contacts {
|
} else {
|
||||||
yealinkPhoneBook.Entries[i] = YealinkEntry{
|
cachedData = newData
|
||||||
Name: c.FirstName + " " + c.LastName,
|
lastUpdate = time.Now()
|
||||||
Telephone: getPhoneByType(c.Phones, "Work"),
|
|
||||||
Mobile: getPhoneByType(c.Phones, "Mobile"),
|
|
||||||
OtherMobile: getPhoneByType(c.Phones, "Home"),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Erstellen der Contacts.xml
|
err := tmpl.Execute(w, cachedData)
|
||||||
contactXML := ContactXML{
|
|
||||||
Contacts: make([]ContactEntry, len(contacts)),
|
|
||||||
}
|
|
||||||
|
|
||||||
for i, c := range contacts {
|
|
||||||
contactXML.Contacts[i] = ContactEntry{
|
|
||||||
Name: c.FirstName + " " + c.LastName,
|
|
||||||
Number: getPhoneByType(c.Phones, "Work"),
|
|
||||||
FirstName: c.FirstName,
|
|
||||||
LastName: c.LastName,
|
|
||||||
Phone: getPhoneByType(c.Phones, "Work"),
|
|
||||||
Mobile: getPhoneByType(c.Phones, "Mobile"),
|
|
||||||
Presence: "0",
|
|
||||||
Starred: "0",
|
|
||||||
Directory: "0",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := saveToTempFile(&addressBook, &cache.grandstreamFile); err != nil {
|
|
||||||
return fmt.Errorf("Fehler beim Speichern der Grandstream-XML: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := saveToTempFile(&yealinkPhoneBook, &cache.yealinkFile); err != nil {
|
|
||||||
return fmt.Errorf("Fehler beim Speichern der Yealink-XML: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := saveToTempFile(&contactXML, &cache.contactFile); err != nil {
|
|
||||||
return fmt.Errorf("Fehler beim Speichern der Contact-XML: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
csvFile, err := os.OpenFile("phonebook.csv", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("Fehler beim Erstellen der CSV-Datei: %v", err)
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
}
|
}
|
||||||
defer csvFile.Close()
|
|
||||||
|
|
||||||
if err := exportToCSV(contacts, csvFile); err != nil {
|
|
||||||
return fmt.Errorf("Fehler beim Exportieren als CSV: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
cache.hash = newHash
|
|
||||||
cache.lastUpdate = time.Now()
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func saveToTempFile(data interface{}, file **os.File) error {
|
func fetchDataFromLDAP() ([]Person, error) {
|
||||||
tempFile, err := os.CreateTemp("", "phonebook_*.xml")
|
l, err := ldap.DialTLS("tcp", ldapConfig.Server+":"+ldapConfig.Port, &tls.Config{InsecureSkipVerify: true})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("Fehler beim Erstellen der temporären Datei: %v", err)
|
return nil, fmt.Errorf("failed to connect to LDAP server: %v", err)
|
||||||
}
|
|
||||||
|
|
||||||
enc := xml.NewEncoder(tempFile)
|
|
||||||
enc.Indent("", " ")
|
|
||||||
if err := enc.Encode(data); err != nil {
|
|
||||||
tempFile.Close()
|
|
||||||
os.Remove(tempFile.Name())
|
|
||||||
return fmt.Errorf("Fehler beim Kodieren der XML: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if *file != nil {
|
|
||||||
(*file).Close()
|
|
||||||
os.Remove((*file).Name())
|
|
||||||
}
|
|
||||||
|
|
||||||
*file = tempFile
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func calculateHash(contacts []Contact) []byte {
|
|
||||||
h := md5.New()
|
|
||||||
for _, contact := range contacts {
|
|
||||||
io.WriteString(h, contact.FirstName)
|
|
||||||
io.WriteString(h, contact.LastName)
|
|
||||||
for _, phone := range contact.Phones {
|
|
||||||
io.WriteString(h, phone.PhoneNumber)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return h.Sum(nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
func getADContacts() ([]Contact, error) {
|
|
||||||
l, err := ldap.DialTLS("tcp", config.LDAPServer+":636", &tls.Config{InsecureSkipVerify: true})
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("LDAP-Verbindung fehlgeschlagen: %v", err)
|
|
||||||
}
|
}
|
||||||
defer l.Close()
|
defer l.Close()
|
||||||
|
|
||||||
err = l.Bind(config.BindDN, config.BindPassword)
|
err = l.Bind(ldapConfig.BindDN, ldapConfig.BindPassword)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("LDAP-Bindung fehlgeschlagen: %v", err)
|
return nil, fmt.Errorf("failed to bind to LDAP server: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Erweiterter LDAP-Filter für Benutzer und Kontakte
|
// Erweitere den Filter, um sowohl Benutzer als auch Kontakte einzuschließen
|
||||||
searchFilter := "(&(|(objectClass=user)(objectClass=contact))(|(telephoneNumber=*)(otherTelephone=*)(mobile=*)(homePhone=*))(!(userAccountControl:1.2.840.113556.1.4.803:=2)))"
|
combinedFilter := fmt.Sprintf("(|(objectClass=user)(objectClass=contact)%s)", ldapConfig.Filter)
|
||||||
|
|
||||||
searchRequest := ldap.NewSearchRequest(
|
searchRequest := ldap.NewSearchRequest(
|
||||||
config.SearchBase,
|
ldapConfig.BaseDN,
|
||||||
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
|
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
|
||||||
searchFilter,
|
combinedFilter,
|
||||||
[]string{"givenName", "sn", "displayName", "telephoneNumber", "otherTelephone", "mobile", "homePhone"},
|
[]string{"objectClass", "givenName", "sn", "mail", "telephoneNumber", "mobile", "otherTelephone", "physicalDeliveryOfficeName"},
|
||||||
nil,
|
nil,
|
||||||
)
|
)
|
||||||
|
|
||||||
sr, err := l.Search(searchRequest)
|
sr, err := l.Search(searchRequest)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("LDAP-Suche fehlgeschlagen: %v", err)
|
return nil, fmt.Errorf("failed to search LDAP server: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
var contacts []Contact
|
var people []Person
|
||||||
for _, entry := range sr.Entries {
|
for _, entry := range sr.Entries {
|
||||||
firstName := entry.GetAttributeValue("givenName")
|
if !isValidEntry(entry) {
|
||||||
lastName := entry.GetAttributeValue("sn")
|
|
||||||
|
|
||||||
if firstName == "" || lastName == "" {
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
phone := formatPhoneNumber(entry.GetAttributeValue("telephoneNumber"))
|
isContact := isContactObject(entry)
|
||||||
otherMobile := formatPhoneNumber(entry.GetAttributeValue("otherMobile"))
|
|
||||||
mobile := formatPhoneNumber(entry.GetAttributeValue("mobile"))
|
|
||||||
|
|
||||||
if isExcludedNumber(phone) || isExcludedNumber(otherMobile) || isExcludedNumber(mobile) {
|
person := Person{
|
||||||
continue
|
FirstName: entry.GetAttributeValue("givenName"),
|
||||||
|
LastName: entry.GetAttributeValue("sn"),
|
||||||
|
Email: entry.GetAttributeValue("mail"),
|
||||||
|
Department: entry.GetAttributeValue("physicalDeliveryOfficeName"),
|
||||||
|
IsContact: isContact,
|
||||||
}
|
}
|
||||||
|
|
||||||
if phone != "" || otherMobile != "" || mobile != "" {
|
officePhone := entry.GetAttributeValue("telephoneNumber")
|
||||||
contact := Contact{
|
mobilePhone := entry.GetAttributeValue("mobile")
|
||||||
FirstName: firstName,
|
|
||||||
LastName: lastName,
|
// Normalisiere die Telefonnummern für den Vergleich
|
||||||
Phones: []Phone{},
|
normalizedOffice := normalizePhoneNumber(officePhone)
|
||||||
Group: 2, // Standardmäßig zur "Work"-Gruppe hinzufügen
|
normalizedMobile := normalizePhoneNumber(mobilePhone)
|
||||||
|
|
||||||
|
if normalizedOffice == normalizedMobile && mobilePhone != "" {
|
||||||
|
formattedMobile := formatPhoneNumber(mobilePhone)
|
||||||
|
person.Phones = append(person.Phones, Phone{PhoneNumber: formattedMobile, Type: "Mobil"})
|
||||||
|
person.RawPhoneNumber = formattedMobile
|
||||||
|
person.InternalPhone = "" // Keine interne Rufnummer für Mobiltelefone
|
||||||
|
} else if officePhone != "" {
|
||||||
|
formattedPhone := formatPhoneNumber(officePhone)
|
||||||
|
person.Phones = append(person.Phones, Phone{PhoneNumber: formattedPhone, Type: "Office"})
|
||||||
|
person.InternalPhone = extractInternalNumber(officePhone)
|
||||||
|
person.RawPhoneNumber = formattedPhone
|
||||||
|
|
||||||
|
if mobilePhone != "" && normalizedOffice != normalizedMobile {
|
||||||
|
formattedMobile := formatPhoneNumber(mobilePhone)
|
||||||
|
person.Phones = append(person.Phones, Phone{PhoneNumber: formattedMobile, Type: "Mobil"})
|
||||||
}
|
}
|
||||||
if phone != "" {
|
} else if mobilePhone != "" {
|
||||||
contact.Phones = append(contact.Phones, Phone{Type: "Work", PhoneNumber: phone, AccountIndex: 0})
|
formattedMobile := formatPhoneNumber(mobilePhone)
|
||||||
}
|
person.Phones = append(person.Phones, Phone{PhoneNumber: formattedMobile, Type: "Mobil"})
|
||||||
if mobile != "" {
|
person.RawPhoneNumber = formattedMobile
|
||||||
contact.Phones = append(contact.Phones, Phone{Type: "Mobile", PhoneNumber: mobile, AccountIndex: 0})
|
person.InternalPhone = "" // Keine interne Rufnummer für Mobiltelefone
|
||||||
}
|
}
|
||||||
if otherMobile != "" {
|
|
||||||
contact.Phones = append(contact.Phones, Phone{Type: "Home", PhoneNumber: otherMobile, AccountIndex: 0})
|
for _, otherPhone := range entry.GetAttributeValues("otherTelephone") {
|
||||||
}
|
person.Phones = append(person.Phones, Phone{PhoneNumber: formatPhoneNumber(otherPhone), Type: "Other"})
|
||||||
contacts = append(contacts, contact)
|
}
|
||||||
|
|
||||||
|
if (len(person.Phones) > 0 && person.Email != "") || isContact {
|
||||||
|
people = append(people, person)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return contacts, nil
|
return people, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func removeDuplicateNumbers(phones []Phone) []Phone {
|
func isValidEntry(entry *ldap.Entry) bool {
|
||||||
seen := make(map[string]bool)
|
firstName := entry.GetAttributeValue("givenName")
|
||||||
result := []Phone{}
|
lastName := entry.GetAttributeValue("sn")
|
||||||
|
telephoneNumber := entry.GetAttributeValue("telephoneNumber")
|
||||||
|
mobile := entry.GetAttributeValue("mobile")
|
||||||
|
|
||||||
for _, phone := range phones {
|
// Für Kontakte erlauben wir auch Einträge ohne Telefonnummer
|
||||||
if !seen[phone.PhoneNumber] {
|
isContact := isContactObject(entry)
|
||||||
seen[phone.PhoneNumber] = true
|
|
||||||
result = append(result, phone)
|
|
||||||
} else if phone.Type == "Work" {
|
|
||||||
// Wenn die Nummer bereits gesehen wurde und dies die "Work" Nummer ist,
|
|
||||||
// ersetzen wir die vorherige (wahrscheinlich "Mobile") mit dieser.
|
|
||||||
for i, p := range result {
|
|
||||||
if p.PhoneNumber == phone.PhoneNumber {
|
|
||||||
result[i] = phone
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return result
|
return (firstName != "" && lastName != "") &&
|
||||||
|
(isContact || telephoneNumber != config.PhoneRules.InvalidNumber || mobile != "")
|
||||||
}
|
}
|
||||||
|
|
||||||
func isExcludedNumber(number string) bool {
|
func isContactObject(entry *ldap.Entry) bool {
|
||||||
excludedNumbers := []string{
|
objectClasses := entry.GetAttributeValues("objectClass")
|
||||||
"+49 5331 89",
|
for _, class := range objectClasses {
|
||||||
"+49533189",
|
if strings.ToLower(class) == "contact" {
|
||||||
"+ 49 5331 89",
|
|
||||||
}
|
|
||||||
|
|
||||||
// Zuerst prüfen wir auf die ausgeschlossenen Nummern
|
|
||||||
for _, excluded := range excludedNumbers {
|
|
||||||
if strings.Contains(number, excluded) {
|
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dann prüfen wir, ob die Nummer mit "089" endet
|
|
||||||
if len(number) >= 3 && number[len(number)-3:] == "089" {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// Wenn keine der obigen Bedingungen zutrifft, ist die Nummer nicht ausgeschlossen
|
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func
|
func isValidContact(entry *ldap.Entry) bool {
|
||||||
|
firstName := entry.GetAttributeValue("givenName")
|
||||||
|
lastName := entry.GetAttributeValue("sn")
|
||||||
|
telephoneNumber := entry.GetAttributeValue("telephoneNumber")
|
||||||
|
|
||||||
|
return firstName != "" && lastName != "" && telephoneNumber != config.PhoneRules.InvalidNumber
|
||||||
|
}
|
||||||
|
|
||||||
|
func formatPhoneNumber(number string) string {
|
||||||
|
// Entferne alle Nicht-Ziffern
|
||||||
|
digits := strings.Map(func(r rune) rune {
|
||||||
|
if unicode.IsDigit(r) {
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
return -1
|
||||||
|
}, number)
|
||||||
|
|
||||||
|
// Entferne führende Nullen
|
||||||
|
digits = strings.TrimLeft(digits, "0")
|
||||||
|
|
||||||
|
// Entferne den Länderprefix, falls vorhanden
|
||||||
|
countryPrefix := config.PhoneRules.Country.Prefix
|
||||||
|
if strings.HasPrefix(digits, countryPrefix) {
|
||||||
|
digits = digits[len(countryPrefix):]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Füge eine führende "0" hinzu, wenn nicht vorhanden
|
||||||
|
if !strings.HasPrefix(digits, "0") {
|
||||||
|
digits = "0" + digits
|
||||||
|
}
|
||||||
|
|
||||||
|
return digits
|
||||||
|
}
|
||||||
|
|
||||||
|
func extractInternalNumber(phoneNumber string) string {
|
||||||
|
digits := formatPhoneNumber(phoneNumber)
|
||||||
|
|
||||||
|
for _, areaCode := range config.PhoneRules.Country.AreaCodes {
|
||||||
|
if strings.HasPrefix(digits[1:], areaCode) { // Ignoriere die führende 0
|
||||||
|
remaining := digits[1+len(areaCode):]
|
||||||
|
if strings.HasPrefix(remaining, config.PhoneRules.Country.InternalPrefix) {
|
||||||
|
return remaining[len(config.PhoneRules.Country.InternalPrefix):]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizePhoneNumber(number string) string {
|
||||||
|
return formatPhoneNumber(number)
|
||||||
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user